Skip to content

Showcase: Distributed Agent Recovery (Zombie Worker & LIFO Sagas)

Ghost in the Machine: The Zombie AI Worker
It lost its lease. Another worker took over. Then the zombie came back.
The worker didn’t survive. The workflow did.

agbossjs/distributed-agent-recovery is a standalone, multi-process distributed AI release pipeline built on @agboss/core@0.1.0 and @agboss/cli@0.1.0. It demonstrates how AGBoss coordinates multiple OS worker processes, survives mid-execution worker freezes (SIGSTOP / lease expiry), rolls back partial external commits via deterministic LIFO sagas, and delegates root-cause recovery planning to an LLM agent without ever letting a probabilistic model manage distributed locks or cleanup state.

  • GitHub Repository: github.com/agbossjs/distributed-agent-recovery
  • Recorded Live LLM + Real-Clock SIGSTOP Evidence: docs/evidence/live-real-clock-cluster-run.json (openai/gpt-4o-mini, $0.00036255 total spend, 2 OS worker PIDs, 30s lease takeover epoch 1 -> 2, linear unbranched checkpoint chain)
  • Automated CI Gates: $0 deterministic offline suite (testWith & mockLlm), real-clock multi-process POSIX SIGSTOP/SIGCONT recovery (--cluster --real-clock), 4-container Docker Compose + hard worker container death (exit 137) failover, and single-node Kubernetes (kind).

Why Multi-Worker AI Pipelines Need Deterministic Recovery

Section titled “Why Multi-Worker AI Pipelines Need Deterministic Recovery”

When teams move AI workflows from single-process prototypes to multi-worker production clusters, two distributed failure modes appear immediately:

  1. Partial External Commits Before a Gate Failure: Multiple worker processes concurrently compile and write real artifacts to disk and a shared database, and a downstream integration smoke check fails. Asking an LLM to “clean up whatever failed” via tool calls is non-deterministic and unsafe; orphaned files corrupt the next attempt. AGBoss solves this with statically verified LIFO Saga Compensation (@Action({ compensateWith })).
  2. The Zombie Worker (GC Pause, I/O Stall, or Container Freeze): Worker A claims a child task under leaseEpoch = 1, commits its Step 1 checkpoint, and freezes during Step 2 until its 30-second execution lease expires. Worker B claims the orphaned child execution under leaseEpoch = 2, resumes from Worker A’s Step 1 checkpoint (execution.recovered), and commits Step 2. Then Worker A wakes up and attempts to commit its stale continuation. AGBoss prevents split-brain corruption through monotonic leaseEpoch fencing at both the external side-effect boundary and the runtime checkpoint saver.

The showcase runs a two-attempt software release pipeline for three modules (auth-service, payment-engine, and telemetry-collector) across a Coordinator and two independent Worker OS processes sharing a SQLite WAL cluster store and external release ledger:


1. Declarative Distributed Fan-Out, LIFO Saga & AI Error Recovery

Section titled “1. Declarative Distributed Fan-Out, LIFO Saga & AI Error Recovery”

ReleaseCoordinatorWorkflow expresses the entire distributed release lifecycle in one statically verified HarnessDSL (HDSL) graph:

  • Distributed child fan-out (ChildPlacement.AnyInstance): .toParallelWorkflows(ModuleWorkerWorkflow, { placement: ChildPlacement.AnyInstance }) writes child workflow tasks to SqliteChildExecutionQueueRepository and yields the parent’s own execution lease while waiting so the coordinator never blocks worker slots.
  • Compile-time compensation enforcement: Because LockReleaseCandidateAction declares compensateWith: CompensateReleaseCandidateAction, agboss check statically verifies that every .onError(...) path leaving VerifyReleaseSmokeGateAction invokes CompensateReleaseCandidateAction before reaching ReleaseRecoveryPlannedWorkflowFinish (otherwise compilation fails with [flow.uncompensated-action]).
  • Role segregation (@Action vs @Agent): Deterministic steps (DecomposeReleaseTasksAction, CompensateReleaseCandidateAction, PromoteReleaseArtifactsAction) handle filesystem and database mutations, while ReleaseRecoveryPlannerAgent (model: "openai/gpt-4o-mini") runs only after compensation completes, querying diagnostics via InspectFailedAttemptTool to produce a typed RecoveryPlanDto.

2. Two-Layer Zombie Worker Lease Fencing (leaseEpoch + LeasedCheckpointSaver)

Section titled “2. Two-Layer Zombie Worker Lease Fencing (leaseEpoch + LeasedCheckpointSaver)”

A critical distributed-systems detail demonstrated by this showcase is why two fencing layers are required when an @Action mutates external state (such as a database or object store):

  1. Layer 1 — External Side-Effect Boundary (leaseEpoch Fencing Token + step.idempotencyKey):
    AGBoss’s runtime LeasedCheckpointSaver renews and validates the 30-second execution lease when a step finishes and writes its LangGraph checkpoint. However, an @Action’s external side effect runs inside execute()—before returning control to LangGraph. If Worker A freezes inside execute() right before writing to the external database, Worker B will reclaim the expired lease with leaseEpoch = 2, resume from Worker A’s Step 1 checkpoint (PrepareModuleCandidateAction), and commit Step 2.
    To prevent Worker A’s delayed write from overwriting Worker B’s committed artifact, StageModuleArtifactAction captures the active (instanceId, leaseEpoch) token at step entry and validates capturedLeaseEpoch >= activeLeaseEpoch transactionally inside the SQLite release ledger alongside executionContext.step.idempotencyKey. When Zombie Worker A wakes up, 1 < 2 triggers StaleLeaseFenceError (ZOMBIE_WRITE_REJECTED), and executionContext.signal.aborted confirms lease loss.
  2. Layer 2 — AGBoss Runtime Checkpoint Boundary (LeasedCheckpointSaver):
    After catching StaleLeaseFenceError and returning from the action, LangGraph attempts to persist Worker A’s checkpoint via LeasedCheckpointSaver.putWrites(). That calls SqliteExecutionLeaseRepository.renew({ leaseEpoch: 1 }), which returns false (RUNTIME_LEASE_FENCED) and throws ExecutionLeaseLostError (execution.lease-lost)—terminating the zombie execution without running .onError handlers or touching Worker B’s completed state.

3. Deterministic $0 Offline Testing (testWith & mockLlm)

Section titled “3. Deterministic $0 Offline Testing (testWith & mockLlm)”

Every failure mode in the showcase—smoke gate failure, LIFO saga rollback, tool-assisted AI recovery planning, and multi-instance child takeover—is verified offline in milliseconds with testWith and mockLlm:


Multi-Process Load Balancing & Real 30s Wall-Clock Proof

Section titled “Multi-Process Load Balancing & Real 30s Wall-Clock Proof”

In addition to fast virtual-clock tests, agbossjs/distributed-agent-recovery runs as a compiled multi-process OS application (node dist/src/demo.js --cluster --real-clock) spawning independent node dist/worker/main.js processes over a shared SQLite WAL database with AGBoss’s untouched 30-second sweep timer (Clock) and real POSIX SIGSTOP / SIGCONT process signals:

  • Cross-Process Sibling Fairness (ClusterSqliteChildExecutionQueueRepository): In multi-process clusters, in-memory EventEmitter wakeups do not cross OS process boundaries; workers discover queued ChildPlacement.AnyInstance tasks on their periodic sweep ticks. By measuring a sibling fairness grace window from min(claimed_at) of the batch, the first awakened worker claims its share and yields remaining sibling tasks so peer worker PIDs participate concurrently (1 / 2 task split across Worker Alpha and Worker Beta in both Attempt 1 and Attempt 2).
  • Expired-Lease Running Child Reclamation: When Worker Alpha freezes (kill -STOP <pid>) after checkpointing Step 1 of payment-engine, its row in child_execution_queue remains Running while execution_leases.expires_at passes the 30-second wall-clock TTL. On the next sweep, Worker Beta atomically requeues the expired sibling row, acquires leaseEpoch = 2, logs execution.recovered, loads Worker Alpha’s Step 1 checkpoint without re-running Step 1, and commits Step 2.
  • Live OpenRouter Verification (--live): With OPENROUTER_API_KEY set, ReleaseRecoveryPlannerAgent calls openai/gpt-4o-mini live (~$0.00036 total run cost), invokes InspectFailedAttemptTool against SQLite to verify Attempt 1 compensation, and returns the structured RecoveryPlanDto that drives Attempt 2 to completion.

Every demo and CI run executes ReleaseInvariantVerifierService against both the application’s SQLite ledger tables (release_artifacts, release_candidate_locks, fencing_tokens, ledger_events), AGBoss’s internal SQLite cluster tables (execution_leases, checkpoints, child_execution_queue) via ClusterSnapshotRepository, and on-disk *.manifest.json files, exiting non-zero if any invariant is violated:

# Invariant ID What It Proves
1 INV-1-ALL-MODULES-COMPLETED All 3 expected modules (auth-service, payment-engine, telemetry-collector) reached PROMOTED status in Attempt 2.
2 INV-2-FINAL-ARTIFACTS-EXIST release-manifest.json and all 3 promoted *.manifest.json files exist on disk and match SQLite ledger records.
3 INV-3-NO-FAILED-ATTEMPT-ARTIFACTS-ACTIVE Zero Attempt 1 rows remain active in SQLite and zero Attempt 1 .artifact.json staging files remain on disk.
4 INV-4-SAGA-COMPENSATIONS-RECORDED-AND-APPLIED CompensateReleaseCandidateAction marked Attempt 1’s candidate lock and all 3 module artifacts COMPENSATED with its step.idempotencyKey.
5 INV-5-NO-DUPLICATE-EXTERNAL-COMMITS Every committed row carries a unique step.idempotencyKey and at most one active artifact exists per (release_id, attempt_number, logical_task_id).
6 INV-6-MULTI-INSTANCE-PARTICIPATION At least 2 distinct AGBoss worker instanceIds executed child workflows across the fixed worker pool.
7 INV-7-ZOMBIE-WORKER-FENCED Verifies Layer 1 (ZOMBIE_WRITE_REJECTED) and Layer 2 (RUNTIME_LEASE_FENCED when the zombie resumes, or hard process death) plus independent verification of AGBoss’s execution_leases (lease_epoch >= 2, holder_instance_id !== stalledInstanceId, released = 1) and checkpoints (strictly linear unbranched parent_checkpoint_id chain proving zero split-brain zombie checkpoint writes).
8 INV-8-ORIGINAL-LOGICAL-TASK-COMPLETED-AFTER-TAKEOVER rel-2026.10.0:payment-engine preserved the exact same childExecutionId and idempotencyKey, with Step 1 prepared by Worker A (leaseEpoch = 1), Step 2 completed by Worker B (leaseEpoch = 2), execution_leases.holder_instance_id matching the committer, and 0 orphaned rows in child_execution_queue.

Clone agbossjs/distributed-agent-recovery (requires Node.js >= 22.13.0 for built-in node:sqlite):


Canonical Directory Layout & Guarantee Boundaries

Section titled “Canonical Directory Layout & Guarantee Boundaries”

The repository enforces strict <kind>/<name>.<kind>.<ext> role separation (1 class = 1 file, < 200 lines per file, Drizzle ORM repositories in src/repositories/, Drizzle table schemas in src/schemas/, pure .sql DDL migrations in src/sql/, domain errors in src/errors/, stateless @Injectable services in src/services/, and symmetric tests/ mirroring src/).