chore: 初始化仓库,导入项目基线代码
Academy v0.8.3 完整代码基线:Go 后端(internal/cmd/cli/mcp-server/docreader)、 Vue 前端(frontend)、数据库迁移(migrations)、部署编排(docker/helm/deploy)与文档。 今日开发的培训推送管理改动随后单独提交。
This commit is contained in:
commit
7ec21f35b0
5767 files changed
+1436788
No files matched your search
@@ -0,0 +1,755 @@
|
||||
// Package hitl coordinates human-in-the-loop prompts raised by agent runs:
|
||||
// tool approvals, in-conversation authorizations, questions for the user.
|
||||
//
|
||||
// The prompt row in Store is the source of truth for every answer. The
|
||||
// replica that raised a prompt keeps an in-memory waiter only as a wake-up
|
||||
// hook: Resolve records the answer with a compare-and-set, then wakes the
|
||||
// waiter locally or over Redis pub/sub, and the waiter also polls the row in
|
||||
// case a wake-up is lost. Kind-specific behaviour (request/response shape and
|
||||
// validation) is registered per kind; the broker never interprets payloads.
|
||||
package hitl
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"academy/internal/config"
|
||||
"academy/internal/logger"
|
||||
"academy/internal/types"
|
||||
"github.com/google/uuid"
|
||||
"github.com/redis/go-redis/v9"
|
||||
)
|
||||
|
||||
// pubsubChannelBase is the Redis channel prefix used to wake the replica that
|
||||
// holds a waiter after another replica recorded the answer. The actual
|
||||
// channel is suffixed with ACADEMY_REDIS_NAMESPACE (when set) so multiple
|
||||
// deployments sharing the same Redis don't cross-talk.
|
||||
const pubsubChannelBase = "academy:agent_prompt:wake"
|
||||
|
||||
// instanceID identifies this process for pub/sub wake-up suppression.
|
||||
var instanceID = uuid.New().String()
|
||||
|
||||
// Timing of the owner-side wait loop. The poll covers lost pub/sub wake-ups;
|
||||
// the lease lets other replicas notice an owner that disappeared.
|
||||
const (
|
||||
defaultPollInterval = 3 * time.Second
|
||||
defaultLeaseTTL = 30 * time.Second
|
||||
defaultRenewInterval = 10 * time.Second
|
||||
)
|
||||
|
||||
// consumeRetryDelays spaces the retries of a Consume the store failed to record.
|
||||
var consumeRetryDelays = []time.Duration{100 * time.Millisecond, 400 * time.Millisecond}
|
||||
|
||||
var (
|
||||
// ErrPromptNotFound is returned when Resolve targets an unknown prompt,
|
||||
// or one outside the caller's session or kind.
|
||||
ErrPromptNotFound = errors.New("agent prompt not found")
|
||||
// ErrTenantMismatch is returned when the caller's tenant does not own the prompt.
|
||||
ErrTenantMismatch = errors.New("workspace mismatch for agent prompt")
|
||||
// ErrUserMismatch is returned when the caller does not own the session.
|
||||
ErrUserMismatch = errors.New("user mismatch for agent prompt")
|
||||
// ErrAlreadyResolved is returned when the prompt was already answered or
|
||||
// ended by timeout / cancellation.
|
||||
ErrAlreadyResolved = errors.New("agent prompt already resolved")
|
||||
// ErrInvalidResponse wraps a kind validator's rejection of an answer.
|
||||
ErrInvalidResponse = errors.New("invalid agent prompt response")
|
||||
)
|
||||
|
||||
// ResponseValidator checks an answer against the prompt that asked for it.
|
||||
type ResponseValidator func(request, response json.RawMessage) error
|
||||
|
||||
// Outcome is how an awaited prompt ended. Prompt is the row as last read.
|
||||
type Outcome struct {
|
||||
Prompt *types.AgentPrompt
|
||||
// Answered means the user responded; Prompt.Response holds the answer.
|
||||
Answered bool
|
||||
TimedOut bool
|
||||
Canceled bool
|
||||
// Suspended means the prompt outlived the in-memory wait: the run must
|
||||
// end now and be resumed once the prompt is answered.
|
||||
Suspended bool
|
||||
// Detached means another owner already took over this run. The old
|
||||
// waiter must exit without publishing or persisting completion.
|
||||
Detached bool
|
||||
ExpiresAt *time.Time
|
||||
Reason string
|
||||
}
|
||||
|
||||
// Spec describes a prompt to raise and wait on.
|
||||
type Spec struct {
|
||||
// Prompt carries kind, scope and request. Status, ownership and lease are
|
||||
// filled in by Await; an empty ID is generated.
|
||||
Prompt *types.AgentPrompt
|
||||
Timeout time.Duration
|
||||
TimeoutReason string
|
||||
// Emit notifies the UI. It runs after the row is persisted and the
|
||||
// waiter is registered, so an immediate answer is never missed.
|
||||
Emit func(ctx context.Context, prompt *types.AgentPrompt) error
|
||||
// Suspend makes the prompt suspendable: when Timeout elapses the run is
|
||||
// suspended instead of the prompt expiring. Nil keeps a plain wait.
|
||||
Suspend *SuspendSpec
|
||||
// FallbackTimeout, when set, turns a suspendable prompt whose run state
|
||||
// cannot be saved into a plain wait of this length instead of failing.
|
||||
// Emit sees the downgrade as Prompt.Suspendable == false.
|
||||
FallbackTimeout time.Duration
|
||||
}
|
||||
|
||||
// SuspendSpec carries the run state saved with a suspendable prompt. It is
|
||||
// written before the prompt is raised, so a replica that dies while waiting
|
||||
// still leaves a resumable run behind.
|
||||
type SuspendSpec struct {
|
||||
Snapshot []byte
|
||||
SnapshotVersion int
|
||||
}
|
||||
|
||||
// ResolveRequest is a user answer to a prompt. SessionID and Kind, when set,
|
||||
// must match the prompt; a mismatch reads as not found so callers cannot
|
||||
// probe prompts outside the session or surface they are authorized for.
|
||||
type ResolveRequest struct {
|
||||
TenantID uint64
|
||||
UserID string
|
||||
SessionID string
|
||||
Kind string
|
||||
PromptID string
|
||||
Response json.RawMessage
|
||||
}
|
||||
|
||||
// Broker raises, awaits and resolves prompts.
|
||||
type Broker struct {
|
||||
store Store
|
||||
suspensions SuspensionStore
|
||||
rdb *redis.Client
|
||||
|
||||
mu sync.Mutex
|
||||
waiters map[string]chan struct{}
|
||||
validators map[string]ResponseValidator
|
||||
|
||||
pollInterval time.Duration
|
||||
leaseTTL time.Duration
|
||||
renewInterval time.Duration
|
||||
// suspendExpiry bounds how long a suspended prompt stays answerable;
|
||||
// zero never expires.
|
||||
suspendExpiry time.Duration
|
||||
// runHooks finish the message of a run Resolve takes over from an owner
|
||||
// that stopped renewing its lease; see SetRunHooks.
|
||||
runHooks RunHooks
|
||||
}
|
||||
|
||||
// SetRunHooks installs the hooks Resolve uses when it suspends a prompt on
|
||||
// behalf of an owner that disappeared, as the reaper would.
|
||||
func (b *Broker) SetRunHooks(h RunHooks) {
|
||||
b.mu.Lock()
|
||||
defer b.mu.Unlock()
|
||||
b.runHooks = h
|
||||
}
|
||||
|
||||
func (b *Broker) hooks() RunHooks {
|
||||
b.mu.Lock()
|
||||
defer b.mu.Unlock()
|
||||
return b.runHooks
|
||||
}
|
||||
|
||||
// Option customizes a Broker.
|
||||
type Option func(*Broker)
|
||||
|
||||
// WithPollInterval overrides how often a waiter re-reads its row.
|
||||
func WithPollInterval(d time.Duration) Option {
|
||||
return func(b *Broker) {
|
||||
if d > 0 {
|
||||
b.pollInterval = d
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// WithSuspensionStore sets where suspendable prompts save their run state.
|
||||
func WithSuspensionStore(s SuspensionStore) Option {
|
||||
return func(b *Broker) {
|
||||
if s != nil {
|
||||
b.suspensions = s
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// WithSuspendExpiry sets how long a suspended prompt stays answerable; zero
|
||||
// never expires.
|
||||
func WithSuspendExpiry(d time.Duration) Option {
|
||||
return func(b *Broker) { b.suspendExpiry = d }
|
||||
}
|
||||
|
||||
// withLease shortens lease timing for tests.
|
||||
func withLease(ttl, renew time.Duration) Option {
|
||||
return func(b *Broker) { b.leaseTTL, b.renewInterval = ttl, renew }
|
||||
}
|
||||
|
||||
// NewBroker builds a broker. store may be nil (process memory; single
|
||||
// replica only). rdb may be nil (no cross-instance wake-ups; waiters still
|
||||
// observe answers by polling the store).
|
||||
func NewBroker(store Store, rdb *redis.Client, opts ...Option) *Broker {
|
||||
if store == nil {
|
||||
store = NewMemoryStore()
|
||||
}
|
||||
b := &Broker{
|
||||
store: store,
|
||||
suspensions: NewMemorySuspensionStore(),
|
||||
rdb: rdb,
|
||||
waiters: make(map[string]chan struct{}),
|
||||
validators: make(map[string]ResponseValidator),
|
||||
pollInterval: defaultPollInterval,
|
||||
leaseTTL: defaultLeaseTTL,
|
||||
renewInterval: defaultRenewInterval,
|
||||
suspendExpiry: config.DefaultPromptExpire,
|
||||
}
|
||||
for _, opt := range opts {
|
||||
opt(b)
|
||||
}
|
||||
if rdb != nil {
|
||||
go b.runSubscriber()
|
||||
}
|
||||
return b
|
||||
}
|
||||
|
||||
// Store exposes the backing store to kind adapters and tests.
|
||||
func (b *Broker) Store() Store { return b.store }
|
||||
|
||||
// Suspensions exposes the run-state store.
|
||||
func (b *Broker) Suspensions() SuspensionStore { return b.suspensions }
|
||||
|
||||
// SessionPrompts lists the session's prompts in the given statuses, oldest
|
||||
// first.
|
||||
func (b *Broker) SessionPrompts(
|
||||
ctx context.Context, sessionID string, statuses []string,
|
||||
) ([]*types.AgentPrompt, error) {
|
||||
return b.store.ListBySession(ctx, sessionID, statuses)
|
||||
}
|
||||
|
||||
// RegisterKind installs the answer validator for kind. Resolve rejects
|
||||
// answers to kinds without a validator.
|
||||
func (b *Broker) RegisterKind(kind string, validate ResponseValidator) {
|
||||
b.mu.Lock()
|
||||
defer b.mu.Unlock()
|
||||
b.validators[kind] = validate
|
||||
}
|
||||
|
||||
// Await persists the prompt as pending and owned by this process, emits it,
|
||||
// and blocks until it is answered, the timeout elapses, or ctx ends. The
|
||||
// outcome always reflects the row's final state, so an answer that lands
|
||||
// concurrently with a timeout or cancellation is never lost.
|
||||
//
|
||||
// A suspendable prompt's run state is kept only while the run may still be
|
||||
// resumed from it: it is dropped when the prompt ends any other way.
|
||||
func (b *Broker) Await(ctx context.Context, spec Spec) (out Outcome, err error) {
|
||||
p := spec.Prompt
|
||||
if p == nil {
|
||||
return Outcome{}, errors.New("agent prompt: nil prompt")
|
||||
}
|
||||
if p.ID == "" {
|
||||
p.ID = uuid.New().String()
|
||||
}
|
||||
delegation, delegated := ctx.Value(delegationKey{}).(Delegation)
|
||||
if delegated {
|
||||
if err := CheckDelegation(ctx); err != nil {
|
||||
return Outcome{}, err
|
||||
}
|
||||
if spec.Suspend == nil {
|
||||
return Outcome{}, errors.New("delegated prompts require a durable snapshot")
|
||||
}
|
||||
// Persist or fail closed; a worker must never silently become a hot waiter.
|
||||
spec.FallbackTimeout = 0
|
||||
spec.Timeout = 0
|
||||
}
|
||||
dbCtx := context.WithoutCancel(ctx)
|
||||
// A fresh token also fences a takeover by another run on this same replica.
|
||||
owner := uuid.NewString()
|
||||
if spec.Suspend != nil {
|
||||
if p.AssistantMessageID == "" {
|
||||
return Outcome{}, errors.New("agent prompt: a suspendable prompt needs an assistant message")
|
||||
}
|
||||
p.Suspendable = true
|
||||
err := b.suspensions.Save(dbCtx, &types.AgentRunSuspension{
|
||||
AssistantMessageID: p.AssistantMessageID,
|
||||
TenantID: p.TenantID,
|
||||
SessionID: p.SessionID,
|
||||
PromptID: p.ID,
|
||||
SnapshotVersion: spec.Suspend.SnapshotVersion,
|
||||
Snapshot: types.JSON(spec.Suspend.Snapshot),
|
||||
})
|
||||
switch {
|
||||
case err == nil:
|
||||
defer func() {
|
||||
if !out.Suspended {
|
||||
row, readErr := b.store.Get(dbCtx, p.ID)
|
||||
if readErr == nil && (row == nil || row.OwnerInstance == owner) {
|
||||
b.dropSnapshot(dbCtx, p.AssistantMessageID, p.ID)
|
||||
}
|
||||
}
|
||||
}()
|
||||
case spec.FallbackTimeout > 0:
|
||||
logger.GetLogger(ctx).Warnf("persist run state of prompt %s, waiting in memory instead: %v", p.ID, err)
|
||||
spec.Suspend, spec.Timeout, p.Suspendable = nil, spec.FallbackTimeout, false
|
||||
default:
|
||||
return Outcome{}, fmt.Errorf("persist run state: %w", err)
|
||||
}
|
||||
}
|
||||
if delegated && delegation.Register != nil {
|
||||
if err := delegation.Register(ctx, p); err != nil {
|
||||
return Outcome{}, err
|
||||
}
|
||||
}
|
||||
lease := time.Now().Add(b.leaseTTL)
|
||||
p.Status = types.AgentPromptPending
|
||||
p.OwnerInstance = owner
|
||||
p.LeaseUntil = &lease
|
||||
if err := b.store.Create(dbCtx, p); err != nil {
|
||||
return Outcome{}, fmt.Errorf("persist agent prompt: %w", err)
|
||||
}
|
||||
|
||||
wake := b.register(p.ID)
|
||||
defer b.unregister(p.ID)
|
||||
|
||||
if spec.Emit != nil {
|
||||
if err := spec.Emit(ctx, p); err != nil {
|
||||
b.closeAsOwner(dbCtx, p.ID, owner, types.AgentPromptCanceled, "prompt could not be delivered")
|
||||
return Outcome{}, fmt.Errorf("emit agent prompt: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
timer := time.NewTimer(spec.Timeout)
|
||||
defer timer.Stop()
|
||||
poll := time.NewTicker(b.pollInterval)
|
||||
defer poll.Stop()
|
||||
renew := time.NewTicker(b.renewInterval)
|
||||
defer renew.Stop()
|
||||
|
||||
for {
|
||||
select {
|
||||
case <-wake:
|
||||
if out, ok := b.closed(dbCtx, p.ID, owner); ok {
|
||||
return out, nil
|
||||
}
|
||||
case <-poll.C:
|
||||
if out, ok := b.closed(dbCtx, p.ID, owner); ok {
|
||||
return out, nil
|
||||
}
|
||||
case <-renew.C:
|
||||
if _, err := b.store.RenewLease(dbCtx, p.ID, owner, time.Now().Add(b.leaseTTL)); err != nil {
|
||||
logger.GetLogger(ctx).Warnf("renew agent prompt lease %s: %v", p.ID, err)
|
||||
}
|
||||
case <-timer.C:
|
||||
if spec.Suspend != nil {
|
||||
return b.suspend(dbCtx, p.ID, owner), nil
|
||||
}
|
||||
return b.closeAsOwner(dbCtx, p.ID, owner, types.AgentPromptExpired, spec.TimeoutReason), nil
|
||||
case <-ctx.Done():
|
||||
return b.closeAsOwner(dbCtx, p.ID, owner, types.AgentPromptCanceled, "request canceled"), nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// suspend moves a pending prompt to suspended. When an answer won the race,
|
||||
// that answer is returned instead.
|
||||
func (b *Broker) suspend(ctx context.Context, id, owner string) Outcome {
|
||||
expiresAt := b.expiresAt(time.Now())
|
||||
ok, err := b.store.Transition(ctx, id, types.AgentPromptTransition{
|
||||
From: []string{types.AgentPromptPending},
|
||||
To: types.AgentPromptSuspended,
|
||||
ExpiresAt: expiresAt,
|
||||
ExpectedOwner: &owner,
|
||||
})
|
||||
if err != nil {
|
||||
logger.GetLogger(ctx).Warnf("suspend agent prompt %s: %v", id, err)
|
||||
}
|
||||
if !ok {
|
||||
if out, closed := b.closed(ctx, id, owner); closed {
|
||||
return out
|
||||
}
|
||||
// The row could not be read or moved; fail the prompt rather than
|
||||
// leave a run suspended on state nobody can confirm.
|
||||
return b.closeAsOwner(ctx, id, owner, types.AgentPromptExpired, "prompt could not be suspended")
|
||||
}
|
||||
return Outcome{
|
||||
Prompt: &types.AgentPrompt{ID: id, Status: types.AgentPromptSuspended, ExpiresAt: expiresAt},
|
||||
Suspended: true,
|
||||
ExpiresAt: expiresAt,
|
||||
}
|
||||
}
|
||||
|
||||
func (b *Broker) expiresAt(now time.Time) *time.Time {
|
||||
if b.suspendExpiry <= 0 {
|
||||
return nil
|
||||
}
|
||||
at := now.Add(b.suspendExpiry)
|
||||
return &at
|
||||
}
|
||||
|
||||
func (b *Broker) dropSnapshot(ctx context.Context, messageID, promptID string) {
|
||||
if err := b.suspensions.Delete(ctx, messageID, promptID); err != nil {
|
||||
logger.GetLogger(ctx).Warnf("drop run state of message %s: %v", messageID, err)
|
||||
}
|
||||
}
|
||||
|
||||
// closeAsOwner ends a pending prompt from the waiting side. When an answer
|
||||
// won the race, that answer is returned instead.
|
||||
func (b *Broker) closeAsOwner(ctx context.Context, id, owner, status, reason string) Outcome {
|
||||
ok, err := b.store.Transition(ctx, id, types.AgentPromptTransition{
|
||||
From: []string{types.AgentPromptPending},
|
||||
To: status,
|
||||
CloseReason: &reason,
|
||||
ExpectedOwner: &owner,
|
||||
})
|
||||
if err != nil {
|
||||
logger.GetLogger(ctx).Warnf("close agent prompt %s as %s: %v", id, status, err)
|
||||
}
|
||||
if !ok {
|
||||
if out, closed := b.closed(ctx, id, owner); closed {
|
||||
return out
|
||||
}
|
||||
}
|
||||
return Outcome{
|
||||
Prompt: &types.AgentPrompt{ID: id, Status: status, CloseReason: reason},
|
||||
TimedOut: status == types.AgentPromptExpired,
|
||||
Canceled: status == types.AgentPromptCanceled,
|
||||
Reason: reason,
|
||||
}
|
||||
}
|
||||
|
||||
// closed reads the row and reports its outcome once the owner should stop
|
||||
// waiting: the prompt ended, or another replica suspended it after this
|
||||
// owner's lease lapsed.
|
||||
func (b *Broker) closed(ctx context.Context, id, owner string) (Outcome, bool) {
|
||||
row, err := b.store.Get(ctx, id)
|
||||
if err != nil {
|
||||
logger.GetLogger(ctx).Warnf("read agent prompt %s: %v", id, err)
|
||||
return Outcome{}, false
|
||||
}
|
||||
if row == nil || row.Status == types.AgentPromptPending {
|
||||
return Outcome{}, false
|
||||
}
|
||||
if row.OwnerInstance != owner {
|
||||
return Outcome{Prompt: row, Suspended: true, Detached: true, ExpiresAt: row.ExpiresAt}, true
|
||||
}
|
||||
if row.Status == types.AgentPromptSuspended {
|
||||
return Outcome{Prompt: row, Suspended: true, ExpiresAt: row.ExpiresAt}, true
|
||||
}
|
||||
return Outcome{
|
||||
Prompt: row,
|
||||
Answered: row.Status == types.AgentPromptAnswered,
|
||||
TimedOut: row.Status == types.AgentPromptExpired,
|
||||
Canceled: row.Status == types.AgentPromptCanceled,
|
||||
Reason: row.CloseReason,
|
||||
}, true
|
||||
}
|
||||
|
||||
// Consume claims an answered prompt before its owner acts on it:
|
||||
// AgentPromptExecuting when the answer authorized a side effect still to run,
|
||||
// AgentPromptDone otherwise. Only the winner may continue the run.
|
||||
// Prompts closed by the system are left alone.
|
||||
//
|
||||
// A storage error is distinct from a lost claim: callers must fail the tool
|
||||
// without detaching the run, so ordinary completion can persist its message.
|
||||
// Neither outcome permits executing the authorized side effect.
|
||||
func (b *Broker) Consume(ctx context.Context, id, to, owner string) (bool, error) {
|
||||
if err := CheckDelegation(ctx); err != nil {
|
||||
return false, err
|
||||
}
|
||||
ctx = context.WithoutCancel(ctx)
|
||||
transition := types.AgentPromptTransition{
|
||||
From: []string{types.AgentPromptAnswered},
|
||||
To: to,
|
||||
ExpectedOwner: &owner,
|
||||
}
|
||||
var lastErr error
|
||||
for attempt := 0; ; attempt++ {
|
||||
ok, err := b.store.Transition(ctx, id, transition)
|
||||
if err == nil && (ok || attempt == 0) {
|
||||
return ok, nil
|
||||
}
|
||||
if err == nil {
|
||||
// An earlier attempt may have committed before failing.
|
||||
break
|
||||
}
|
||||
lastErr = err
|
||||
if attempt == len(consumeRetryDelays) {
|
||||
break
|
||||
}
|
||||
time.Sleep(consumeRetryDelays[attempt])
|
||||
}
|
||||
row, readErr := b.store.Get(ctx, id)
|
||||
if readErr == nil {
|
||||
if row == nil || row.OwnerInstance != owner {
|
||||
return false, nil
|
||||
}
|
||||
if row.Status == to {
|
||||
return true, nil
|
||||
}
|
||||
if row.Status != types.AgentPromptAnswered {
|
||||
return false, nil
|
||||
}
|
||||
}
|
||||
// We could not confirm a durable claim. Close only this owner's prompt;
|
||||
// a concurrent takeover must not be canceled by the stale caller.
|
||||
reason := "could not persist prompt consumption; tool was not executed"
|
||||
_, closeErr := b.store.Transition(ctx, id, types.AgentPromptTransition{
|
||||
From: []string{types.AgentPromptAnswered, types.AgentPromptExecuting},
|
||||
To: types.AgentPromptFailed,
|
||||
ExpectedOwner: &owner,
|
||||
CloseReason: &reason,
|
||||
})
|
||||
err := fmt.Errorf("consume agent prompt %s: %w", id, errors.Join(lastErr, readErr, closeErr))
|
||||
logger.GetLogger(ctx).Warnf("%v", err)
|
||||
return false, err
|
||||
}
|
||||
|
||||
// MarkExecuted records that the side effect an answer authorized has run.
|
||||
func (b *Broker) MarkExecuted(ctx context.Context, id string) {
|
||||
if id == "" {
|
||||
return
|
||||
}
|
||||
_, err := b.store.Transition(context.WithoutCancel(ctx), id, types.AgentPromptTransition{
|
||||
From: []string{types.AgentPromptExecuting},
|
||||
To: types.AgentPromptDone,
|
||||
})
|
||||
if err != nil {
|
||||
logger.GetLogger(ctx).Warnf("mark agent prompt %s executed: %v", id, err)
|
||||
}
|
||||
}
|
||||
|
||||
// Resolution is the result of a recorded answer.
|
||||
type Resolution struct {
|
||||
// Prompt is the answered row.
|
||||
Prompt *types.AgentPrompt
|
||||
// Resume means the prompt was suspended: its run has ended and the
|
||||
// caller must resume it. This replica now holds the prompt's lease; see
|
||||
// KeepLease.
|
||||
Resume bool
|
||||
// OwnerGone means the run was suspended on behalf of an owner that
|
||||
// stopped renewing its lease, so nothing will tear down what that owner
|
||||
// left behind (such as its live-run marker). Otherwise the owner suspended
|
||||
// the run itself and may still be finishing it.
|
||||
OwnerGone bool
|
||||
// OwnerLeaseUntil bounds how long the previous waiter may still finish.
|
||||
OwnerLeaseUntil *time.Time
|
||||
}
|
||||
|
||||
// Resolve records a user answer on an open prompt. A pending prompt's waiter
|
||||
// is woken; a suspended prompt is handed to the caller to resume. The tenant
|
||||
// must match the prompt; when the prompt was registered with a user, the
|
||||
// caller must present that same non-empty user.
|
||||
func (b *Broker) Resolve(ctx context.Context, req ResolveRequest) (Resolution, error) {
|
||||
row, err := b.store.Get(ctx, req.PromptID)
|
||||
if err != nil {
|
||||
return Resolution{}, err
|
||||
}
|
||||
if row == nil ||
|
||||
(req.Kind != "" && row.Kind != req.Kind) ||
|
||||
(req.SessionID != "" && row.SessionID != req.SessionID) {
|
||||
return Resolution{}, ErrPromptNotFound
|
||||
}
|
||||
if row.TenantID != req.TenantID {
|
||||
return Resolution{}, ErrTenantMismatch
|
||||
}
|
||||
// An empty caller userID is a mismatch (fail-close) so a missing auth
|
||||
// middleware cannot bypass the per-user check.
|
||||
if row.UserID != "" && row.UserID != req.UserID {
|
||||
return Resolution{}, ErrUserMismatch
|
||||
}
|
||||
if !row.IsOpen() {
|
||||
return Resolution{}, ErrAlreadyResolved
|
||||
}
|
||||
|
||||
b.mu.Lock()
|
||||
validate := b.validators[row.Kind]
|
||||
b.mu.Unlock()
|
||||
if validate == nil {
|
||||
return Resolution{}, fmt.Errorf("%w: unsupported prompt kind %q", ErrInvalidResponse, row.Kind)
|
||||
}
|
||||
if err := validate(json.RawMessage(row.Request), req.Response); err != nil {
|
||||
return Resolution{}, fmt.Errorf("%w: %v", ErrInvalidResponse, err)
|
||||
}
|
||||
|
||||
now := time.Now()
|
||||
// A pending prompt whose owner stopped renewing has no waiter left to
|
||||
// wake. Suspend it as the reaper would, so the answer resumes the run
|
||||
// instead of being recorded for nobody.
|
||||
if row.Status == types.AgentPromptPending && row.Suspendable &&
|
||||
row.LeaseUntil != nil && row.LeaseUntil.Before(now) {
|
||||
b.reapPending(ctx, now, row, b.hooks())
|
||||
if row, err = b.store.Get(ctx, req.PromptID); err != nil {
|
||||
return Resolution{}, err
|
||||
}
|
||||
if row == nil {
|
||||
return Resolution{}, ErrPromptNotFound
|
||||
}
|
||||
if !row.IsOpen() {
|
||||
return Resolution{}, ErrAlreadyResolved
|
||||
}
|
||||
}
|
||||
ownerLeaseUntil := row.LeaseUntil
|
||||
ownerGone := row.OwnerInstance == "" ||
|
||||
(row.Status == types.AgentPromptSuspended && ownerLeaseUntil != nil && ownerLeaseUntil.Before(now))
|
||||
resolvedBy := req.UserID
|
||||
answer := func(t types.AgentPromptTransition) (bool, error) {
|
||||
t.To = types.AgentPromptAnswered
|
||||
t.Response = types.JSON(req.Response)
|
||||
t.ResolvedBy = &resolvedBy
|
||||
t.ResolvedAt = &now
|
||||
return b.store.Transition(ctx, req.PromptID, t)
|
||||
}
|
||||
|
||||
owner, lease := uuid.NewString(), now.Add(b.leaseTTL)
|
||||
ok, err := answer(types.AgentPromptTransition{
|
||||
From: []string{types.AgentPromptSuspended},
|
||||
UnexpiredAt: &now,
|
||||
Owner: &owner,
|
||||
LeaseUntil: &lease,
|
||||
})
|
||||
if err != nil {
|
||||
return Resolution{}, err
|
||||
}
|
||||
if ok {
|
||||
row.Status, row.Response = types.AgentPromptAnswered, types.JSON(req.Response)
|
||||
row.ResolvedBy, row.ResolvedAt = resolvedBy, &now
|
||||
row.OwnerInstance, row.LeaseUntil = owner, &lease
|
||||
return Resolution{Prompt: row, Resume: true, OwnerGone: ownerGone, OwnerLeaseUntil: ownerLeaseUntil}, nil
|
||||
}
|
||||
|
||||
ok, err = answer(types.AgentPromptTransition{From: []string{types.AgentPromptPending}})
|
||||
if err != nil {
|
||||
return Resolution{}, err
|
||||
}
|
||||
if !ok {
|
||||
return Resolution{}, ErrAlreadyResolved
|
||||
}
|
||||
b.wake(ctx, req.PromptID)
|
||||
row.Status, row.Response = types.AgentPromptAnswered, types.JSON(req.Response)
|
||||
row.ResolvedBy, row.ResolvedAt = resolvedBy, &now
|
||||
return Resolution{Prompt: row}, nil
|
||||
}
|
||||
|
||||
// KeepLease renews this replica's lease on a prompt it resumes until stop is
|
||||
// called or the prompt leaves the leased states. Without it the reaper
|
||||
// treats the resumed run as abandoned.
|
||||
func (b *Broker) KeepLease(ctx context.Context, id, owner string) (stop func()) {
|
||||
ctx, cancel := context.WithCancel(context.WithoutCancel(ctx))
|
||||
go func() {
|
||||
ticker := time.NewTicker(b.renewInterval)
|
||||
defer ticker.Stop()
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-ticker.C:
|
||||
ok, err := b.store.RenewLease(ctx, id, owner, time.Now().Add(b.leaseTTL))
|
||||
if err != nil {
|
||||
logger.GetLogger(ctx).Warnf("renew agent prompt lease %s: %v", id, err)
|
||||
continue
|
||||
}
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
}()
|
||||
return cancel
|
||||
}
|
||||
|
||||
// Fail closes a prompt the caller holds (answered or executing) whose run
|
||||
// could not go on.
|
||||
func (b *Broker) Fail(ctx context.Context, id, reason string) {
|
||||
_, err := b.store.Transition(context.WithoutCancel(ctx), id, types.AgentPromptTransition{
|
||||
From: []string{types.AgentPromptAnswered, types.AgentPromptExecuting},
|
||||
To: types.AgentPromptFailed,
|
||||
CloseReason: &reason,
|
||||
})
|
||||
if err != nil {
|
||||
logger.GetLogger(ctx).Warnf("fail agent prompt %s: %v", id, err)
|
||||
}
|
||||
}
|
||||
|
||||
func (b *Broker) register(id string) <-chan struct{} {
|
||||
ch := make(chan struct{}, 1)
|
||||
b.mu.Lock()
|
||||
b.waiters[id] = ch
|
||||
b.mu.Unlock()
|
||||
return ch
|
||||
}
|
||||
|
||||
func (b *Broker) unregister(id string) {
|
||||
b.mu.Lock()
|
||||
delete(b.waiters, id)
|
||||
b.mu.Unlock()
|
||||
}
|
||||
|
||||
// wakeLocal nudges a waiter on this process; it reports whether one exists.
|
||||
func (b *Broker) wakeLocal(id string) bool {
|
||||
b.mu.Lock()
|
||||
ch, ok := b.waiters[id]
|
||||
b.mu.Unlock()
|
||||
if !ok {
|
||||
return false
|
||||
}
|
||||
select {
|
||||
case ch <- struct{}{}:
|
||||
default:
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
type wakeMessage struct {
|
||||
PromptID string `json:"prompt_id"`
|
||||
OriginID string `json:"origin_id,omitempty"`
|
||||
}
|
||||
|
||||
func pubsubChannel() string {
|
||||
if ns := strings.TrimSpace(os.Getenv("ACADEMY_REDIS_NAMESPACE")); ns != "" {
|
||||
return pubsubChannelBase + ":" + ns
|
||||
}
|
||||
return pubsubChannelBase
|
||||
}
|
||||
|
||||
// wake nudges the waiter wherever it lives. Delivery is best-effort: the
|
||||
// waiter's poll observes the answer even if the pub/sub message is lost.
|
||||
func (b *Broker) wake(ctx context.Context, id string) {
|
||||
if b.wakeLocal(id) || b.rdb == nil {
|
||||
return
|
||||
}
|
||||
payload, err := json.Marshal(wakeMessage{PromptID: id, OriginID: instanceID})
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
pubCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 2*time.Second)
|
||||
defer cancel()
|
||||
if err := b.rdb.Publish(pubCtx, pubsubChannel(), payload).Err(); err != nil {
|
||||
logger.GetLogger(ctx).Warnf("agent prompt pubsub wake: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// runSubscriber listens for cross-instance wake-ups for the process lifetime.
|
||||
func (b *Broker) runSubscriber() {
|
||||
ctx := context.Background()
|
||||
channel := pubsubChannel()
|
||||
backoff := time.Second
|
||||
const maxBackoff = 30 * time.Second
|
||||
for {
|
||||
sub := b.rdb.Subscribe(ctx, channel)
|
||||
for msg := range sub.Channel() {
|
||||
backoff = time.Second
|
||||
var m wakeMessage
|
||||
if err := json.Unmarshal([]byte(msg.Payload), &m); err != nil {
|
||||
logger.GetLogger(ctx).Warnf("agent prompt pubsub: bad payload: %v", err)
|
||||
continue
|
||||
}
|
||||
if m.OriginID != instanceID {
|
||||
b.wakeLocal(m.PromptID)
|
||||
}
|
||||
}
|
||||
_ = sub.Close()
|
||||
time.Sleep(backoff)
|
||||
backoff = min(backoff*2, maxBackoff)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,366 @@
|
||||
package hitl
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"academy/internal/types"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// testKind stands in for any prompt kind: the broker must not care what the
|
||||
// request and response mean.
|
||||
const testKind = "test_question"
|
||||
|
||||
func validateTestAnswer(_, response json.RawMessage) error {
|
||||
var r struct {
|
||||
Answer string `json:"answer"`
|
||||
}
|
||||
if err := json.Unmarshal(response, &r); err != nil {
|
||||
return err
|
||||
}
|
||||
if r.Answer == "" {
|
||||
return errors.New("answer is required")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func newTestBroker(store Store) *Broker {
|
||||
b := NewBroker(store, nil, WithPollInterval(20*time.Millisecond))
|
||||
b.RegisterKind(testKind, validateTestAnswer)
|
||||
return b
|
||||
}
|
||||
|
||||
func testSpec(timeout time.Duration, emit func(ctx context.Context, p *types.AgentPrompt) error) Spec {
|
||||
return Spec{
|
||||
Prompt: &types.AgentPrompt{
|
||||
TenantID: 1, UserID: "alice", SessionID: "s1", AssistantMessageID: "m1",
|
||||
Kind: testKind, Request: types.JSON(`{"question":"which?"}`),
|
||||
},
|
||||
Timeout: timeout,
|
||||
TimeoutReason: "no answer",
|
||||
Emit: emit,
|
||||
}
|
||||
}
|
||||
|
||||
func answer(promptID, text string) ResolveRequest {
|
||||
return ResolveRequest{
|
||||
TenantID: 1, UserID: "alice", SessionID: "s1", Kind: testKind, PromptID: promptID,
|
||||
Response: json.RawMessage(`{"answer":"` + text + `"}`),
|
||||
}
|
||||
}
|
||||
|
||||
func TestBroker_AnswerOnOtherReplicaReachesOwnerThroughStore(t *testing.T) {
|
||||
store := NewMemoryStore()
|
||||
owner, other := newTestBroker(store), newTestBroker(store)
|
||||
|
||||
out, err := owner.Await(context.Background(), testSpec(5*time.Second,
|
||||
func(_ context.Context, p *types.AgentPrompt) error {
|
||||
go func() { require.NoError(t, resolveErr(context.Background(), other, answer(p.ID, "blue"))) }()
|
||||
return nil
|
||||
}))
|
||||
require.NoError(t, err)
|
||||
require.True(t, out.Answered)
|
||||
require.JSONEq(t, `{"answer":"blue"}`, string(out.Prompt.Response))
|
||||
require.Equal(t, "alice", out.Prompt.ResolvedBy)
|
||||
|
||||
require.True(t, consumeWithoutError(context.Background(), t, owner,
|
||||
out.Prompt.ID, types.AgentPromptDone, out.Prompt.OwnerInstance))
|
||||
row, err := store.Get(context.Background(), out.Prompt.ID)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, types.AgentPromptDone, row.Status)
|
||||
}
|
||||
|
||||
func TestBroker_ResolveChecksScopeOwnershipAndAnswer(t *testing.T) {
|
||||
b := newTestBroker(NewMemoryStore())
|
||||
out, err := b.Await(context.Background(), testSpec(5*time.Second,
|
||||
func(_ context.Context, p *types.AgentPrompt) error {
|
||||
go func() {
|
||||
ctx := context.Background()
|
||||
otherSession := answer(p.ID, "x")
|
||||
otherSession.SessionID = "s2"
|
||||
require.ErrorIs(t, resolveErr(ctx, b, otherSession), ErrPromptNotFound)
|
||||
|
||||
otherKind := answer(p.ID, "x")
|
||||
otherKind.Kind = "something_else"
|
||||
require.ErrorIs(t, resolveErr(ctx, b, otherKind), ErrPromptNotFound)
|
||||
|
||||
otherTenant := answer(p.ID, "x")
|
||||
otherTenant.TenantID = 2
|
||||
require.ErrorIs(t, resolveErr(ctx, b, otherTenant), ErrTenantMismatch)
|
||||
|
||||
anonymous := answer(p.ID, "x")
|
||||
anonymous.UserID = ""
|
||||
require.ErrorIs(t, resolveErr(ctx, b, anonymous), ErrUserMismatch)
|
||||
|
||||
require.ErrorIs(t, resolveErr(ctx, b, answer(p.ID, "")), ErrInvalidResponse)
|
||||
|
||||
require.NoError(t, resolveErr(ctx, b, answer(p.ID, "red")))
|
||||
require.ErrorIs(t, resolveErr(ctx, b, answer(p.ID, "green")), ErrAlreadyResolved)
|
||||
}()
|
||||
return nil
|
||||
}))
|
||||
require.NoError(t, err)
|
||||
require.True(t, out.Answered)
|
||||
require.JSONEq(t, `{"answer":"red"}`, string(out.Prompt.Response))
|
||||
}
|
||||
|
||||
func TestBroker_UnregisteredKindIsRejected(t *testing.T) {
|
||||
b := NewBroker(nil, nil, WithPollInterval(20*time.Millisecond))
|
||||
out, err := b.Await(context.Background(), testSpec(200*time.Millisecond,
|
||||
func(_ context.Context, p *types.AgentPrompt) error {
|
||||
require.ErrorIs(t, resolveErr(context.Background(), b, answer(p.ID, "x")), ErrInvalidResponse)
|
||||
return nil
|
||||
}))
|
||||
require.NoError(t, err)
|
||||
require.True(t, out.TimedOut)
|
||||
}
|
||||
|
||||
// An answer recorded without a wake-up must win over the owner's timeout.
|
||||
func TestBroker_AnswerRecordedBeforeTimeoutWins(t *testing.T) {
|
||||
store := NewMemoryStore()
|
||||
b := NewBroker(store, nil, WithPollInterval(time.Hour))
|
||||
out, err := b.Await(context.Background(), testSpec(300*time.Millisecond,
|
||||
func(_ context.Context, p *types.AgentPrompt) error {
|
||||
_, err := store.Transition(context.Background(), p.ID, types.AgentPromptTransition{
|
||||
From: []string{types.AgentPromptPending}, To: types.AgentPromptAnswered,
|
||||
Response: types.JSON(`{"answer":"late"}`),
|
||||
})
|
||||
return err
|
||||
}))
|
||||
require.NoError(t, err)
|
||||
require.True(t, out.Answered)
|
||||
require.False(t, out.TimedOut)
|
||||
}
|
||||
|
||||
func TestBroker_TimeoutAndCancelAreRecorded(t *testing.T) {
|
||||
b := newTestBroker(NewMemoryStore())
|
||||
|
||||
var timedOutID string
|
||||
out, err := b.Await(context.Background(), testSpec(100*time.Millisecond,
|
||||
func(_ context.Context, p *types.AgentPrompt) error { timedOutID = p.ID; return nil }))
|
||||
require.NoError(t, err)
|
||||
require.True(t, out.TimedOut)
|
||||
require.Equal(t, "no answer", out.Reason)
|
||||
require.ErrorIs(t, resolveErr(context.Background(), b, answer(timedOutID, "x")), ErrAlreadyResolved)
|
||||
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
out, err = b.Await(ctx, testSpec(time.Minute,
|
||||
func(context.Context, *types.AgentPrompt) error { cancel(); return nil }))
|
||||
require.NoError(t, err)
|
||||
require.True(t, out.Canceled)
|
||||
row, err := b.Store().Get(context.Background(), out.Prompt.ID)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, types.AgentPromptCanceled, row.Status)
|
||||
}
|
||||
|
||||
func TestBroker_ExecutingUntilMarkedExecuted(t *testing.T) {
|
||||
b := newTestBroker(NewMemoryStore())
|
||||
out, err := b.Await(context.Background(), testSpec(5*time.Second,
|
||||
func(_ context.Context, p *types.AgentPrompt) error {
|
||||
go func() { require.NoError(t, resolveErr(context.Background(), b, answer(p.ID, "go"))) }()
|
||||
return nil
|
||||
}))
|
||||
require.NoError(t, err)
|
||||
|
||||
require.True(t, consumeWithoutError(context.Background(), t, b,
|
||||
out.Prompt.ID, types.AgentPromptExecuting, out.Prompt.OwnerInstance))
|
||||
row, _ := b.Store().Get(context.Background(), out.Prompt.ID)
|
||||
require.Equal(t, types.AgentPromptExecuting, row.Status)
|
||||
|
||||
b.MarkExecuted(context.Background(), out.Prompt.ID)
|
||||
row, _ = b.Store().Get(context.Background(), out.Prompt.ID)
|
||||
require.Equal(t, types.AgentPromptDone, row.Status)
|
||||
}
|
||||
|
||||
func resolveErr(ctx context.Context, b *Broker, req ResolveRequest) error {
|
||||
_, err := b.Resolve(ctx, req)
|
||||
return err
|
||||
}
|
||||
|
||||
func TestBrokerConsumeFencesOwnerAndOnlyWinsOnce(t *testing.T) {
|
||||
b := newTestBroker(NewMemoryStore())
|
||||
ctx := t.Context()
|
||||
require.NoError(t, b.store.Create(ctx, &types.AgentPrompt{
|
||||
ID: "p", Status: types.AgentPromptAnswered, OwnerInstance: "new-run",
|
||||
}))
|
||||
require.False(t, consumeWithoutError(ctx, t, b, "p", types.AgentPromptExecuting, "old-run"))
|
||||
require.True(t, consumeWithoutError(ctx, t, b, "p", types.AgentPromptExecuting, "new-run"))
|
||||
require.False(t, consumeWithoutError(ctx, t, b, "p", types.AgentPromptExecuting, "new-run"))
|
||||
}
|
||||
|
||||
func TestBrokerWaiterDetachesAfterTakeoverOnSameReplica(t *testing.T) {
|
||||
b := newTestBroker(NewMemoryStore())
|
||||
ctx := t.Context()
|
||||
var resumed Resolution
|
||||
out, err := b.Await(ctx, suspendableSpec(time.Second, func(_ context.Context, p *types.AgentPrompt) error {
|
||||
oldOwner := p.OwnerInstance
|
||||
past := time.Now().Add(-time.Second)
|
||||
_, err := b.store.Transition(ctx, p.ID, types.AgentPromptTransition{
|
||||
From: []string{types.AgentPromptPending}, To: types.AgentPromptPending, LeaseUntil: &past,
|
||||
})
|
||||
require.NoError(t, err)
|
||||
resumed, err = b.Resolve(ctx, answer(p.ID, "blue"))
|
||||
require.NoError(t, err)
|
||||
require.True(t, resumed.Resume)
|
||||
require.NotEqual(t, oldOwner, resumed.Prompt.OwnerInstance)
|
||||
return nil
|
||||
}))
|
||||
require.NoError(t, err)
|
||||
require.True(t, out.Detached)
|
||||
require.True(t, out.Suspended)
|
||||
require.False(t, out.Answered)
|
||||
snapshot, err := b.suspensions.Get(ctx, out.Prompt.AssistantMessageID)
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, snapshot, "the stale waiter must not delete the new owner's state")
|
||||
require.True(t, consumeWithoutError(ctx, t, b,
|
||||
resumed.Prompt.ID, types.AgentPromptExecuting, resumed.Prompt.OwnerInstance))
|
||||
}
|
||||
|
||||
type renewBeforeTransitionStore struct {
|
||||
Store
|
||||
renew bool
|
||||
}
|
||||
|
||||
func (s *renewBeforeTransitionStore) Transition(
|
||||
ctx context.Context, id string, tr types.AgentPromptTransition,
|
||||
) (bool, error) {
|
||||
if s.renew {
|
||||
s.renew = false
|
||||
row, err := s.Get(ctx, id)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
if _, err := s.RenewLease(ctx, id, row.OwnerInstance, time.Now().Add(time.Hour)); err != nil {
|
||||
return false, err
|
||||
}
|
||||
}
|
||||
return s.Store.Transition(ctx, id, tr)
|
||||
}
|
||||
|
||||
func TestReaperDoesNotTakeOverLeaseRenewedAfterScan(t *testing.T) {
|
||||
for _, status := range []string{types.AgentPromptPending, types.AgentPromptAnswered, types.AgentPromptExecuting} {
|
||||
t.Run(status, func(t *testing.T) {
|
||||
ctx := t.Context()
|
||||
store := &renewBeforeTransitionStore{Store: NewMemoryStore(), renew: true}
|
||||
b := NewBroker(store, nil)
|
||||
past := time.Now().Add(-time.Minute)
|
||||
require.NoError(t, store.Create(ctx, &types.AgentPrompt{
|
||||
ID: "p", Status: status, OwnerInstance: "owner", LeaseUntil: &past,
|
||||
Suspendable: true, AssistantMessageID: "m",
|
||||
}))
|
||||
require.NoError(t, b.suspensions.Save(ctx, &types.AgentRunSuspension{
|
||||
AssistantMessageID: "m", PromptID: "p", Snapshot: types.JSON(`{"version":1}`),
|
||||
}))
|
||||
n, err := b.Reap(ctx, time.Now(), RunHooks{Closed: func(
|
||||
context.Context, *types.AgentPrompt, *types.AgentRunSuspension, string,
|
||||
) error {
|
||||
t.Fatal("must not close a renewed run")
|
||||
return nil
|
||||
}})
|
||||
require.NoError(t, err)
|
||||
require.Zero(t, n)
|
||||
row, err := store.Get(ctx, "p")
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, status, row.Status)
|
||||
saved, err := b.suspensions.Get(ctx, "m")
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, saved)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// flakyTransitionStore fails the next failures Transition calls; with
|
||||
// committed set, each failing call still applies before reporting its error.
|
||||
type flakyTransitionStore struct {
|
||||
Store
|
||||
failures int
|
||||
committed bool
|
||||
readError bool
|
||||
}
|
||||
|
||||
func (s *flakyTransitionStore) Transition(
|
||||
ctx context.Context, id string, tr types.AgentPromptTransition,
|
||||
) (bool, error) {
|
||||
if s.failures > 0 {
|
||||
s.failures--
|
||||
if s.committed {
|
||||
_, _ = s.Store.Transition(ctx, id, tr)
|
||||
}
|
||||
return false, errors.New("database unavailable")
|
||||
}
|
||||
return s.Store.Transition(ctx, id, tr)
|
||||
}
|
||||
|
||||
func consumeWithoutError(ctx context.Context, t *testing.T, b *Broker, id, to, owner string) bool {
|
||||
t.Helper()
|
||||
ok, err := b.Consume(ctx, id, to, owner)
|
||||
require.NoError(t, err)
|
||||
return ok
|
||||
}
|
||||
|
||||
func (s *flakyTransitionStore) Get(ctx context.Context, id string) (*types.AgentPrompt, error) {
|
||||
if s.readError {
|
||||
return nil, errors.New("read unavailable")
|
||||
}
|
||||
return s.Store.Get(ctx, id)
|
||||
}
|
||||
|
||||
func TestBroker_ConsumeTellsAStoreFailureFromALostClaim(t *testing.T) {
|
||||
saved := consumeRetryDelays
|
||||
consumeRetryDelays = []time.Duration{0, 0}
|
||||
t.Cleanup(func() { consumeRetryDelays = saved })
|
||||
cases := map[string]struct {
|
||||
failures int
|
||||
committed, readError bool
|
||||
rowOwner string
|
||||
want, wantErr bool
|
||||
status string
|
||||
}{
|
||||
"confirms a claim committed before its error": {
|
||||
failures: 1, committed: true, rowOwner: "me", want: true, status: types.AgentPromptExecuting,
|
||||
},
|
||||
"recovers after transient failures": {
|
||||
failures: 2, rowOwner: "me", want: true, status: types.AgentPromptExecuting,
|
||||
},
|
||||
"does not execute through a write outage": {
|
||||
failures: 10, rowOwner: "me", wantErr: true, status: types.AgentPromptAnswered,
|
||||
},
|
||||
"closes an unclaimed answer when storage recovers": {
|
||||
failures: 3, rowOwner: "me", wantErr: true, status: types.AgentPromptFailed,
|
||||
},
|
||||
"does not execute through a read outage": {
|
||||
failures: 10, readError: true, rowOwner: "me", wantErr: true, status: types.AgentPromptAnswered,
|
||||
},
|
||||
"unknown owner cannot execute or cancel a takeover": {
|
||||
failures: 3, readError: true, rowOwner: "other", wantErr: true, status: types.AgentPromptAnswered,
|
||||
},
|
||||
"gives up an answer another owner holds": {
|
||||
failures: 10, rowOwner: "other", status: types.AgentPromptAnswered,
|
||||
},
|
||||
"gives up without any failure when not owned": {
|
||||
rowOwner: "other", status: types.AgentPromptAnswered,
|
||||
},
|
||||
}
|
||||
for name, tc := range cases {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
ctx := t.Context()
|
||||
store := &flakyTransitionStore{
|
||||
Store: NewMemoryStore(), failures: tc.failures, committed: tc.committed, readError: tc.readError,
|
||||
}
|
||||
require.NoError(t, store.Create(ctx, &types.AgentPrompt{
|
||||
ID: "p", Status: types.AgentPromptAnswered, OwnerInstance: tc.rowOwner,
|
||||
}))
|
||||
b := NewBroker(store, nil)
|
||||
ok, err := b.Consume(ctx, "p", types.AgentPromptExecuting, "me")
|
||||
require.Equal(t, tc.want, ok)
|
||||
require.Equal(t, tc.wantErr, err != nil)
|
||||
row, err := store.Store.Get(ctx, "p")
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, tc.status, row.Status)
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package hitl
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"academy/internal/types"
|
||||
)
|
||||
|
||||
type delegationKey struct{}
|
||||
|
||||
// Delegation is installed by the worker, never from model arguments. Register
|
||||
// durably associates a prompt with the current run before it can be answered.
|
||||
type Delegation struct {
|
||||
Register func(context.Context, *types.AgentPrompt) error
|
||||
Check func(context.Context) error
|
||||
}
|
||||
|
||||
// WithDelegation attaches child prompt ownership checks to the execution context.
|
||||
func WithDelegation(ctx context.Context, d Delegation) context.Context {
|
||||
return context.WithValue(ctx, delegationKey{}, d)
|
||||
}
|
||||
|
||||
// CheckDelegation rejects canceled or stale child executions before prompt handling.
|
||||
func CheckDelegation(ctx context.Context) error {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
if d, ok := ctx.Value(delegationKey{}).(Delegation); ok && d.Check != nil {
|
||||
return d.Check(ctx)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
package hitl
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"academy/internal/types"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestDelegatedPromptPersistsBeforeEmissionAndSuspendsImmediately(t *testing.T) {
|
||||
b := NewBroker(nil, nil)
|
||||
registered := false
|
||||
ctx := WithDelegation(
|
||||
context.Background(),
|
||||
Delegation{
|
||||
Check: func(context.Context) error { return nil },
|
||||
Register: func(ctx context.Context, p *types.AgentPrompt) error {
|
||||
snapshot, err := b.Suspensions().Get(ctx, p.AssistantMessageID)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, p.ID, snapshot.PromptID)
|
||||
registered = true
|
||||
return nil
|
||||
},
|
||||
},
|
||||
)
|
||||
start := time.Now()
|
||||
out, err := b.Await(ctx, Spec{
|
||||
Prompt: &types.AgentPrompt{ID: "p", AssistantMessageID: "m"}, Timeout: time.Hour,
|
||||
Suspend: &SuspendSpec{
|
||||
Snapshot: []byte(`{}`),
|
||||
SnapshotVersion: 1,
|
||||
}, Emit: func(ctx context.Context, p *types.AgentPrompt) error {
|
||||
require.True(t, registered)
|
||||
row, err := b.Store().Get(ctx, p.ID)
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, row)
|
||||
return nil
|
||||
},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
require.True(t, out.Suspended)
|
||||
require.Less(t, time.Since(start), time.Second)
|
||||
snapshot, err := b.Suspensions().Get(ctx, "m")
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, snapshot)
|
||||
}
|
||||
|
||||
func TestCanceledDelegationCannotConsumeLateApproval(t *testing.T) {
|
||||
b := NewBroker(nil, nil)
|
||||
require.NoError(
|
||||
t,
|
||||
b.Store().
|
||||
Create(context.Background(),
|
||||
&types.AgentPrompt{
|
||||
ID: "p",
|
||||
Status: types.AgentPromptAnswered,
|
||||
OwnerInstance: "owner",
|
||||
}),
|
||||
)
|
||||
ctx := WithDelegation(
|
||||
context.Background(),
|
||||
Delegation{Check: func(context.Context) error { return errors.New("task canceled") }},
|
||||
)
|
||||
ok, err := b.Consume(ctx, "p", types.AgentPromptExecuting, "owner")
|
||||
require.False(t, ok)
|
||||
require.ErrorContains(t, err, "task canceled")
|
||||
p, err := b.Store().Get(context.Background(), "p")
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, types.AgentPromptAnswered, p.Status)
|
||||
}
|
||||
|
||||
func TestDelegatedPromptCannotFallBackToUnsafeHotWait(t *testing.T) {
|
||||
b := NewBroker(nil, nil, WithSuspensionStore(failingSuspensionStore{NewMemorySuspensionStore()}))
|
||||
emitted := false
|
||||
ctx := WithDelegation(context.Background(), Delegation{})
|
||||
_, err := b.Await(
|
||||
ctx,
|
||||
Spec{
|
||||
Prompt: &types.AgentPrompt{ID: "p", AssistantMessageID: "m"},
|
||||
Timeout: time.Hour,
|
||||
FallbackTimeout: time.Hour,
|
||||
Suspend: &SuspendSpec{
|
||||
Snapshot: []byte(`{}`),
|
||||
SnapshotVersion: 1,
|
||||
},
|
||||
Emit: func(context.Context, *types.AgentPrompt) error { emitted = true; return nil },
|
||||
},
|
||||
)
|
||||
require.Error(t, err)
|
||||
require.False(t, emitted)
|
||||
}
|
||||
@@ -0,0 +1,219 @@
|
||||
package hitl
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"academy/internal/logger"
|
||||
"academy/internal/types"
|
||||
)
|
||||
|
||||
// reapBatch bounds how many prompts one sweep handles per rule.
|
||||
const reapBatch = 100
|
||||
|
||||
// Reasons recorded on prompts the system closes, and shown for the calls
|
||||
// they blocked.
|
||||
const (
|
||||
ReasonOwnerStopped = "the replica waiting on this prompt stopped"
|
||||
ReasonResumeStopped = "the run resuming after this prompt was interrupted before the tool ran"
|
||||
ReasonExecuteStopped = "the run was interrupted while the approved tool was running; its outcome is unknown"
|
||||
ReasonPromptExpired = "the prompt expired before it was answered"
|
||||
ReasonPromptSupersede = "the user moved on without answering this prompt"
|
||||
)
|
||||
|
||||
// RunHooks finish the assistant message of a run the reaper or a supersede
|
||||
// takes over.
|
||||
type RunHooks struct {
|
||||
// RecoverAnswered transfers safe, unconsumed answers to a durable scheduler.
|
||||
RecoverAnswered func(context.Context, *types.AgentPrompt) (bool, error)
|
||||
// Suspended shows a run whose owner disappeared while waiting the way a
|
||||
// run that suspended itself looks: the saved steps, waiting on prompt.
|
||||
Suspended func(ctx context.Context, prompt *types.AgentPrompt, state *types.AgentRunSuspension) error
|
||||
// Closed completes a run that will never resume. reason explains what
|
||||
// happened to the blocked call and the calls after it.
|
||||
Closed func(ctx context.Context, prompt *types.AgentPrompt, state *types.AgentRunSuspension, reason string) error
|
||||
}
|
||||
|
||||
// Reap takes over prompts their owner can no longer finish:
|
||||
//
|
||||
// 1. pending, lease lapsed: the owner died during the in-memory wait. A
|
||||
// suspendable prompt with saved state is suspended, any other expires.
|
||||
// 2. answered or executing, lease lapsed, saved state present: the replica
|
||||
// resuming the run died. The prompt fails and the run is closed; an
|
||||
// executing tool is never replayed.
|
||||
// 3. suspended past its expiry: the prompt expires and the run is closed.
|
||||
//
|
||||
// It returns how many prompts it took over.
|
||||
func (b *Broker) Reap(ctx context.Context, now time.Time, hooks RunHooks) (int, error) {
|
||||
reaped := 0
|
||||
|
||||
pending, err := b.store.ListStaleLeases(ctx, []string{types.AgentPromptPending}, now, reapBatch)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
for _, row := range pending {
|
||||
if b.reapPending(ctx, now, row, hooks) {
|
||||
reaped++
|
||||
}
|
||||
}
|
||||
|
||||
resuming, err := b.store.ListStaleLeases(ctx,
|
||||
[]string{types.AgentPromptAnswered, types.AgentPromptExecuting}, now, reapBatch)
|
||||
if err != nil {
|
||||
return reaped, err
|
||||
}
|
||||
for _, row := range resuming {
|
||||
if row.Status == types.AgentPromptAnswered && hooks.RecoverAnswered != nil {
|
||||
handled, err := hooks.RecoverAnswered(ctx, row)
|
||||
if err != nil {
|
||||
return reaped, err
|
||||
}
|
||||
if handled {
|
||||
continue
|
||||
}
|
||||
}
|
||||
state := b.runState(ctx, row)
|
||||
if state == nil {
|
||||
// An in-memory waiter consumed it; nothing to resume or close.
|
||||
continue
|
||||
}
|
||||
reason := ReasonResumeStopped
|
||||
if row.Status == types.AgentPromptExecuting {
|
||||
reason = ReasonExecuteStopped
|
||||
}
|
||||
if b.closeRun(ctx, row, state, []string{row.Status}, types.AgentPromptFailed, reason, hooks, now) {
|
||||
reaped++
|
||||
}
|
||||
}
|
||||
|
||||
expired, err := b.store.ListExpired(ctx, now, reapBatch)
|
||||
if err != nil {
|
||||
return reaped, err
|
||||
}
|
||||
for _, row := range expired {
|
||||
if b.closeRun(ctx, row, b.runState(ctx, row),
|
||||
[]string{types.AgentPromptSuspended}, types.AgentPromptExpired, ReasonPromptExpired, hooks) {
|
||||
reaped++
|
||||
}
|
||||
}
|
||||
return reaped, nil
|
||||
}
|
||||
|
||||
// SupersedeSession closes the session's suspended prompts because the user
|
||||
// moved on (sent a new message, rewound), completing their runs so the
|
||||
// conversation history stays well formed. It returns how many it closed.
|
||||
func (b *Broker) SupersedeSession(ctx context.Context, sessionID string, hooks RunHooks) (int, error) {
|
||||
rows, err := b.store.ListBySession(ctx, sessionID, []string{types.AgentPromptSuspended})
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
n := 0
|
||||
for _, row := range rows {
|
||||
if b.closeRun(ctx, row, b.runState(ctx, row),
|
||||
[]string{types.AgentPromptSuspended}, types.AgentPromptSuperseded, ReasonPromptSupersede, hooks) {
|
||||
n++
|
||||
}
|
||||
}
|
||||
return n, nil
|
||||
}
|
||||
|
||||
// runState returns the saved state of row's run, or nil when there is none
|
||||
// or it belongs to another prompt.
|
||||
func (b *Broker) runState(ctx context.Context, row *types.AgentPrompt) *types.AgentRunSuspension {
|
||||
if !row.Suspendable || row.AssistantMessageID == "" {
|
||||
return nil
|
||||
}
|
||||
saved, err := b.suspensions.Get(ctx, row.AssistantMessageID)
|
||||
if err != nil {
|
||||
logger.GetLogger(ctx).Warnf("read run state of prompt %s: %v", row.ID, err)
|
||||
return nil
|
||||
}
|
||||
if saved == nil || saved.PromptID != row.ID {
|
||||
return nil
|
||||
}
|
||||
return saved
|
||||
}
|
||||
|
||||
func (b *Broker) reapPending(ctx context.Context, now time.Time, row *types.AgentPrompt, hooks RunHooks) bool {
|
||||
log := logger.GetLogger(ctx)
|
||||
state := b.runState(ctx, row)
|
||||
if state == nil {
|
||||
reason := ReasonOwnerStopped
|
||||
ok, err := b.store.Transition(ctx, row.ID, types.AgentPromptTransition{
|
||||
From: []string{types.AgentPromptPending},
|
||||
To: types.AgentPromptExpired,
|
||||
ExpectedOwner: &row.OwnerInstance,
|
||||
LeaseBefore: &now,
|
||||
CloseReason: &reason,
|
||||
})
|
||||
if err != nil {
|
||||
log.Warnf("expire orphaned agent prompt %s: %v", row.ID, err)
|
||||
}
|
||||
return ok
|
||||
}
|
||||
|
||||
expiresAt := b.expiresAt(now)
|
||||
// Clearing the owner records that the run was suspended for it, which
|
||||
// Resolve reports as Resolution.OwnerGone.
|
||||
noOwner := ""
|
||||
ok, err := b.store.Transition(ctx, row.ID, types.AgentPromptTransition{
|
||||
From: []string{types.AgentPromptPending},
|
||||
To: types.AgentPromptSuspended,
|
||||
ExpiresAt: expiresAt,
|
||||
Owner: &noOwner,
|
||||
ExpectedOwner: &row.OwnerInstance,
|
||||
LeaseBefore: &now,
|
||||
})
|
||||
if err != nil {
|
||||
log.Warnf("suspend orphaned agent prompt %s: %v", row.ID, err)
|
||||
}
|
||||
if !ok {
|
||||
return false
|
||||
}
|
||||
row.Status = types.AgentPromptSuspended
|
||||
row.ExpiresAt = expiresAt
|
||||
row.OwnerInstance = ""
|
||||
if hooks.Suspended != nil {
|
||||
if err := hooks.Suspended(ctx, row, state); err != nil {
|
||||
log.Warnf("finish suspended run of message %s: %v", row.AssistantMessageID, err)
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// closeRun moves row from one of from to `to`, then completes its run and
|
||||
// drops the saved state. state may be nil when the run left none.
|
||||
func (b *Broker) closeRun(
|
||||
ctx context.Context, row *types.AgentPrompt, state *types.AgentRunSuspension,
|
||||
from []string, to, reason string, hooks RunHooks, staleBefore ...time.Time,
|
||||
) bool {
|
||||
log := logger.GetLogger(ctx)
|
||||
transition := types.AgentPromptTransition{
|
||||
From: from,
|
||||
To: to,
|
||||
CloseReason: &reason,
|
||||
}
|
||||
if len(staleBefore) > 0 {
|
||||
transition.ExpectedOwner = &row.OwnerInstance
|
||||
transition.LeaseBefore = &staleBefore[0]
|
||||
}
|
||||
ok, err := b.store.Transition(ctx, row.ID, transition)
|
||||
if err != nil {
|
||||
log.Warnf("close agent prompt %s as %s: %v", row.ID, to, err)
|
||||
}
|
||||
if !ok {
|
||||
return false
|
||||
}
|
||||
row.Status, row.CloseReason = to, reason
|
||||
if state == nil {
|
||||
return true
|
||||
}
|
||||
if hooks.Closed != nil {
|
||||
if err := hooks.Closed(ctx, row, state, reason); err != nil {
|
||||
log.Warnf("close run of message %s: %v", row.AssistantMessageID, err)
|
||||
return true
|
||||
}
|
||||
}
|
||||
b.dropSnapshot(ctx, row.AssistantMessageID, row.ID)
|
||||
return true
|
||||
}
|
||||
@@ -0,0 +1,175 @@
|
||||
package hitl
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"academy/internal/types"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// seedSuspended stores a suspended prompt for message msgID with saved run
|
||||
// state, expiring at expires.
|
||||
func seedSuspended(
|
||||
t *testing.T, b *Broker, id, msgID string, expires time.Time,
|
||||
) {
|
||||
t.Helper()
|
||||
ctx := context.Background()
|
||||
require.NoError(t, b.Store().Create(ctx, &types.AgentPrompt{
|
||||
ID: id, TenantID: 1, SessionID: "s1", AssistantMessageID: msgID, Kind: testKind,
|
||||
Status: types.AgentPromptSuspended, Suspendable: true, ExpiresAt: &expires,
|
||||
Request: types.JSON(`{"question":"color?"}`),
|
||||
}))
|
||||
require.NoError(t, b.Suspensions().Save(ctx, &types.AgentRunSuspension{
|
||||
AssistantMessageID: msgID, TenantID: 1, SessionID: "s1", PromptID: id,
|
||||
SnapshotVersion: 1, Snapshot: types.JSON(`{"version":1}`),
|
||||
}))
|
||||
}
|
||||
|
||||
type hookLog struct {
|
||||
suspended []string
|
||||
closed map[string]string
|
||||
}
|
||||
|
||||
func (h *hookLog) hooks() RunHooks {
|
||||
h.closed = map[string]string{}
|
||||
return RunHooks{
|
||||
Suspended: func(_ context.Context, p *types.AgentPrompt, _ *types.AgentRunSuspension) error {
|
||||
h.suspended = append(h.suspended, p.ID)
|
||||
return nil
|
||||
},
|
||||
Closed: func(_ context.Context, p *types.AgentPrompt, _ *types.AgentRunSuspension, reason string) error {
|
||||
h.closed[p.ID] = reason
|
||||
return nil
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func TestBroker_ResolveSuspendedHandsRunToCaller(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
b := newTestBroker(NewMemoryStore())
|
||||
seedSuspended(t, b, "p1", "m1", time.Now().Add(time.Hour))
|
||||
|
||||
res, err := b.Resolve(ctx, answer("p1", "blue"))
|
||||
require.NoError(t, err)
|
||||
require.True(t, res.Resume)
|
||||
require.Equal(t, types.AgentPromptAnswered, res.Prompt.Status)
|
||||
|
||||
row, err := b.Store().Get(ctx, "p1")
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, types.AgentPromptAnswered, row.Status)
|
||||
require.Equal(t, res.Prompt.OwnerInstance, row.OwnerInstance, "the resuming replica holds the lease")
|
||||
require.NotNil(t, row.LeaseUntil)
|
||||
require.True(t, row.LeaseUntil.After(time.Now()))
|
||||
|
||||
require.ErrorIs(t, resolveErr(ctx, b, answer("p1", "red")), ErrAlreadyResolved)
|
||||
}
|
||||
|
||||
func TestBroker_ResolveRejectsExpiredSuspension(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
b := newTestBroker(NewMemoryStore())
|
||||
seedSuspended(t, b, "p1", "m1", time.Now().Add(-time.Second))
|
||||
|
||||
require.ErrorIs(t, resolveErr(ctx, b, answer("p1", "blue")), ErrAlreadyResolved)
|
||||
row, err := b.Store().Get(ctx, "p1")
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, types.AgentPromptSuspended, row.Status, "left for the reaper to expire")
|
||||
}
|
||||
|
||||
func TestBroker_KeepLeaseRenewsUntilPromptCloses(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
b := NewBroker(nil, nil, withLease(80*time.Millisecond, 10*time.Millisecond))
|
||||
b.RegisterKind(testKind, validateTestAnswer)
|
||||
seedSuspended(t, b, "p1", "m1", time.Now().Add(time.Hour))
|
||||
res, err := b.Resolve(ctx, answer("p1", "blue"))
|
||||
require.NoError(t, err)
|
||||
|
||||
stop := b.KeepLease(ctx, "p1", res.Prompt.OwnerInstance)
|
||||
defer stop()
|
||||
time.Sleep(200 * time.Millisecond)
|
||||
row, err := b.Store().Get(ctx, "p1")
|
||||
require.NoError(t, err)
|
||||
require.True(t, row.LeaseUntil.After(time.Now()), "lease kept past its TTL")
|
||||
|
||||
n, err := b.Reap(ctx, time.Now(), RunHooks{})
|
||||
require.NoError(t, err)
|
||||
require.Zero(t, n, "a run with a live lease is not reaped")
|
||||
}
|
||||
|
||||
func TestBroker_ReapClosesAbandonedResumeAndExpiredSuspension(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
b := newTestBroker(NewMemoryStore())
|
||||
past, future := time.Now().Add(-time.Minute), time.Now().Add(time.Hour)
|
||||
|
||||
// Resumed, then the resuming replica died before and during the tool.
|
||||
for id, status := range map[string]string{
|
||||
"answered": types.AgentPromptAnswered, "executing": types.AgentPromptExecuting,
|
||||
} {
|
||||
seedSuspended(t, b, id, "m-"+id, future)
|
||||
ok, err := b.Store().Transition(ctx, id, types.AgentPromptTransition{
|
||||
From: []string{types.AgentPromptSuspended}, To: status, LeaseUntil: &past,
|
||||
})
|
||||
require.NoError(t, err)
|
||||
require.True(t, ok)
|
||||
}
|
||||
// Answered in the hot wait: its waiter dropped the run state.
|
||||
require.NoError(t, b.Store().Create(ctx, &types.AgentPrompt{
|
||||
ID: "hot", TenantID: 1, SessionID: "s1", AssistantMessageID: "m-hot", Kind: testKind,
|
||||
Status: types.AgentPromptExecuting, Suspendable: true, LeaseUntil: &past,
|
||||
}))
|
||||
seedSuspended(t, b, "old", "m-old", past)
|
||||
seedSuspended(t, b, "fresh", "m-fresh", future)
|
||||
|
||||
log := &hookLog{}
|
||||
n, err := b.Reap(ctx, time.Now(), log.hooks())
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, 3, n)
|
||||
require.Equal(t, map[string]string{
|
||||
"answered": ReasonResumeStopped,
|
||||
"executing": ReasonExecuteStopped,
|
||||
"old": ReasonPromptExpired,
|
||||
}, log.closed)
|
||||
|
||||
for id, want := range map[string]string{
|
||||
"answered": types.AgentPromptFailed,
|
||||
"executing": types.AgentPromptFailed,
|
||||
"hot": types.AgentPromptExecuting,
|
||||
"old": types.AgentPromptExpired,
|
||||
"fresh": types.AgentPromptSuspended,
|
||||
} {
|
||||
row, err := b.Store().Get(ctx, id)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, want, row.Status, id)
|
||||
}
|
||||
for msg, kept := range map[string]bool{"m-answered": false, "m-old": false, "m-fresh": true} {
|
||||
saved, err := b.Suspensions().Get(ctx, msg)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, kept, saved != nil, msg)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBroker_SupersedeSessionClosesOnlyItsSuspendedPrompts(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
b := newTestBroker(NewMemoryStore())
|
||||
seedSuspended(t, b, "p1", "m1", time.Now().Add(time.Hour))
|
||||
require.NoError(t, b.Store().Create(ctx, &types.AgentPrompt{
|
||||
ID: "other", TenantID: 1, SessionID: "s2", AssistantMessageID: "m2", Kind: testKind,
|
||||
Status: types.AgentPromptSuspended, Suspendable: true,
|
||||
}))
|
||||
|
||||
log := &hookLog{}
|
||||
n, err := b.SupersedeSession(ctx, "s1", log.hooks())
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, 1, n)
|
||||
require.Equal(t, map[string]string{"p1": ReasonPromptSupersede}, log.closed)
|
||||
|
||||
row, err := b.Store().Get(ctx, "p1")
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, types.AgentPromptSuperseded, row.Status)
|
||||
require.ErrorIs(t, resolveErr(ctx, b, answer("p1", "blue")), ErrAlreadyResolved)
|
||||
|
||||
other, err := b.Store().Get(ctx, "other")
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, types.AgentPromptSuspended, other.Status)
|
||||
}
|
||||
@@ -0,0 +1,210 @@
|
||||
package hitl
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"slices"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"academy/internal/types"
|
||||
"academy/internal/types/interfaces"
|
||||
)
|
||||
|
||||
// Store persists prompts. Production wiring passes the GORM repository; the
|
||||
// in-memory store keeps single-process callers and tests on the same code path.
|
||||
type Store = interfaces.AgentPromptRepository
|
||||
|
||||
// memoryStore is a process-local Store. It cannot coordinate replicas.
|
||||
type memoryStore struct {
|
||||
mu sync.Mutex
|
||||
rows map[string]types.AgentPrompt
|
||||
}
|
||||
|
||||
// NewMemoryStore returns a process-local Store.
|
||||
func NewMemoryStore() Store {
|
||||
return &memoryStore{rows: make(map[string]types.AgentPrompt)}
|
||||
}
|
||||
|
||||
func (s *memoryStore) Create(_ context.Context, row *types.AgentPrompt) error {
|
||||
if row == nil || row.ID == "" {
|
||||
return errors.New("agent prompt row requires an id")
|
||||
}
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
if _, exists := s.rows[row.ID]; exists {
|
||||
return errors.New("agent prompt already exists")
|
||||
}
|
||||
now := time.Now()
|
||||
stored := *row
|
||||
stored.CreatedAt, stored.UpdatedAt = now, now
|
||||
s.rows[row.ID] = stored
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *memoryStore) Get(_ context.Context, id string) (*types.AgentPrompt, error) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
row, ok := s.rows[id]
|
||||
if !ok {
|
||||
return nil, nil
|
||||
}
|
||||
return &row, nil
|
||||
}
|
||||
|
||||
func (s *memoryStore) Transition(_ context.Context, id string, t types.AgentPromptTransition) (bool, error) {
|
||||
if len(t.From) == 0 || t.To == "" {
|
||||
return false, errors.New("transition requires from and to states")
|
||||
}
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
row, ok := s.rows[id]
|
||||
if !ok || !slices.Contains(t.From, row.Status) {
|
||||
return false, nil
|
||||
}
|
||||
if t.UnexpiredAt != nil && row.ExpiresAt != nil && !row.ExpiresAt.After(*t.UnexpiredAt) {
|
||||
return false, nil
|
||||
}
|
||||
if t.ExpectedOwner != nil && row.OwnerInstance != *t.ExpectedOwner {
|
||||
return false, nil
|
||||
}
|
||||
if t.LeaseBefore != nil && (row.LeaseUntil == nil || !row.LeaseUntil.Before(*t.LeaseBefore)) {
|
||||
return false, nil
|
||||
}
|
||||
if t.Owner != nil {
|
||||
row.OwnerInstance = *t.Owner
|
||||
}
|
||||
if t.LeaseUntil != nil {
|
||||
at := *t.LeaseUntil
|
||||
row.LeaseUntil = &at
|
||||
}
|
||||
row.Status = t.To
|
||||
row.UpdatedAt = time.Now()
|
||||
if len(t.Response) > 0 {
|
||||
row.Response = t.Response
|
||||
}
|
||||
if t.CloseReason != nil {
|
||||
row.CloseReason = *t.CloseReason
|
||||
}
|
||||
if t.ResolvedBy != nil {
|
||||
row.ResolvedBy = *t.ResolvedBy
|
||||
}
|
||||
if t.ResolvedAt != nil {
|
||||
at := *t.ResolvedAt
|
||||
row.ResolvedAt = &at
|
||||
}
|
||||
if t.ExpiresAt != nil {
|
||||
at := *t.ExpiresAt
|
||||
row.ExpiresAt = &at
|
||||
}
|
||||
s.rows[id] = row
|
||||
return true, nil
|
||||
}
|
||||
|
||||
func (s *memoryStore) RenewLease(_ context.Context, id, owner string, until time.Time) (bool, error) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
row, ok := s.rows[id]
|
||||
if !ok || !slices.Contains(leasedStatuses, row.Status) || row.OwnerInstance != owner {
|
||||
return false, nil
|
||||
}
|
||||
row.LeaseUntil = &until
|
||||
row.UpdatedAt = time.Now()
|
||||
s.rows[id] = row
|
||||
return true, nil
|
||||
}
|
||||
|
||||
// leasedStatuses are the states whose row is held by an owner replica.
|
||||
var leasedStatuses = []string{types.AgentPromptPending, types.AgentPromptAnswered, types.AgentPromptExecuting}
|
||||
|
||||
func (s *memoryStore) ListStaleLeases(
|
||||
_ context.Context, statuses []string, before time.Time, limit int,
|
||||
) ([]*types.AgentPrompt, error) {
|
||||
return s.list(limit, func(row types.AgentPrompt) bool {
|
||||
return slices.Contains(statuses, row.Status) && row.LeaseUntil != nil && row.LeaseUntil.Before(before)
|
||||
}, func(row types.AgentPrompt) time.Time { return *row.LeaseUntil }), nil
|
||||
}
|
||||
|
||||
func (s *memoryStore) ListExpired(_ context.Context, before time.Time, limit int) ([]*types.AgentPrompt, error) {
|
||||
return s.list(limit, func(row types.AgentPrompt) bool {
|
||||
return row.Status == types.AgentPromptSuspended && row.ExpiresAt != nil && row.ExpiresAt.Before(before)
|
||||
}, func(row types.AgentPrompt) time.Time { return *row.ExpiresAt }), nil
|
||||
}
|
||||
|
||||
func (s *memoryStore) ListBySession(
|
||||
_ context.Context, sessionID string, statuses []string,
|
||||
) ([]*types.AgentPrompt, error) {
|
||||
return s.list(0, func(row types.AgentPrompt) bool {
|
||||
return row.SessionID == sessionID && slices.Contains(statuses, row.Status)
|
||||
}, func(row types.AgentPrompt) time.Time { return row.CreatedAt }), nil
|
||||
}
|
||||
|
||||
// list returns matching rows ordered by key; limit 0 is unlimited.
|
||||
func (s *memoryStore) list(
|
||||
limit int, match func(types.AgentPrompt) bool, key func(types.AgentPrompt) time.Time,
|
||||
) []*types.AgentPrompt {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
var out []*types.AgentPrompt
|
||||
for _, row := range s.rows {
|
||||
if match(row) {
|
||||
r := row
|
||||
out = append(out, &r)
|
||||
}
|
||||
}
|
||||
slices.SortFunc(out, func(a, b *types.AgentPrompt) int { return key(*a).Compare(key(*b)) })
|
||||
if limit > 0 && len(out) > limit {
|
||||
out = out[:limit]
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// SuspensionStore persists the state of runs blocked on a prompt.
|
||||
type SuspensionStore = interfaces.AgentRunSuspensionRepository
|
||||
|
||||
// memorySuspensionStore is a process-local SuspensionStore.
|
||||
type memorySuspensionStore struct {
|
||||
mu sync.Mutex
|
||||
rows map[string]types.AgentRunSuspension
|
||||
}
|
||||
|
||||
// NewMemorySuspensionStore returns a process-local SuspensionStore.
|
||||
func NewMemorySuspensionStore() SuspensionStore {
|
||||
return &memorySuspensionStore{rows: make(map[string]types.AgentRunSuspension)}
|
||||
}
|
||||
|
||||
func (s *memorySuspensionStore) Save(_ context.Context, row *types.AgentRunSuspension) error {
|
||||
if row == nil || row.AssistantMessageID == "" {
|
||||
return errors.New("agent run suspension requires an assistant message id")
|
||||
}
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
stored := *row
|
||||
stored.UpdatedAt = time.Now()
|
||||
if prev, ok := s.rows[row.AssistantMessageID]; ok {
|
||||
stored.CreatedAt = prev.CreatedAt
|
||||
} else {
|
||||
stored.CreatedAt = stored.UpdatedAt
|
||||
}
|
||||
s.rows[row.AssistantMessageID] = stored
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *memorySuspensionStore) Get(_ context.Context, assistantMessageID string) (*types.AgentRunSuspension, error) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
row, ok := s.rows[assistantMessageID]
|
||||
if !ok {
|
||||
return nil, nil
|
||||
}
|
||||
return &row, nil
|
||||
}
|
||||
|
||||
func (s *memorySuspensionStore) Delete(_ context.Context, assistantMessageID, promptID string) error {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
if row, ok := s.rows[assistantMessageID]; ok && row.PromptID == promptID {
|
||||
delete(s.rows, assistantMessageID)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,270 @@
|
||||
package hitl
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"academy/internal/types"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func suspendableSpec(hotWait time.Duration, emit func(ctx context.Context, p *types.AgentPrompt) error) Spec {
|
||||
spec := testSpec(hotWait, emit)
|
||||
spec.Suspend = &SuspendSpec{Snapshot: []byte(`{"version":1}`), SnapshotVersion: 1}
|
||||
return spec
|
||||
}
|
||||
|
||||
func TestBroker_HotWaitEndsInSuspensionAndKeepsRunState(t *testing.T) {
|
||||
b := NewBroker(nil, nil, WithPollInterval(20*time.Millisecond), WithSuspendExpiry(time.Hour))
|
||||
b.RegisterKind(testKind, validateTestAnswer)
|
||||
|
||||
before := time.Now()
|
||||
out, err := b.Await(context.Background(), suspendableSpec(100*time.Millisecond, nil))
|
||||
require.NoError(t, err)
|
||||
require.True(t, out.Suspended)
|
||||
require.False(t, out.TimedOut)
|
||||
require.NotNil(t, out.ExpiresAt)
|
||||
require.WithinDuration(t, before.Add(time.Hour), *out.ExpiresAt, 5*time.Second)
|
||||
|
||||
row, err := b.Store().Get(context.Background(), out.Prompt.ID)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, types.AgentPromptSuspended, row.Status)
|
||||
require.True(t, row.Suspendable)
|
||||
|
||||
saved, err := b.Suspensions().Get(context.Background(), "m1")
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, saved)
|
||||
require.Equal(t, out.Prompt.ID, saved.PromptID)
|
||||
require.JSONEq(t, `{"version":1}`, string(saved.Snapshot))
|
||||
}
|
||||
|
||||
func TestBroker_NegativeExpiryNeverExpires(t *testing.T) {
|
||||
b := NewBroker(nil, nil, WithPollInterval(20*time.Millisecond), WithSuspendExpiry(0))
|
||||
out, err := b.Await(context.Background(), suspendableSpec(50*time.Millisecond, nil))
|
||||
require.NoError(t, err)
|
||||
require.True(t, out.Suspended)
|
||||
require.Nil(t, out.ExpiresAt)
|
||||
}
|
||||
|
||||
func TestBroker_AnsweredInHotWaitDropsRunState(t *testing.T) {
|
||||
b := newTestBroker(NewMemoryStore())
|
||||
out, err := b.Await(context.Background(), suspendableSpec(5*time.Second,
|
||||
func(_ context.Context, p *types.AgentPrompt) error {
|
||||
go func() { require.NoError(t, resolveErr(context.Background(), b, answer(p.ID, "blue"))) }()
|
||||
return nil
|
||||
}))
|
||||
require.NoError(t, err)
|
||||
require.True(t, out.Answered)
|
||||
require.False(t, out.Suspended)
|
||||
|
||||
saved, err := b.Suspensions().Get(context.Background(), "m1")
|
||||
require.NoError(t, err)
|
||||
require.Nil(t, saved)
|
||||
}
|
||||
|
||||
func TestBroker_CanceledInHotWaitDropsRunState(t *testing.T) {
|
||||
b := newTestBroker(NewMemoryStore())
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
out, err := b.Await(ctx, suspendableSpec(time.Minute,
|
||||
func(context.Context, *types.AgentPrompt) error { cancel(); return nil }))
|
||||
require.NoError(t, err)
|
||||
require.True(t, out.Canceled)
|
||||
|
||||
saved, err := b.Suspensions().Get(context.Background(), "m1")
|
||||
require.NoError(t, err)
|
||||
require.Nil(t, saved)
|
||||
}
|
||||
|
||||
func TestBroker_SuspendableNeedsAssistantMessage(t *testing.T) {
|
||||
b := newTestBroker(NewMemoryStore())
|
||||
spec := suspendableSpec(time.Second, nil)
|
||||
spec.Prompt.AssistantMessageID = ""
|
||||
_, err := b.Await(context.Background(), spec)
|
||||
require.Error(t, err)
|
||||
}
|
||||
|
||||
// An owner whose lease lapsed sees another replica's takeover as a
|
||||
// suspension, not as a prompt still waiting on it.
|
||||
func TestBroker_OwnerSeesTakeoverAsSuspension(t *testing.T) {
|
||||
store := NewMemoryStore()
|
||||
owner := NewBroker(store, nil, WithPollInterval(20*time.Millisecond), withLease(time.Millisecond, time.Hour))
|
||||
reaper := NewBroker(store, nil, WithSuspendExpiry(time.Hour))
|
||||
reaper.suspensions = owner.suspensions
|
||||
|
||||
out, err := owner.Await(context.Background(), suspendableSpec(time.Minute,
|
||||
func(context.Context, *types.AgentPrompt) error {
|
||||
go func() {
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
n, err := reaper.Reap(context.Background(), time.Now(), RunHooks{})
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, 1, n)
|
||||
}()
|
||||
return nil
|
||||
}))
|
||||
require.NoError(t, err)
|
||||
require.True(t, out.Suspended)
|
||||
|
||||
saved, err := owner.Suspensions().Get(context.Background(), "m1")
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, saved, "the run state must survive for the resume")
|
||||
}
|
||||
|
||||
func TestBroker_ReapSuspendsOrphanedSuspendablePrompt(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
store, suspensions := NewMemoryStore(), NewMemorySuspensionStore()
|
||||
b := NewBroker(store, nil, WithSuspensionStore(suspensions), WithSuspendExpiry(time.Hour))
|
||||
|
||||
past := time.Now().Add(-time.Minute)
|
||||
require.NoError(t, store.Create(ctx, &types.AgentPrompt{
|
||||
ID: "p1", TenantID: 1, SessionID: "s1", AssistantMessageID: "m1", Kind: testKind,
|
||||
Status: types.AgentPromptPending, Suspendable: true, LeaseUntil: &past,
|
||||
}))
|
||||
require.NoError(t, suspensions.Save(ctx, &types.AgentRunSuspension{
|
||||
AssistantMessageID: "m1", TenantID: 1, SessionID: "s1", PromptID: "p1",
|
||||
SnapshotVersion: 1, Snapshot: types.JSON(`{"version":1}`),
|
||||
}))
|
||||
|
||||
var hooked *types.AgentRunSuspension
|
||||
n, err := b.Reap(ctx, time.Now(), RunHooks{Suspended: func(
|
||||
_ context.Context, p *types.AgentPrompt, s *types.AgentRunSuspension,
|
||||
) error {
|
||||
require.Equal(t, "p1", p.ID)
|
||||
hooked = s
|
||||
return nil
|
||||
}})
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, 1, n)
|
||||
require.NotNil(t, hooked)
|
||||
|
||||
row, err := store.Get(ctx, "p1")
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, types.AgentPromptSuspended, row.Status)
|
||||
require.NotNil(t, row.ExpiresAt)
|
||||
|
||||
n, err = b.Reap(ctx, time.Now(), RunHooks{})
|
||||
require.NoError(t, err)
|
||||
require.Zero(t, n, "a suspended prompt is not reaped again")
|
||||
}
|
||||
|
||||
func TestBroker_ReapExpiresOrphanWithoutRunState(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
store, suspensions := NewMemoryStore(), NewMemorySuspensionStore()
|
||||
b := NewBroker(store, nil, WithSuspensionStore(suspensions))
|
||||
|
||||
past, future := time.Now().Add(-time.Minute), time.Now().Add(time.Minute)
|
||||
require.NoError(t, store.Create(ctx, &types.AgentPrompt{
|
||||
ID: "plain", TenantID: 1, SessionID: "s1", AssistantMessageID: "m1", Kind: testKind,
|
||||
Status: types.AgentPromptPending, LeaseUntil: &past,
|
||||
}))
|
||||
// Suspendable, but its saved state belongs to a newer prompt.
|
||||
require.NoError(t, store.Create(ctx, &types.AgentPrompt{
|
||||
ID: "stale", TenantID: 1, SessionID: "s1", AssistantMessageID: "m2", Kind: testKind,
|
||||
Status: types.AgentPromptPending, Suspendable: true, LeaseUntil: &past,
|
||||
}))
|
||||
require.NoError(t, suspensions.Save(ctx, &types.AgentRunSuspension{
|
||||
AssistantMessageID: "m2", PromptID: "newer", Snapshot: types.JSON(`{}`),
|
||||
}))
|
||||
require.NoError(t, store.Create(ctx, &types.AgentPrompt{
|
||||
ID: "alive", TenantID: 1, SessionID: "s1", AssistantMessageID: "m3", Kind: testKind,
|
||||
Status: types.AgentPromptPending, LeaseUntil: &future,
|
||||
}))
|
||||
|
||||
called := false
|
||||
n, err := b.Reap(ctx, time.Now(), RunHooks{Suspended: func(
|
||||
context.Context, *types.AgentPrompt, *types.AgentRunSuspension,
|
||||
) error {
|
||||
called = true
|
||||
return nil
|
||||
}})
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, 2, n)
|
||||
require.False(t, called)
|
||||
|
||||
for id, want := range map[string]string{
|
||||
"plain": types.AgentPromptExpired,
|
||||
"stale": types.AgentPromptExpired,
|
||||
"alive": types.AgentPromptPending,
|
||||
} {
|
||||
row, err := store.Get(ctx, id)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, want, row.Status, id)
|
||||
}
|
||||
}
|
||||
|
||||
// An answer to a pending prompt whose owner stopped renewing suspends it as
|
||||
// the reaper would and resumes the run, instead of waking nobody.
|
||||
func TestBroker_ResolveTakesOverPromptOfVanishedOwner(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
store, suspensions := NewMemoryStore(), NewMemorySuspensionStore()
|
||||
b := NewBroker(store, nil, WithSuspensionStore(suspensions), WithSuspendExpiry(time.Hour))
|
||||
b.RegisterKind(testKind, validateTestAnswer)
|
||||
var hooked bool
|
||||
b.SetRunHooks(RunHooks{Suspended: func(context.Context, *types.AgentPrompt, *types.AgentRunSuspension) error {
|
||||
hooked = true
|
||||
return nil
|
||||
}})
|
||||
|
||||
past := time.Now().Add(-time.Minute)
|
||||
require.NoError(t, store.Create(ctx, &types.AgentPrompt{
|
||||
ID: "p1", TenantID: 1, UserID: "alice", SessionID: "s1", AssistantMessageID: "m1", Kind: testKind,
|
||||
Status: types.AgentPromptPending, Suspendable: true, LeaseUntil: &past, OwnerInstance: "dead",
|
||||
}))
|
||||
require.NoError(t, suspensions.Save(ctx, &types.AgentRunSuspension{
|
||||
AssistantMessageID: "m1", TenantID: 1, SessionID: "s1", PromptID: "p1",
|
||||
SnapshotVersion: 1, Snapshot: types.JSON(`{"version":1}`),
|
||||
}))
|
||||
|
||||
res, err := b.Resolve(ctx, answer("p1", "blue"))
|
||||
require.NoError(t, err)
|
||||
require.True(t, res.Resume)
|
||||
require.True(t, res.OwnerGone)
|
||||
require.True(t, hooked, "the message must be shown as awaiting input before it resumes")
|
||||
|
||||
row, err := store.Get(ctx, "p1")
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, types.AgentPromptAnswered, row.Status)
|
||||
require.Equal(t, res.Prompt.OwnerInstance, row.OwnerInstance)
|
||||
}
|
||||
|
||||
// A run that suspended itself still has an owner tearing it down.
|
||||
func TestBroker_ResolveOfSelfSuspendedPromptKeepsOwner(t *testing.T) {
|
||||
b := NewBroker(nil, nil, WithPollInterval(20*time.Millisecond), WithSuspendExpiry(time.Hour))
|
||||
b.RegisterKind(testKind, validateTestAnswer)
|
||||
out, err := b.Await(context.Background(), suspendableSpec(50*time.Millisecond, nil))
|
||||
require.NoError(t, err)
|
||||
require.True(t, out.Suspended)
|
||||
|
||||
res, err := b.Resolve(context.Background(), answer(out.Prompt.ID, "blue"))
|
||||
require.NoError(t, err)
|
||||
require.True(t, res.Resume)
|
||||
require.False(t, res.OwnerGone)
|
||||
}
|
||||
|
||||
type failingSuspensionStore struct{ SuspensionStore }
|
||||
|
||||
func (failingSuspensionStore) Save(context.Context, *types.AgentRunSuspension) error {
|
||||
return errors.New("jsonb rejected the snapshot")
|
||||
}
|
||||
|
||||
func TestBroker_UnsavableRunStateFallsBackToPlainWait(t *testing.T) {
|
||||
b := NewBroker(nil, nil, WithPollInterval(20*time.Millisecond),
|
||||
WithSuspensionStore(failingSuspensionStore{NewMemorySuspensionStore()}))
|
||||
spec := suspendableSpec(10*time.Millisecond, func(_ context.Context, p *types.AgentPrompt) error {
|
||||
require.False(t, p.Suspendable)
|
||||
return nil
|
||||
})
|
||||
spec.FallbackTimeout = 80 * time.Millisecond
|
||||
|
||||
start := time.Now()
|
||||
out, err := b.Await(context.Background(), spec)
|
||||
require.NoError(t, err)
|
||||
require.False(t, out.Suspended)
|
||||
require.True(t, out.TimedOut)
|
||||
require.GreaterOrEqual(t, time.Since(start), 80*time.Millisecond)
|
||||
|
||||
spec = suspendableSpec(10*time.Millisecond, nil)
|
||||
_, err = b.Await(context.Background(), spec)
|
||||
require.Error(t, err, "without a fallback the failure is reported")
|
||||
}
|
||||
Reference in new issue
Block a user