Skip to content

feat: agent-authoritative execution state machine with single-writer projection (RELIABILITY-005) #524

Closed

Description

@vybe

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 ExecutionStateEvent for every transition over the existing trinity:events Redis stream (XADD), including a structured error_code enum on terminal failures (replacing today's stderr regex classification).
  • Single backend ExecutionStateProjector consumes the stream and is the only writer to schedule_executions.status for non-create transitions. Direct status writes from TaskExecutionService, CleanupService (phases 0/1/1b/1c/3), BacklogService, scheduler, and termination handlers are removed in favor of emitting events.
  • Backend ProcessRegistry mirror: 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_log is 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.py with 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.py consumer; refactor cleanup/TES/backlog to emit-not-write.
  • Related: docs/planning/ORCHESTRATION_RELIABILITY_2026-04.md Tier 2.5 — this is the contract change that the consolidation rests on.

Activity

  1. added
    priority-p1
    type-feature
    on Apr 26, 2026
  2. added 2 commits that reference this issue on Apr 26, 2026
  3. vybe commented on Apr 27, 2026

    @vybe
    ContributorAuthor

    /claim

  4. github-actions commented on Apr 27, 2026

    @github-actions

    Claimed by @vybe. Label status-in-progress added.

    Next steps:

    1. Create branch: feature/524-<short-slug>
    2. Implement the feature
    3. Open a PR with Fixes #524
  5. added
    status-in-progress
    on Apr 27, 2026
  6. vybe commented on Apr 27, 2026

    @vybe
    ContributorAuthor

    Scoped down — minimal implementation shipping

    After review, the full projector architecture (agent-push events, separate stream key, projected_status shadow 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:

    1. 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.

    2. TOCTOU fix in mark_stale_executions_failed and mark_no_session_executions_failed — the inner UPDATE now carries AND status = 'running' so a SUCCESS that arrives between the SELECT and the UPDATE is never overwritten.

    3. _recover_execution routed through the already-guarded writer — startup orphan recovery now uses mark_execution_failed_by_watchdog (which already has AND status = 'running' guard) instead of the unguarded update_execution_status.

    4. State machine documented in TaskExecutionStatus docstring — canonical states, allowed transitions, and authorized writers in one place. Added PENDING_RETRY to the enum (was in migrations but missing from the model).

    What's deferred to a future issue:

    • ExecutionStateProjector service (single backend consumer for agent-emitted events)
    • Agent lifecycle event emission (blocked on transport design — agents have no Redis access; needs HTTP callback design)
    • projected_status shadow column for divergence tracking
    • Full retirement of old writers (refactor: collapse 9-path cleanup pyramid once agent is authoritative #429 territory)

    The 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.

  7. added
    status-in-dev
    and removed
    status-in-progress
    on Apr 27, 2026
  8. kinthaiofficial commented on Apr 28, 2026

    @kinthaiofficial

    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:

    1. Agent emits events, backend projects them:

      Agent → Event Bus → [started, running, tool_call, finished/failed]
                       ↓
      Backend: projector writes status once per event (single writer)
      
    2. Heartbeat as liveness signal, not state signal:
      The agent sends periodic heartbeats ('I'm still alive'). If heartbeats stop, the backend transitions to stale (not failed). Only after a configurable timeout (default: 30s) does the backend transition to presumed_failed. This is the only state the backend writes without an agent event — and it's explicitly marked as presumptive.

    3. 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.

    4. Recovery protocol:
      When an agent recovers from a crash, it emits a recovered event 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

  9. added a commit that references this issue on Apr 30, 2026
  10. added a commit that references this issue on May 4, 2026
  11. added a commit that references this issue on May 10, 2026
  12. vybe commented on Jun 1, 2026

    @vybe
    ContributorAuthor

    Shipped in v0.6.0 (released via #998).

  13. added
    complexity-medium
    theme-reliability
    and removed
    status-in-dev
    on Jun 1, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

complexity-mediumpriority-p1theme-reliabilitytype-feature

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions