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:
- Accept: Validates caller RBAC (
runverb) and(workspace_id, principal_id, request_key)idempotency, inserts theinbox_entriesrow (message,child_result,child_message,tool_result,browser_handback, ordesktop_handback), and—when the thread can start a Run—freezesagent_revision_id,app_activation,executionpolicy,RunConfiguration, andRequestContexton the newrunsrow. - Claim: A
workerreplica claims an eligible Run by creating a numberedAttemptrow with a renewable lease deadline, leaving the DB connection immediately before constructingExecutableAgent. - 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.
- Seal: Records the immutable terminal outcome (
completed,waiting,failed, orcancelled), marks incorporated inbox entriesconsumed(incorporated_checkpoint_seq), snapshotsusage_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 claimsAttempt N+1, downloads the last committedruns.checkpointfrom S3, re-supplies any assigned inbox entries orresumedecisions not yet recorded inincorporated_checkpoint_seq, and continues the samerun_idon its originally pinned Agent revision. - Pre-upload lease guard & pointer fencing: An Attempt skips starting an S3 checkpoint upload when fewer than
objects.timeoutseconds 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 becauseruns.current_attempt_idhas 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 prefix | Contents | Reclamation 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 pages | Superseded/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 checkpoints | Retained in the sealed Run's frozen keep-set so later forks and continuations work |
compactions/{workspace}/{hash}/{kind}.json | Self-contained hydrated background compaction inputs and summary results | Cleaned 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.
Dual-plane observation, monotonic delta usage, and full-text search
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}/streamtails Redis Streams for instant token streaming across anycontrolreplica. 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& deltausage_records: Before each LLM call, the worker records amodel_dispatches(call_id, ...)reservation againstmax_usage.requestsin a short transaction. Usage deltas ingest monotonically per single-writer scope (after_sequence <= stored_sequence) with dispatch-timeprice_snapshotlocked in—and late usage reports from an expired Attempt are still recorded while preventing that Attempt from mutating checkpoints. - Zero-extension Jieba
tsvectorRun search:text_queryfiltering on/sessions,/threads, and/runsuses an internal GIN-indexed PostgreSQLtsvectorcolumn (runs.search_vector) populated in Python outside DB sessions using a pinned deterministicjiebatokenizer (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.