Repository navigation
Description
Summary
Define a canonical execution lifecycle contract where the agent container is the sole emitter of state transitions (started → running → finished | failed | terminated) and the backend is a single-writer projector that consumes those events and writes schedule_executions.status exactly once per transition. Today the column has ~12 distinct writers (TES, cleanup phases 0/1/1b/1c/3, slot reclaim, backlog drain, scheduler, retry, terminate handler, etc.) with FAILED→SUCCESS races mitigated only by re-verify patches.
This is the prerequisite contract that lets #429 (CLEANUP-COLLAPSE) actually delete cleanup phases instead of just hiding them. #306 (Event Bus, shipped) provides the transport; this issue defines what flows over it.
Context
From the orchestration architecture review (2026-04-26):
The execution status column has ~12 writers and no single-writer guarantee. FAILED→SUCCESS races are mitigated by Phase 3 re-verify, not prevented. This is exactly the kind of patch that holds until it doesn't, especially as new trigger types (webhook, retry, self-exec) layer on.
Common root: the agent isn't authoritative for its own lifecycle yet. Until push completion fully replaces watchdog reconciliation, most reliability issues are symptoms of the same disease — the backend is guessing state from outside the agent and patching the gaps with timeouts.
Pairs with #306 (transport, shipped), #429 (cleanup collapse, gated on this), and #307 (heartbeat).
Acceptance Criteria
- Documented state machine: states (
pending,queued,running,finished,failed,terminated), allowed transitions, and which actor (agent vs. backend) is authorized to emit each. - Agent container emits a typed
ExecutionStateEventfor every transition over the existingtrinity:eventsRedis stream (XADD), including a structurederror_codeenum on terminal failures (replacing today's stderr regex classification). - Single backend
ExecutionStateProjectorconsumes the stream and is the only writer toschedule_executions.statusfor non-create transitions. Direct status writes fromTaskExecutionService,CleanupService(phases 0/1/1b/1c/3),BacklogService, scheduler, and termination handlers are removed in favor of emitting events. - Backend
ProcessRegistrymirror: backend persists agent-reported active execution IDs so a container restart loses ProcessRegistry but state is reconstructible from the projection. - Audit verification: invariant test asserts that for any execution, the sequence of status transitions in
audit_logis monotonically valid (no FAILED→SUCCESS, no double-terminal). - Migration is additive — projector ships alongside existing writers behind a feature flag; old writers retired only after ≥2 weeks of zero divergence between projected status and current writers.
- Unblocks refactor: collapse 9-path cleanup pyramid once agent is authoritative #429 — re-verify patches in cleanup phases can be deleted because the projector enforces single-writer terminal transition by construction.
Technical Notes
- Builds on
services/event_bus.py(RELIABILITY-003, feat: Redis Streams event bus for reliable WebSocket delivery (RELIABILITY-003) #306). - Agent side: extend
agent_server/services/process_registry.pywith structured event emission on register/unregister/terminate, plus periodic "I'm running these IDs" reconciliation event on container start. - Backend side: new
services/execution_state_projector.pyconsumer; refactor cleanup/TES/backlog to emit-not-write. - Related:
docs/planning/ORCHESTRATION_RELIABILITY_2026-04.mdTier 2.5 — this is the contract change that the consolidation rests on.
Activity
docs(planning): add Tier 2.6 hardening + actor-model destination roadmap
docs(planning): mark #291 (WEBHOOK-001) shipped, Sprint C now 5/5
vybe commentedon Apr 27, 2026
/claim
github-actions commentedon Apr 27, 2026
Claimed by @vybe. Label
status-in-progressadded.Next steps:
feature/524-<short-slug>Fixes #524vybe commentedon Apr 27, 2026
Scoped down — minimal implementation shipping
After review, the full projector architecture (agent-push events, separate stream key,
projected_statusshadow column, restart reconciliation) is complex and risky enough to warrant deferring. The core race conditions can be fixed now with much smaller, lower-risk changes.What shipped in this PR:
CAS guard in
update_execution_status— SUCCESS writes are unconditional (agent's completion always wins); all other terminal writes (failed,cancelled, etc.) are blocked if the row is already in a terminal state. This eliminates the root FAILED→SUCCESS race without new infrastructure.TOCTOU fix in
mark_stale_executions_failedandmark_no_session_executions_failed— the inner UPDATE now carriesAND status = 'running'so a SUCCESS that arrives between the SELECT and the UPDATE is never overwritten._recover_executionrouted through the already-guarded writer — startup orphan recovery now usesmark_execution_failed_by_watchdog(which already hasAND status = 'running'guard) instead of the unguardedupdate_execution_status.State machine documented in
TaskExecutionStatusdocstring — canonical states, allowed transitions, and authorized writers in one place. AddedPENDING_RETRYto the enum (was in migrations but missing from the model).What's deferred to a future issue:
ExecutionStateProjectorservice (single backend consumer for agent-emitted events)projected_statusshadow column for divergence trackingThe deferred work is still the right long-term direction. These fixes are the load-bearing minimum that #429 needed before the cleanup pyramid can be safely removed.
fix(reliability): CAS guards on execution status writes + state machi…
kinthaiofficial commentedon Apr 28, 2026
This is the right architectural fix. The '12 writers with no single-writer guarantee' problem is exactly what we had at KinthAI before refactoring to agent-authoritative state management.
Why agent-authoritative is the only correct model:
The backend guessing state from outside the agent creates a fundamental race condition: the agent and the backend can disagree about the current state. Every 'patch with timeout' is a new edge case waiting to bite. The fix is simple in principle but hard to implement: the agent is the sole source of truth for its own lifecycle state.
Our implementation:
Agent emits events, backend projects them:
Heartbeat as liveness signal, not state signal:
The agent sends periodic heartbeats ('I'm still alive'). If heartbeats stop, the backend transitions to
stale(notfailed). Only after a configurable timeout (default: 30s) does the backend transition topresumed_failed. This is the only state the backend writes without an agent event — and it's explicitly marked as presumptive.Idempotent transitions:
Every state transition carries a monotonic sequence number. The projector rejects out-of-order or duplicate events. This prevents the FAILED→SUCCESS race entirely — if event Setup improvements #5 (FAILED) arrives after event fix: add missing logging_config.py to backend Dockerfile #4 (SUCCESS was expected), the projector rejects Setup improvements #5 because it's out of sequence.
Recovery protocol:
When an agent recovers from a crash, it emits a
recoveredevent with its actual state. The backend trusts this over its own presumed state. The agent is always right about itself.Multi-agent reliability: 221 Agents: Multi-Agent Coordination Lessons
Release: v0.5.0 (#608)
fix(Abilityai#411): canary terminal status set must match TaskExecuti…
fix(tests): green dev-merge residuals (refs Abilityai#660)
feat(#411): canary invariant harness Phase 1 (S-01, E-02, L-03) (#653)
vybe commentedon Jun 1, 2026
Shipped in v0.6.0 (released via #998).
docs(requirements): the model-dropdown section takes a free number (A…
feat(workspace): a user-friendly model dropdown in the chat composer (A…