Skip to main content

Runbook: gate decisions, gate timeouts, crash recovery and schedules for agents+gates runs (W2, core#4424)

Companion to agents-gates-claude-runtime.md (R1/R2). That runbook covers how a run parks at a gate. This one covers what happens next: who may decide the gate, how the decision reaches the run, what a timeout does, how a crashed run comes back, and how schedule triggers fire.

1. What arms, where​

PieceProcessArmed whenCode
Decision authorizer (who may decide a gate)agent-orchestrator (the approval service)always. A gate row of source orchestrator-session is never decidable without itinternal/workflow/gatepolicy
DecisionPublisher arm (decision → resume)agent-orchestratoralways registered; delivers only once the agents+gates mode is armedinternal/workflow/gatesweep (Publisher)
Gate and crash sweeper, every 15 sagent-orchestratoragents+gates mode armed (WORKFLOW_AGENTS_GATES_ENABLED + runtime deps)gatesweep.Sweeper, cmd/agent-orchestrator/agentsgates_w2.go
Schedule runner, every 30 scontext-engineWORKFLOW_AGENTS_GATES_ENABLEDinternal/workflow/schedule

Boot logs: agents+gates gate sweeper interval=15s; agents+gates schedule triggers armed tick=30s misfire_grace=1h0m0s timezone=UTC (or not armed, with the reason).

2. Who may decide a gate​

The decision is checked in approval.Service.RecordDecision, before the first-write CAS. Every decision path goes through this check: the portal /approvals, the workflow AnswerRunPrompt RPC (what X1's answer_run_prompt and the portal prompt card call), Quad, and email. A refused decider gets PermissionDenied (approval: the decider may not decide this approval: <reason>). The row stays pending, and a workflow_gate_decision_refused audit row is written.

The rules come from the run's definition snapshot, never from the approval row:

  • The decider must be an active human member of the run's org. Agent members and suspended or removed members never qualify.
  • GATE_ANSWERER_SCOPE_ANYONE: any such member.
  • GATE_ANSWERER_SCOPE_REQUESTER: the run's requester_member_id, resolved once at trigger. For a schedule or event run it resolves to the workflow's owner. If that owner is not an active human member, nobody qualifies and the gate cannot be decided. It then times out under its timeout_policy. This is the resolve-or-refuse ruling, #4466 S4.
  • GATE_ANSWERER_SCOPE_TEAM: a direct org_unit_memberships row in team_id, for a unit that is not deleted. Membership is not inherited from parent or child units.
  • After the gate escalates, the audience is timeout_policy.escalate_to. The original audience no longer qualifies.
  • Clearance: the decider must be at or above the gate's required_clearance and the row's floor. This holds for every gate kind, including input gates.
  • A governance-imposed gate (governance:<policy>) may be decided by any active human member except the run's requester and its triggering actor, at or above the run's own clearance. This is architect ruling 7 on #4466.
  • The run must be parked on this gate. A decision on a gate of a cancelled, finished or moved-on run is refused.

3. From decision to resume​

  1. When a decision is admitted, the CAS records it and DecisionPublisher fires.
  2. The orchestrator-session arm builds the run Ref from the row (org, and metadata.run_id). It calls Resumer.ResumeDecided on a bounded pool of 8, never on the RPC goroutine. The resume drives the run's next segment on this process. The session comes from the SessionStore, so any worker can serve it.
  3. ErrUndecided and ErrStaleApproval are no-ops. They are counted, and the stale case is audited as workflow_gate_decision_ignored.
  4. If the pool is full, or the decision landed on a process where the mode is not armed, the sweeper delivers it on its next tick. A parked run whose row is decided is always swept.

4. Gate timeouts and escalation​

  • The sweeper owns the exact deadline. On its first sweep of a parked run, it stamps metadata.gate_deadline = requested_at + timeout_minutes and expires_at = gate_deadline + 5 min. The approvals scheduler's own expiry is only a backstop.
  • A governance-imposed gate has no timeout policy. It gets 24 h, and its expiry fails the run.
  • At the deadline, the sweeper voids the row and delivers the timeout outcome.
    • FAIL (or unset): the run ends failed(timeout).
    • ESCALATE: the run re-parks on the same row. The sweeper re-opens that row to escalate_to for another window, counted from the re-open, and records escalation_level + 1, metadata.gate_escalated_at and a workflow_gate_escalated audit.
    • A second expiry fails the run.
  • Rejections follow on_reject. FAIL (or unset) ends the run. RETURN_TO_ORCHESTRATOR resumes it with the rejection and reason. This is applied by runstore on R2's ResumeDecided.
  • A cancelled run's pending gate is voided by the sweeper (workflow_gate_voided).

5. Crash recovery​

  • Orphaned runs. A run is orphaned when it is running, its session is bound and its lease has lapsed. The usual causes are an orchestrator process that died or a segment that broke without an outcome.
    • The orchestrator's own claim loop picks these up every 2 s.
    • The sweeper also calls Recoverer.RecoverOrphans(1) for each orphan it finds, on the same bounded pool, every 15 s.
    • Every claim of a run with a bound session is a recovery, whichever path claimed it (claim loop or RecoverOrphans). The claiming process logs run.recovered (run_id, org_id, session_id, owner), counts workflow_runs_recovered_total, and audits workflow_run_recovered once per run per 10 minutes per orchestrator process (the dedupe is in memory; core#4616: on dev the claim loop won every recovery, and only the sweeper audited).
    • Re-fired tool calls are idempotent on their hop key (run:step@ordinal).
  • Graceful stop (SIGTERM). agent-orchestrator stops agents+gates right after the health server (readiness drops first) and before the other servers and the pgx pool (Orchestrator.Shutdown, at most 20 s of the 35 s budget). It stops claiming, and each in-flight segment ends without an outcome: a hook call in flight gets no reply, the worker stream is dropped, the segment's running time is recorded and the lease is released at once. The next claim, on this host after the restart or on another, resumes it in the same session. A store closed after a timed-out drain is only ever seen by a segment that is already being cut (core#4616).
  • The resume of a cut segment. With no gate answer and no deferred call to re-fire, the worker sends a recovery prompt that tells the model the platform interrupted the run, that a call denied by the stop did not run, and that a call already running when the run was interrupted may have completed (check before re-issuing a side-effecting call). Such a re-issue is a new hop key (@2), so hop-key idempotency does not dedupe it: the at-least-once window ADR-0020 and ADR-0023 already state. A prompt-less resume of such a session waits for input forever (the pinned CLI, measured). A gate resume, or a session still parked on a deferred call, stays prompt-less so the call re-fires.
  • Wall time. max_wall_minutes bounds the time the session spends running, across segments and processes (an interrupted segment's time is recorded on release). Time parked on a gate, or with no process holding the run, is not counted. A segment overruns its remaining wall by at most the worker's 15 s interrupt grace.
  • Task-less runs. A running run with no task anchor that is older than 10 minutes is failed (workflow_run_abandoned). Claim never picks these runs up.
  • Completion is earned (core#4625). A session that stops completed without a final output (an empty last turn, a sub-agent that returned nothing, an upstream failure the CLI reported as success) ends the run failed(error) with state_detail starting no_output: , then the last upstream error the CLI reported (upstream API error 502 (server_error), retry 1 of 10) or the model produced no final output. The orchestrator enforces it whatever the worker sends. An upstream 5xx that left nothing is retried once in the same segment by resuming the session. Cost: a persistent outage spends two rounds of the CLI's own retry backoff (about 3 minutes each) before the run fails, still inside max_wall_minutes.

6. Schedule triggers​

  • A definition's schedule triggers become rows in workflow_schedules. A trigger on workflows derives them whenever the definition, status or deletion changes. Only active, undeleted agents+gates workflows have rows.
  • Cron is five fields, in UTC. It accepts *, ?, lists, ranges, steps and the names JAN-DEC and SUN-SAT. When both day fields are restricted, a day matches either one.
  • A new schedule fires first at the next slot after it was armed. Nothing is back-filled.
  • Exactly once per slot. Each run is started as the workflow's owner, through TriggerWorkflow, with the idempotency key schedule:<cron>@<slot RFC 3339>. Duplicate starts collapse on (workflow_id, idempotency_key), whether they come from retries or from two context-engine replicas.
  • Misfire. If context-engine was down past one or more slots, it fires the latest missed slot once, provided that slot is at most 1 h old. Older slots are skipped and audited (workflow_schedule_skipped).
  • A transient start failure, including FailedPrecondition, is retried on the next tick with the same key. It is retried until the misfire window passes.
  • A scheduled definition must not require inputs. A schedule supplies none, so TriggerWorkflow refuses the run (InvalidArgument) and the slot is skipped and audited.
  • No owner. A workflow whose created_by is not an active member is skipped and audited (owner_unresolved).

7. Observing it​

SignalWhere
Audit actionsworkflow_gate_decision_refused, …_decision_ignored, workflow_gate_timed_out, …_escalated, …_voided, workflow_run_recovered, workflow_run_abandoned, workflow_schedule_fired, …_skipped (migration 293)
INFO log eventsrun.parked, run.gate_delivered, run.gate_timed_out, run.gate_escalated, run.gate_voided, run.recovered, run.abandoned (structured run_id, session_id, approval_id; to move onto internal/obslog when #3477 lands)
Metrics (agent-orchestrator/workflow-gates)workflow_gate_deliveries_total{result,decision}, workflow_gate_sweeps_total{action}, workflow_runs_recovered_total, workflow_runs_abandoned_total, workflow_runs_orphaned (gauge)

Find a parked run and its gate's state:

SELECT r.id, r.run_state, r.pending_gate_id, r.pending_gate_escalated, a.status, a.expires_at,
a.metadata->>'gate_deadline' AS deadline, a.metadata->>'answerable_by' AS audience
FROM workflow_runs r JOIN governance_approvals a ON a.id = r.pending_approval_id
WHERE r.org_id = :'org' AND r.run_state IN ('awaiting_approval', 'needs_input');

8. Acceptance on dev (coordinator + founder)​

  1. Slice-2 demo. Trigger the SDLC workflow. It parks at founder-signoff (before_agent:coder). Approve at /approvals/<pending_approval_id> as an L5 member. The run resumes into the coder and completes. Repeat the approval as an L2 member: it is refused and the row stays pending.
  2. Governance gate. Give the run's team a policy that requires approval for the coder dispatch, with no definition gate. Then:
    • the requester's approval is refused;
    • another member's approval resumes the run.
  3. Timeout. Set founder-signoff.timeout_policy to {timeout_minutes: 1, on_timeout: FAIL}. Within about 75 s the run is failed(timeout). With ESCALATE, the row is pending again with escalation_level = 1, and only escalate_to can decide it.
  4. Crash. Kill agent-orchestrator mid-segment. Within one lease TTL plus 15 s, run.recovered is logged and the run continues in the same session. A docker restart (SIGTERM) releases the lease at once, so the new process recovers it within one claim tick of starting; the dying process logs orchestrator: segment interrupted; releasing for recovery, never closed pool, and the session has no turn the model wrote after the cut.
  5. Schedule. Add {"schedule": {"cron": "*/5 * * * *"}} to an active definition with no required inputs. One run starts per 5-minute slot, with trigger_key = schedule:*/5 * * * *. A context-engine restart within the slot starts no second run.

Local proof is go test -tags integration ./internal/workflow/ -run TestW2_, run against a scratch DB on both connection classes.