Under the hood: distributed execution, lease fencing, and durable facts

Deep dive into Service internals—the accept/claim/execute/seal state machine, S3 lease-fenced checkpoints, owner-driven outbox GC, Redis provisional SSE, and delta usage accounting.

This page explains how a13n-service scales multi-tenant agent execution horizontally across stateless control replicas and leased worker replicas while preserving strict tenant isolation, crash recovery, and zero-long-transaction database discipline. For operational commands and API usage, see Operate the Service and Agents, conversations and runs.

Four-stage Run state machine (accept → claim → execute → seal)

Service executes agent turns on leased worker replicas outside HTTP request handlers, scoping PostgreSQL sessions and transactions strictly to four short, atomic database transitions while keeping LLM inference, tool waits, object uploads, and SSE streams outside transactions:

  1. Accept: Validates caller RBAC (run verb) and (workspace_id, principal_id, request_key) idempotency, inserts the inbox_entries row (message, child_result, child_message, tool_result, browser_handback, or desktop_handback), and—when the thread can start a Run—freezes agent_revision_id, app_activation, execution policy, RunConfiguration, and RequestContext on the new runs row.
  2. Claim: A worker replica claims an eligible Run by creating a numbered Attempt row with a renewable lease deadline, leaving the DB connection immediately before constructing ExecutableAgent.
  3. Execute: The worker drives Harness in memory, streams provisional events to Redis, uploads zstd-compressed checkpoint objects to S3 under unique per-attempt random keys, and commits pointer swaps in millisecond PostgreSQL transactions that verify the worker still holds the active Attempt lease.
  4. Seal: Records the immutable terminal outcome (completed, waiting, failed, or cancelled), marks incorporated inbox entries consumed (incorporated_checkpoint_seq), snapshots usage_at_seal, and stages lifecycle webhooks in the transactional Outbox.

Run vs. Attempt and zombie-worker fencing

Separating a logical Run from its physical worker Attempts allows seamless crash takeover without split-brain corruption:

  • Worker crash or preemption: When a worker dies and its Attempt lease expires, a sweep makes the Run claimable again (attempts < max_attempts). A new worker claims Attempt N+1, downloads the last committed runs.checkpoint from S3, re-supplies any assigned inbox entries or resume decisions not yet recorded in incorporated_checkpoint_seq, and continues the same run_id on its originally pinned Agent revision.
  • Pre-upload lease guard & pointer fencing: An Attempt skips starting an S3 checkpoint upload when fewer than objects.timeout seconds remain on its local lease. Even if a network stall delays a superseded worker's upload, S3 keys are write-once (orgs/{org}/runs/{run}/state/{attempt}/{128-bit-random}) so concurrent workers write distinct keys—and the superseded worker's subsequent PostgreSQL pointer transaction is rejected because runs.current_attempt_id has already moved to the successor Attempt.

Owner-driven object storage and isolated cleanup pools

Service relies on unconditional S3 PUTs without a separate mutable object-catalog table: an object is reachable if and only if it is referenced by a Run's committed checkpoint, tail, display pages catalog, or compactions row:

Object prefixContentsReclamation trigger
orgs/{org}/runs/{run}/state/{attempt}/{random}Compressed HarnessState (with a13n.usage stripped)Replaced state/tail keys staged in checkpoint_cleanup outbox on pointer swap
orgs/{org}/runs/{run}/tail/{attempt}/{random} & pages/Live display tail and sealed paginated AG-UI transcript pagesSuperseded/orphan attempt keys swept on Attempt takeover and final Run seal
orgs/{org}/runs/{run}/contents/ & subagents/Offloaded large binary parts and finished inline subagent checkpointsRetained in the sealed Run's frozen keep-set so later forks and continuations work
compactions/{workspace}/{hash}/{kind}.jsonSelf-contained hydrated background compaction inputs and summary resultsCleaned via checkpoint_cleanup once disposition settles and leases expire

On S3 deployments, control / all replicas allocate a dedicated connection pool (objects.cleanup_max_pool_connections, default 4) separate from foreground read connections (objects.max_pool_connections, default 32) so prefix-scan garbage collection leaves user API read capacity isolated.

Service separates immutable database facts (enforced by PostgreSQL BEFORE UPDATE/DELETE triggers on audit_events, agent_revisions, skill_revisions, uploads, usage_records, and sealed runs) from derived real-time projections:

  • Provisional Redis session streams vs. canonical display pages: GET /api/v1/sessions/{id}/stream tails Redis Streams for instant token streaming across any control replica. Reconnecting clients and Console Debug views read committed display pages + tail pointers from PostgreSQL/S3, ensuring clean convergence even if Redis restarts.
  • Reservation-backed model_dispatches & delta usage_records: Before each LLM call, the worker records a model_dispatches(call_id, ...) reservation against max_usage.requests in a short transaction. Usage deltas ingest monotonically per single-writer scope (after_sequence <= stored_sequence) with dispatch-time price_snapshot locked in—and late usage reports from an expired Attempt are still recorded while preventing that Attempt from mutating checkpoints.
  • Zero-extension Jieba tsvector Run search: text_query filtering on /sessions, /threads, and /runs uses an internal GIN-indexed PostgreSQL tsvector column (runs.search_vector) populated in Python outside DB sessions using a pinned deterministic jieba tokenizer (with identifier camelCase/snake_case splitting and bounded 8 KiB user / 16 KiB assistant head+tail excerpts, capped at a 512 KiB vector budget via FIFO intermediate-turn eviction)—requiring zero custom PostgreSQL C extensions.

On this page