Any system that hands work to more than one machine eventually meets the same ghost. A worker picks up a job, then goes quiet: a long garbage-collection pause (the language runtime stopping the program to tidy up memory), a frozen virtual machine, a network cable that someone bumped. The system waits, gives up, and hands the job to a second worker. Then the first one wakes up. It has no idea any time passed. As far as it knows, it still owns the job, and it is about to write its result.
That first worker is usually called a zombie, and what a system does with a zombie’s late write is one of the better tests of whether “failover” is a feature or a slide. Patch pipelines, incident runbooks, CI systems, and the newer crop of long-running AI agent jobs all run on some kind of workflow engine now, so “what happens when the owner changes mid-task” is a question security and infrastructure people end up owning whether they wanted it or not.
The Rabbit Hole Generator picked Distributed-Durable-Workflow-Engine this week: a workflow engine written in Go that keeps all of its state in PostgreSQL and uses Kafka to hand tasks to Python workers. It is one person’s educational project, not a product, and it says so. What makes it worth a post is that its README doesn’t ask to be believed. Every claim links to a committed evidence file: 48 fault-injection cases (tests that deliberately break something at a chosen moment), 60 scheduler takeovers, 180 blocked writes from old owners, and one late worker result rejected as STALE_ATTEMPT.
So the point this week is two questions a reader can reuse on any system that says “safe failover.” First, does the published evidence actually say what the README says it says? Second, what does the mechanism protect, and what was it never asked to protect? I checked the evidence files, then brought the whole stack up in Docker, froze a worker mid-task, stopped a scheduler, pulled the database out, and slowed the network down. The zombie got a 409. Then a made-up client with no credentials told the engine that 1 + 2 + 3 is 999,999, and got a 200.
What is a durable workflow engine used for in infrastructure automation?
A durable workflow engine runs multi-step jobs so that they survive crashes: each step’s progress is saved to a database, so if a machine dies halfway through, another machine picks up from the last saved step instead of starting over or losing the job. Temporal is the best-known example. This project is a small, readable one built on PostgreSQL for state and Apache Kafka (a message log that services publish to and read from) for task delivery, with schedulers in Go and workers in Python. Its focus is the hard part of that promise: making sure that when ownership of a job moves from one machine to another, the old owner can’t keep writing. It is explicitly educational; the README says it “makes no production-readiness or universal exactly-once claim.”
The Architecture: PostgreSQL decides, Kafka only delivers
Some vocabulary first. None of this is specific to this project; it’s the standard kit for this problem, and it shows up in Kubernetes, in databases, and in most queue systems.
- A workflow is a job made of steps. Here a step is called an activity: one unit of work a worker runs, like “add these numbers” or “restart that service.”
- A scheduler is the process that decides what runs next. There are two of them in the local stack, so one can take over if the other dies.
- A lease is a lock with an expiry time. Instead of “I own this until I say otherwise,” a lease says “I own this until 14:23:15 unless I renew.” If the owner dies, the lease simply runs out and someone else can take it. Kubernetes uses the same idea for leader election.
- A fencing token fixes the hole that leases leave open. A lease can expire while its owner is frozen, and the owner won’t know. So every time the lease changes hands, a counter goes up, and every write has to carry the counter value the writer was given. The storage layer refuses any write with an old number. Martin Kleppmann’s 2016 write-up on distributed locking is still the clearest explanation of why you need this. This project calls its counter the lease epoch.
- At-least-once delivery is what Kafka gives you by default: a message will arrive, but it may arrive more than once. Anything consuming those messages has to cope with duplicates.
- A transactional outbox is the standard answer to “how do I update my database and send a message without one happening and not the other?” You write the message into a table in the same database transaction as the state change, and a separate process publishes rows from that table afterwards. If the process crashes, the row is still there and gets published later.
- An inbox is the receiving half: a table of message IDs already handled, so a duplicate delivery is recognized and skipped.
- Idempotent means “safe to do twice.” Submitting the same request again gives the same answer and doesn’t create a second copy.
- An invariant is a rule that must always be true, like “a workflow’s revision numbers never skip” or “only the current attempt’s result is stored.” This project ships an invariant checker: a separate program that reads the database rows after the fact and tests those rules, without sharing code paths with the engine that wrote them. It’s the project’s referee, and it features heavily below.
With that, here is how one task travels:
The design bet is in the title of this section. Kafka is treated as a delivery truck: it can be late, it can deliver twice, and nothing it does is trusted on its own. Every decision that matters is a row in PostgreSQL, and every write is conditional. There are three separate checks, and it helps to keep them apart because they stop different things:
- Lease epoch stops an old scheduler. Workflows are spread over 16 partitions (buckets), and a scheduler has to hold a partition’s lease to advance the workflows in it.
- Workflow revision stops two writers racing on the same workflow. Each change names the revision number it read, and loses if someone else got there first.
- Attempt number and claim token stop a late or duplicate worker. Each try at an activity is a numbered attempt. When a worker claims one, the API hands it a random token, and a result only counts if it carries the current attempt’s number and token.
The lease check is short enough to read. This runs inside the same transaction as the write it protects:
// internal/state/store.go (lockLease, trimmed)
SELECT owner_id::text, epoch, lease_expires_at, clock_timestamp()
FROM engine.partition_leases
WHERE partition_id = $1
FOR UPDATE
...
if owner == nil || expiry == nil || *owner != ref.OwnerID ||
epoch != ref.Epoch || !expiry.After(databaseNow) {
return Lease{}, ErrLeaseNotOwned
}
Two details in there are the whole trick. FOR UPDATE takes a row lock, so nobody can change the lease between this check and the write that follows. And clock_timestamp() means “expired” is judged by the database’s clock, not the scheduler’s. Two machines never have to agree on what time it is; they only have to ask the same database. That removes a whole class of clock-skew bugs.
What this design does not try to do is make calls to the outside world safe to repeat. A database can’t put “restart that server” in a transaction. The project’s answer is to stop and ask: an outcome it can’t confirm goes to a reconciliation queue or a human approval step instead of being retried blindly. That part isn’t in the default local stack, which matters for Reality Check 5.
The Reality Check: where this breaks
That’s the pitch. Each week the Rabbit Hole Generator also writes a critique of its pick: where it fails at scale, what it quietly assumes, and what security problem it might introduce. This week’s has six distinct points:
- Points 1 to 3 are about scale. I measured 1 and 2 on one laptop and I’m clear below about what that does and doesn’t show. Point 3 is about multiple regions, which sounds untestable on a Mac and isn’t.
- Points 4 and 5 are assumptions about the environment. I tested 4. I did not test 5, and I say why.
- Point 6 is the vulnerability the design leaves open. I tested it end to end, and it’s the part I’d want every reader to take away.
1. PostgreSQL becomes the throughput ceiling (measured per workflow, not load tested)
Lease renewals, takeover scans, state transitions, inbox writes, and outbox polling all hit the same database. Add partitions and schedulers and they all contend for it. I can’t make a laptop into a large cluster, but I can count. Lab step 8 uses PostgreSQL’s own statement statistics: one two-step workflow cost 641 SQL statements, and under a modest burst it was about 1,700 per workflow, with a fifth of them touching the lease table.
2. Tables grow faster than the demo shows (measured, backlog not simulated)
Outbox rows, duplicate receipts, retry history, and revisions pile up. In lab step 8, every two-step workflow left 32 rows behind in three tables, and nothing removed them. I did not build a large Kafka backlog to watch that growth under pressure; the per-workflow number is real, the growth curve is arithmetic.
3. Across regions, it stays correct and becomes unusable (tested)
The critique’s wording is careful: lease safety doesn’t depend on clocks, so correctness survives distance, but every lease, transaction, and recovery scan gets slower. Lab step 9 puts a proxy between the schedulers and the database and adds delay. A workflow that took 139 milliseconds took 34.5 seconds with 80 milliseconds of added round-trip time, and still passed every correctness check.
4. It assumes PostgreSQL is always there (tested)
Everything authoritative lives in one database. The README is upfront that its cloud evidence is “not database-host durability.” Lab step 7 stops PostgreSQL for 35 seconds mid-task. The engine behaved well. The health check did not notice.
5. It assumes the outside world offers idempotency keys (not tested)
For actions outside the database, the design depends on the other system offering a stable idempotency key (a caller-chosen ID that lets the receiver recognize a repeat), a way to ask “did that happen?”, or a human who can check. Plenty of real APIs offer none of those. I didn’t test this because the default local stack only runs two pure functions (pure.add and pure.echo); the approval and effect service is exercised by the project’s own integration test, not deployed. Standing up a fake remote API to prove “an API with no idempotency key can’t be retried safely” would have been me testing my own fixture, not the engine.
6. Introduced Vulnerability: results aren’t bound to an identity (tested)
The fences prove a result is fresh. They don’t prove who sent it. The critique predicted forged or replayed completion messages at the API boundary. In lab step 10, a curl command calling itself not-a-real-worker claimed a task and returned a false result, the workflow finished successfully with the wrong answer, and the project’s invariant checker reported no violations. The project documents the API as unauthenticated and local-only, and has since added authentication for its Kubernetes deployment, so this is a boundary, not a bug. It’s still the boundary that matters most.
Two findings went beyond the critique. Each worker reports to exactly one scheduler replica, so stopping a scheduler cost far more time than the lease math suggests (lab step 6). And the health endpoint says ok with the database down (lab step 7).
The 30-Minute Lab: audit the evidence, then make your own
The Rabbit Hole Generator’s challenge was an evidence audit: clone the repository, run go test ./..., and run a small Python script over three of the linked JSON files to see whether they support four claims: 48 fault cases passed, 60 takeovers happened, 180 stale-owner writes were fenced, and a late worker result was rejected as STALE_ATTEMPT. Its instruction was to “treat absent fields as an audit failure rather than inferring them from the README,” which is the right attitude.
I did that first. Then, because reading someone’s evidence is not the same as watching the thing happen, I ran the engine and produced my own. It took a good deal longer than 30 minutes.
All the lab files are in this post’s bundle: start with README.txt. Everything was run at commit cd8d590 (November 24). The series works through a backlog, so this pick was two months old when I got to it, and the repository had grown by several hundred commits. That only changed one thing, noted in step 11.
1. Building the lab
The pieces. The repository ships a Docker Compose file (deploy/local/compose.yaml) that starts eight containers: PostgreSQL 18.6, Kafka 4.3.1, two copies of the Go runtime (each one is both an HTTP API and a scheduler), two Python workers with two task slots each, and an OpenTelemetry collector and Prometheus for metrics, which I didn’t use. I added three things: a throwaway golang:1.27.4 container for running Go commands so nothing gets installed on the Mac, a handful of shell scripts, and (for one step) a network-delay proxy.
The fault injector is just Docker. docker pause freezes every process in a container without killing it, which is exactly what a zombie is: alive, holding its state, and unaware that time is passing. docker stop is a crash. That’s the whole toolkit.
First snag: everything is PowerShell. The README’s setup is pwsh ./scripts/bootstrap.ps1 -StartServices. The repository has 56 PowerShell scripts and 8 shell scripts, and none of the shell ones bring the stack up. PowerShell runs fine on a Mac, but I didn’t want to install it (or the Python tool uv, which the bootstrap also demands) for a lab. The scripts are readable, so I translated the two that matter into about 25 lines of bash. up.sh generates the .env file with a random database password, starts the stack, and applies the 23 SQL migration files in order:
git clone https://github.com/XiaoyunYin/Distributed-Durable-Workflow-Engine.git ddwe
cd ddwe && git checkout cd8d590
../lab/up.sh
apply 000001_bootstrap.up.sql
...
apply 000023_k6_dispatch.up.sql
SERVICE STATUS
kafka Up 38 seconds (healthy)
postgres Up 38 seconds (healthy)
runtime-a Up 30 seconds (healthy)
runtime-b Up 30 seconds (healthy)
worker-a Up 24 seconds (healthy)
worker-b Up 24 seconds (healthy)
Build and first start took 56 seconds.
Second snag: “healthy” arrives before the database has a schema. Compose waits for every container to report healthy, and both runtimes did, before any migration had run. Their logs at that moment:
WARN scheduler repair scan failed error="ERROR: relation \"engine.scheduler_wakeups\" does not exist (SQLSTATE 42P01)"
WARN relay pass failed error="claim outbox rows: ERROR: column \"next_attempt_at\" does not exist (SQLSTATE 42703)"
They recovered on their own once the tables existed, so it’s harmless here. But it’s the first sign of something that comes back in step 7: the health check reports that the process is up, not that it can do its job.
Third snag: there’s no API for defining a workflow. You can submit a workflow over HTTP, but the definition it refers to (which steps, in what order) has to already exist in the database. The project’s demo program inserts one through its Go code. I did the same with plain SQL so the rest of the lab could be curl and psql. define.sql creates two:
INSERT INTO engine.workflow_definitions
(definition_id, version, definition_hash, graph, activity_versions, effect_classes)
VALUES
('lab-add', 1, 'lab-add',
'{"entry":"pure.add","nodes":[{"id":"pure.add","kind":"activity","next":"pure.echo"},
{"id":"pure.echo","kind":"activity","next":"done"},{"id":"done","kind":"success"}]}',
'{"pure.add":"v1","pure.echo":"v1"}',
'{"pure.add":"PURE_ACTIVITY","pure.echo":"PURE_ACTIVITY"}'),
('lab-slow', 1, 'lab-slow', ...); -- one step: dur048.sleep
lab-add sums a list and echoes the answer: two steps, done in milliseconds. lab-slow is one step that sleeps, which I need because you can’t freeze a worker in the middle of a task that takes 30 milliseconds. The workers already have a sleep activity for the project’s own recovery tests; it’s switched on with two lines in .env:
DUR048_ACTIVITY_DELAY_MS=20000 # the sleep activity takes 20 seconds
DUR048_ALLOW_FIXTURE_ACTIVITY=1 # let the scheduler dispatch it
Four small helpers do the repetitive parts: dc.sh (Compose with the right files), psql.sh (a SQL prompt inside the database container), submit.sh (one curl that submits a workflow), and gorun.sh (runs a Go command in a container on the lab’s network, so it can reach postgres and kafka by name).
To confirm the stack worked before I started breaking it, I ran the project’s own demo through that last helper:
$ ../lab/gorun.sh go run ./cmd/local-demo -api http://runtime-a:8080
workflow: local-demo-62069019-4b29-4a1d-a58f-e9bf3491942b
state: SUCCEEDED
activity result: 6
Python worker claims: 2
invariant checker: PASS
2. The Rabbit Hole Generator’s audit, as written
The challenge has three commands. Each one taught me something other than what it was meant to.
go test ./... failed, and the passes were worth less than they looked. On a clean clone, in a Go container:
--- FAIL: TestM2SchedulerContinuesAfterContendedPartition (0.00s)
engine_integration_test.go:722: set DURABLE_DATABASE_URL or provide .env for PostgreSQL integration tests
FAIL durable-agent-execution-engine/internal/engine 0.010s
...
ok durable-agent-execution-engine/internal/state 0.005s
38 packages passed and one failed, in 36 seconds. The failure isn’t a bug in the engine; one test helper stops with an error when it can’t find a database, where its neighbors quietly skip. The more important line is the last one. internal/state is the package that holds the fencing logic, and it “passed” in five thousandths of a second. That’s because the tests that matter need a real PostgreSQL and skip themselves without one. The source has 40 places where a test can skip.
So a green go test ./... on this repository tells you very little about the claims. Once the stack from step 1 was up, I stopped the runtimes and workers (the project’s own CI does this so they don’t fight the tests over the database) and ran it again with the database attached:
../lab/dc.sh stop runtime-a runtime-b worker-a worker-b
EXTRA_ENV="-e DURABLE_REQUIRE_DATABASE=1 -e DURABLE_RUN_INTEGRATION=1" \
../lab/gorun.sh go test -p 1 -count=1 ./...
ok durable-agent-execution-engine/internal/engine 10.326s
ok durable-agent-execution-engine/internal/state 23.511s
--- FAIL: TestK1PythonDrainResultsAndReplacement (0.01s)
lifecycle_integration_test.go:280: Python drain: exec: "uv": executable file not found in $PATH
--- FAIL: TestK2MixedWorkerVersionsCompleteExistingWorkflow (0.01s)
registry_integration_test.go:108: mixed rollout worker old: exec: "uv": executable file not found in $PATH
internal/state went from 0.005 seconds to 23.5. That’s the number to look at: it’s the difference between tests that ran and tests that didn’t. 37 packages passed in 2 minutes 18 seconds. The two failures are mine, not the project’s: those tests launch Python workers with uv, and my Go container doesn’t have it. I left them failing and am saying so, since installing uv into the container to turn two lines green wouldn’t have told me anything new about fencing. -p 1 runs one package at a time, because they share one database.
The specific test for this post’s subject passes against real PostgreSQL:
--- PASS: TestPostgresStateRepository/stale_owner_is_fenced_after_takeover (0.00s)
--- PASS: TestPostgresStateRepository/concurrent_claims_and_result-timeout_races_have_one_winner (0.70s)
The audit script crashed on the first file.
json.decoder.JSONDecodeError: Unexpected UTF-8 BOM (decode using utf-8-sig): line 1 column 1 (char 0)
A BOM (byte order mark) is three invisible bytes, EF BB BF, that some Windows tools put at the start of a text file. Two of the three evidence files start with one, because they were written by PowerShell. Python’s JSON parser refuses it unless you open the file as utf-8-sig. One word fixed it; the corrected script is audit.py. It’s a small thing, but it’s a real one: evidence that a standard parser can’t open on the first try is evidence fewer people will check.
Then the script worked, and couldn’t answer the first question. It walks every value in each JSON file and prints the ones whose name or content matches words like pass, stale, takeover, or epoch. For the 48-case file that was 291 matches, and its follow-up grep for 48 matched nothing useful, because “48” isn’t written anywhere in the file. The file is a list with 48 entries. The count is the length of the list. The grep did turn up 41 lines of captured === RUN output from Go tests that are stored inside the JSON as strings and happen to contain the word “stale.”
By the challenge’s own rule (absent field means audit failure) that’s a fail for claim one, which would be the wrong conclusion. The number is there. It just has to be derived, not found.
docker compose config --services printed nothing, because the Compose file isn’t at the repository root:
no configuration file provided: not found
3. Checking the four claims properly
A keyword search can tell you a word appears. I wanted a script that fails unless each number can be computed from the file. claims.py is 40 lines:
$ python3 ../lab/claims.py
[PASS] 48 fault cases passed
entries=48 distinct_cases=16 seeds=[11, 23, 47] status_tuples={('PASS', 'PASS', 'PASS', 'PASS'): 48}
checker_output values: {'{"runs":1,"valid":true,"violations":null}': 48}
[PASS] 60 takeovers
safety.takeovers=60 sum_of_arms=60 arms=['owner_crash', 'owner_pause']
[PASS] 180 stale-owner writes fenced
safety.fenced_old_owner_writes=180 sum_of_arms=180 false_takeovers=0
recorded at commit c50960c0b452; limitations[0]: R096 lock-held takeover is excluded and remains unresolved.
[PASS] late worker result rejected as STALE_ATTEMPT
api_rejection=STALE_ATTEMPT stale_attempt_current=False stale_result_recorded=False superseded_epoch_transitions=0
How to read it, claim by claim:
- 48 fault cases. The file has 48 entries, made of 16 distinct case names each run with three random seeds (11, 23, 47), which matches the README’s “16 boundaries × 3 seeds.” Each entry carries four separate verdicts: the fault controller’s, the Go test’s, the invariant checker’s, and an overall status. All 48 are
PASSon all four. If only the overallstatusfield existed, I’d have less to go on; four agreeing fields from different components is better. - 60 takeovers and 180 fenced writes. The summary totals equal the sum of the two test arms underneath them (30 owner crashes and 30 owner pauses, 90 fenced writes each). A total that didn’t match its parts would be the first sign of a hand-edited number.
false_takeovers=0matters as much as the 60: a takeover from an owner that was actually fine would be its own bug. - The late result. Three things line up: the API’s rejection code, the worker’s own log line with
status=409 code=STALE_ATTEMPT, and the checker’s view of the database afterwards, which says the stale attempt exists, isn’t current, and has no result recorded. A rejection in a log with the result quietly stored anyway would be the failure to look for.
Two things the script printed that I hadn’t gone looking for. The local recovery file records the commit it was produced at, c50960c, from September 20. The repository is 522 commits past that now. And its own limitations list says one scenario (a scheduler stuck while holding the lease row’s lock) “remains unresolved,” while the current README says that repair is done and verified. Both can be true, since the README was updated later. But it’s a good reminder that an evidence file is a statement about one commit, and the number in the README is a link to the past.
Replaying the project’s checker. A results file that says “checker: PASS” is still the project grading itself. The repository also commits the raw material: for each of the 48 cases, a trace of what the fault harness did and a snapshot of the database rows afterwards. That means I can rebuild the checker from today’s source and re-run it over the saved data, offline. archive-check.sh is a bash version of the project’s own PowerShell script for this:
$ docker run --rm -v "$PWD":/src -v "$PWD/../lab":/lab:ro -w /src golang:1.27.4 /lab/archive-check.sh
traces=48 pass=48 fail=0
Does the checker actually check? A checker that says valid to everything would produce the same output. So I broke one snapshot on purpose. tamper.py copies the saved rows for a lease-fence case and rolls the last scheduler write back to an older epoch, which is what a stale scheduler getting a write through would look like:
$ python3 ../lab/tamper.py experiments/m5/durable/F08-lease-fence-seed11.json .scratch-lab/F08-tampered.json
revision 3: SchedulerEpoch 740 -> 739
$ fault-checker -offline -trace .../F08-lease-fence-seed11.jsonl -durable-trace .scratch-lab/F08-tampered.json
{"runs":1,"valid":false,"violations":["scheduler epoch moved backwards: m5-fixture-F08-lease-fence-..."]}
exit=1
It caught it, named the rule, and exited non-zero. That one negative test is what makes the 48 passes mean something.
So the evidence holds up: all four claims are supported by the files they link to. What the files can’t tell me is whether the running system behaves that way on my machine today. That’s the rest of the lab.
4. One workflow, read from its own history
Before breaking anything, I wanted to see what “normal” looks like, because every later step is a comparison against it.
$ ../lab/submit.sh add-1 lab-add pure.add '[1,2,3]'
{"workflow":{"workflow_id":"add-1", ... "partition_id":0,"state":"RUNNABLE","revision":1, ...},"created":true}
HTTP 201
When I checked a few seconds later the status endpoint said "state":"SUCCEEDED","revision":12; by its own timestamps the whole thing took 160 milliseconds. The engine keeps an append-only history of every change, and GET /v1/workflows/add-1/history returns it. The first few entries, trimmed:
rev actor who epoch attempt reason
1 client client - - WORKFLOW_CREATED
2 scheduler runtime-scheduler 1 - ACTIVITY_SCHEDULED
3 scheduler runtime-scheduler 1 1 ATTEMPT_CREATED
4 worker worker-a-1 - 1 ATTEMPT_RESULT_RECORDED
This table is the thing to learn to read, because all three fences from the Architecture section are visible in it:
revis the workflow revision. It goes up by exactly one per change, with no gaps. A gap or a repeat would mean two writers both thought they were next.epochappears only on scheduler rows and is the lease epoch that scheduler held when it wrote. Within one workflow’s history it should never go down. That’s precisely the rule my tampered snapshot broke in step 3.attemptis which try at the activity this row belongs to. Here there’s only attempt 1. In the next step there will be two, and the question will be which one’s result counts.whoon a worker row is the name the worker gave. Remember that this is a name the caller typed. It comes back in step 10.
The outbox is visible too. One two-step workflow produced ten messages, each written in the same transaction as the state change it describes, and all published:
event_type | topic | publish_state | count
--------------------------+-------------------------+---------------+-------
activity.result | durable-agent.events.v1 | PUBLISHED | 2
attempt.dispatch | durable-agent.tasks.v1 | PUBLISHED | 2
graph.advanced | durable-agent.events.v1 | PUBLISHED | 3
workflow.created | durable-agent.events.v1 | PUBLISHED | 1
workflow.result_consumed | durable-agent.events.v1 | PUBLISHED | 2
Only the two attempt.dispatch rows are work for a Python worker. The other eight are the engine telling itself what happened. Ten messages for two activities is worth remembering for step 8.
5. Freezing a worker mid-task
This is the README’s headline claim, reproduced from scratch. zombie-worker.sh submits the 20-second sleep workflow, waits until the database shows a worker has claimed it, freezes that worker’s container, waits for the engine to finish the workflow some other way, and then thaws the frozen worker to see what it does.
The core of it:
OWNER=$(q "SELECT worker_id FROM engine.activity_attempts WHERE workflow_id='$WF' AND state='CLAIMED'")
SVC=${OWNER%-*} # worker-a-0 -> worker-a
"$LAB/dc.sh" pause "$SVC" # the zombie is made
until [ "$(q "SELECT state FROM engine.workflow_executions WHERE workflow_id='$WF'")" = "SUCCEEDED" ]; do sleep 1; done
"$LAB/dc.sh" unpause "$SVC" # and wakes up
I ask the database which worker owns the attempt instead of guessing, because Kafka decides which worker gets a task and it isn’t always the same one. The run:
[14:23:01] submit slow-1
[14:23:02] attempt 1 claimed by worker-a-0; freezing service worker-a
attempt | state | is_current | worker_id | hb_deadline
---------+---------+------------+------------+-------------
1 | CLAIMED | t | worker-a-0 | 14:24:01
[14:24:22] workflow SUCCEEDED while worker-a is still frozen
attempt | state | is_current | worker_id | hb_deadline
---------+-----------+------------+------------+-------------
1 | TIMED_OUT | f | worker-a-0 | 14:24:01
2 | SUCCEEDED | f | worker-b-0 | 14:25:16
[14:24:22] thawing worker-a
[14:24:47] worker-a log lines about slow-1 after the thaw:
INFO:workers.runner:activity result submission workflow_id=slow-1 node_id=dur048.sleep iteration=0
attempt_number=1 worker_id=worker-a-0 attempt_state=SUCCEEDED payload_sha256=5aa762ae...
outcome=rejected status=409 code=STALE_ATTEMPT retries=0
What each part shows:
hb_deadlineis the attempt’s own small lease. A worker sends a heartbeat (an “I’m still here” call) every 3 seconds, and each one pushes the deadline out to 60 seconds from now. A frozen worker sends none, so the deadline stayed at 14:24:01.- At 14:24:01, on the second, the scheduler marked attempt 1
TIMED_OUTand created attempt 2. The workflow’s history shows it as one row:rev 4, scheduler, epoch 242, attempt 1, TIMEOUT_REPLACEMENT, 14:24:01.891. The timeout was judged by the database clock against a deadline stored in the database, so nobody’s local clock was involved. worker-b-0ran attempt 2 and finished 20 seconds later. The workflow was done at 14:24:22, with the first worker still frozen.- The thawed worker did exactly what a zombie does. From its point of view it had just finished its 20-second sleep. It reported
attempt_state=SUCCEEDEDfor attempt 1 and got409 STALE_ATTEMPT.409is HTTP’s “conflict”: the request was understood and refused because of the current state of the thing. - The final table is the proof, not the log line. Attempt 1 is still
TIMED_OUTwith no result. If the late write had been stored, that row would saySUCCEEDED. A rejection message with the data saved anyway is the classic way this goes wrong, so always check the rows.
For a second opinion I ran the project’s invariant checker over my own workflows. It’s a Go package inside the repository, so a 30-line program, labcheck, copied into the repo’s cmd/ folder, can call it on any workflow ID:
$ ../lab/gorun.sh go run ./cmd/labcheck add-1 slow-1
add-1 valid=true violations=[]
slow-1 valid=true violations=[]
Total cost of the failure: 81 seconds for a 20-second task. That’s 60 seconds of waiting for the attempt to time out plus 20 seconds to redo the work. The work the frozen worker had finished was thrown away, which is the correct trade: the engine can’t tell a frozen worker from a dead one, so it has to choose between possibly doing the work twice and possibly never doing it. This is why the activity has to be safe to run twice, and why the project treats anything with outside side effects so differently (Reality Check 5).
One more number from that history. The lease epoch on this workflow’s partition was 1 when the task was scheduled and 242 when it timed out a minute later. The schedulers were taking and releasing that partition’s lease about four times a second the whole time the workflow sat waiting. Hold that for step 8.
6. Stopping a scheduler
Same idea, different victim. scheduler-down.sh waits for a worker to claim the task, then stops the scheduler replica that worker reports to. With two schedulers and a lease that expires in seconds, I expected this to be the boring one.
[14:44:49] submit sched-1 (20s activity)
[14:44:50] claimed by worker-b-0, which reports to runtime-b; stopping runtime-b
[14:47:11] sched-1 SUCCEEDED with runtime-b still down
attempt | state | worker_id
---------+-----------+------------
1 | TIMED_OUT | worker-b-0
2 | SUCCEEDED | worker-a-1
INFO:workers.runner:activity result submission workflow_id=sched-1 ... attempt_number=1 worker_id=worker-b-0
attempt_state=SUCCEEDED ... outcome=rejected status=503 code=CONTROL_UNAVAILABLE retries=0
Two minutes and 22 seconds for a 20-second task. The history explains where the time went:
rev actor epoch attempt reason time
3 scheduler 887 1 ATTEMPT_CREATED 14:44:49.741
4 scheduler 1013 1 TIMEOUT_REPLACEMENT 14:45:49.806
5 scheduler 1074 2 REDISPATCH_UNCLAIMED 14:46:20.303
6 scheduler 1135 2 REDISPATCH_UNCLAIMED 14:46:50.807
7 worker - 2 ATTEMPT_RESULT_RECORDED 14:47:10.841
The scheduler takeover itself was fine: runtime-a carried on writing with higher epochs and nothing was lost. The delay came from somewhere I hadn’t looked. In the Compose file, each worker has one environment variable naming the API it talks to:
worker-b:
environment:
CONTROL_API_URL: http://runtime-b:8080
worker-b only knows about runtime-b. When runtime-b stopped, worker-b finished its 20-second task and had nobody to tell: 503 CONTROL_UNAVAILABLE, logged as outcome=rejected with retries=0. That finished result was never delivered. Then it got worse. worker-b was still connected to Kafka and still looked like a healthy consumer (Kafka’s word for a process reading messages; Kafka splits a topic into partitions and assigns each one to a consumer), so when the replacement attempt was dispatched, twice, it went unclaimed for 30 seconds each time (the REDISPATCH_UNCLAIMED rows) before worker-a finally picked it up. My reading is that those deliveries landed on the worker that couldn’t reach its API; worker-b’s log is a wall of control request unavailable through exactly that window. I didn’t trace the Kafka partition assignment to prove it, so treat that last link as likely, not confirmed.
Why it matters: nothing here broke a safety rule, and the checker would be happy. But “two schedulers” suggested more redundancy than the workers actually had. A scheduler outage took half the worker pool with it for as long as it lasted. Why it might not matter to you: this is a Compose file for a laptop, and the fix is ordinary: put both runtimes behind one address (a load balancer, or a Kubernetes Service) and point every worker at that. It’s the kind of thing that only shows up when you stop the box and watch the clock.
7. Pulling the database out
Reality Check 4 says everything assumes PostgreSQL is there. db-outage.sh starts a 20-second task, stops PostgreSQL five seconds in, pokes the API, waits 30 seconds, and starts it again.
[14:33:29] submit outage-2 (20s activity)
[14:33:34] stopping postgres with the activity in flight
[14:33:34] GET status -> 503 {"error":{"code":"DATABASE_UNAVAILABLE","message":"database is unavailable"}}
[14:33:35] POST new submit -> 503 {"error":{"code":"DATABASE_UNAVAILABLE","message":"database is unavailable"}}
[14:33:35] healthz a/b -> 200 {"role":"scheduler-a","status":"ok","version":"0.1.0-dev"} | 200 {"role":"scheduler-b","status":"ok",...}
[14:34:05] starting postgres again (outage ~35s)
[14:34:06] outage-2 SUCCEEDED
attempt | state | worker_id
---------+-----------+------------
1 | SUCCEEDED | worker-b-0
[14:34:06] retry the submit that got an error during the outage (same submission_key)
HTTP 201
INFO:workers.runner:activity result submission workflow_id=outage-2 ... outcome=accepted retries=7
Most of this is the engine behaving well, and it’s worth saying how:
- The API fails loudly and specifically.
503 DATABASE_UNAVAILABLEis the right answer. It doesn’t serve a cached “still running,” and it doesn’t accept a submission it can’t store. The project’s API notes are precise about what a client should do: retry the same submission with the same key, because a failed commit can be ambiguous. - The worker held its result. It finished its sleep about 15 seconds into the outage, with the database gone, and kept retrying (
retries=7) until it got through. The result was accepted on attempt 1. No replacement, no wasted work. - Recovery took one second after PostgreSQL was back.
- The retried submission returned
201, creating the workflow once. The submission key did its job.
The outage was 35 seconds, shorter than the 60-second attempt lease. A longer one would have turned into step 5: attempt timed out, work redone.
The line that isn’t good is the third one. Both /healthz endpoints returned 200 ok while the database was down and every real request was failing. Compose’s health check, and anything else watching that URL, saw a healthy service. A load balancer would have kept sending traffic. This is the same thing as the second snag in step 1, and the same lesson KubeAPT taught me last time from the other direction: a check that reports “the thing exists” is an inventory. If you run something like this, point your monitoring at a request that needs the database.
What I couldn’t test is the part of the critique that actually bites: this stack has one PostgreSQL. I stopped it and started it and the data was still there. I did not lose the disk, fail over to a replica, or lose the last few commits, and the project’s README is careful to say its evidence doesn’t cover that either. Everything the fences guarantee is only as durable as that one database.
8. What each workflow costs the database
Reality Checks 1 and 2 are scale claims, and a laptop can’t be a large cluster. What it can do is count. PostgreSQL has an extension called pg_stat_statements that tallies every SQL statement the server runs, and the project’s Compose file already loads it. dbcost.sh resets the counters, measures 30 seconds of idle, resets again, submits N of the two-step lab-add workflows, waits for all of them, and reads the totals. I ran it at three sizes:
idle, 30s, zero workflows in flight: 308 statements, 0 touching partition_leases
1 two-step workflows, 3s wall clock: 641 statements, 66 touching partition_leases
rows left behind for those 1 workflows: history=12 outbox=10 inbox=10 attempts=2
50 two-step workflows, 7s wall clock: 84767 statements, 18220 touching partition_leases
rows left behind for those 50 workflows: history=600 outbox=500 inbox=500 attempts=100
200 two-step workflows, 15s wall clock: 356660 statements, 77479 touching partition_leases
rows left behind for those 200 workflows: history=2400 outbox=2000 inbox=2000 attempts=400
A second run at 50 gave 82,369, so the numbers are repeatable to within a few percent. Reading them:
- Idle is cheap. About 10 statements a second with nothing to do, and none on the lease table. The schedulers only take leases when there’s work.
- One workflow is 641 statements. That includes a few seconds of idle polling, so call it 600 for two trivial activities. 66 of those touched the lease table.
- Under a burst it’s about 1,700 per workflow (84,767 ÷ 50, and 356,660 ÷ 200 is 1,783), and roughly one statement in five touches
partition_leases. This is the four-times-a-second lease churn from step 5, seen from the database’s side. The top of the statement list wasbegin,commit, and the lease-rowSELECT ... FOR UPDATEfrom the Architecture section. - Every workflow leaves 32 rows behind: 12 history, 10 outbox, 10 inbox. Nothing cleaned them up. After the lab’s few hundred workflows the outbox table held 3,037 rows, all in
PUBLISHEDstate, none removed. The API notes say this is deliberate for now (“retention/deletion is a later operational policy”).
What this does and doesn’t show. It is not a load test. I submitted workflows one curl at a time from a shell loop, on one machine, with everything sharing the same CPUs. I’m not claiming a throughput ceiling, and the project’s own measurement on this point is modest too (two schedulers kept up with 2 workflows a second where one didn’t). What the count does show is the shape the critique described: the cost is in round trips to one database, the lease table is a hot spot in that traffic, and storage grows with every workflow until someone writes the cleanup job. At 32 rows per small workflow, a million workflows is 32 million rows before the first index.
9. Moving the database “to another region”
Reality Check 3 is about multi-region deployments, which sounds like the textbook “can’t test that on a laptop” case. But the claim isn’t really about geography. It’s about what happens when each trip to the database takes longer. That I can fake.
Toxiproxy is a small proxy from Shopify built for exactly this: you route a connection through it and tell it to add delay, drop packets, or cut the line. A Compose overlay file, compose.latency.yaml, adds it to the stack and changes one setting on each runtime so their database connection goes through the proxy:
runtime-a:
environment:
DATABASE_URL: postgresql://${POSTGRES_USER}:${POSTGRES_PASSWORD}@toxiproxy:5432/${POSTGRES_DB}?sslmode=disable
Workers and Kafka are untouched; only scheduler-to-database traffic is slowed. latency.sh sets a delay in each direction, runs ten lab-add workflows one at a time, and reads how long each took from the engine’s own history timestamps (first row to last row, database clock), so my script’s polling isn’t part of the measurement.
$ ../lab/latency.sh "0 5 20 40"
+0ms each way (round trip +0ms): n=10 min=104ms median=139ms max=631ms
+5ms each way (round trip +10ms): n=10 min=3325ms median=3460ms max=3669ms
+20ms each way (round trip +40ms): n=10 min=11763ms median=12090ms max=12371ms
+40ms each way (round trip +80ms): n=10 min=25601ms median=34534ms max=42199ms
I did not expect that. Ten milliseconds of added round-trip time, which is roughly two data centers in the same metro area, turned a 139-millisecond workflow into a 3.5-second one. Eighty milliseconds, about a US coast-to-coast link, made it 34.5 seconds.
The slope is the interesting part. Going from +0 to +10 ms added about 3,300 ms, and from +0 to +40 ms added about 12,000 ms. Divide either one and you get roughly 300 to 330: the workflow makes about 300 sequential round trips to the database, each one waiting for the last. That lines up with the 641 statements from step 8, since a lot of those travel together (a begin, a query, and a commit aren’t always three separate waits). Two different measurements, from two different tools, landing on the same picture is why I trust it. The slowest setting doesn’t fit the line as neatly: it works out to about 430 round trips, with a much wider spread (25 to 42 seconds). My guess is that at that delay some operations start hitting the 2-second lock timeout the Compose file sets on PostgreSQL and get retried, but I didn’t dig into it.
And it stayed correct. I ran the checker over a workflow from the slowest batch:
lat40x1795531052-9 valid=true violations=[]
That is exactly what the critique said: safety survives, usability doesn’t. The fix for a design like this is not clever. Keep the schedulers in the same place as the database. Workers can be far away, since they make a handful of HTTP calls per task; schedulers can’t.
10. Forging a result
Everything so far has been about a stale writer: someone who was legitimate and is now out of date. Reality Check 6 is about a different thing: someone who was never legitimate at all.
The project’s API notes are direct about this. The worker routes “are unauthenticated and accept caller-declared worker_id because this is a localhost-bound development API only.” I wanted to see what that looks like in practice, and what the fences do about it. forge.sh plays a client that is not a worker. It submits an add-workflow for [1,2,3], then:
== 2. claim the task with a made-up worker name
{"attempt_number":1,"claim_token":"a74c1c00-60d7-48f4-8d39-f5ad9bfd365e","effect_class":"PURE_ACTIVITY", ...}
== 3. control: a result with the wrong token
POST /v1/workflows/forge-1/nodes/pure.add/iterations/0/result
body: {"attempt_number":1,"claim_token":"00000000-0000-4000-8000-000000000000","attempt_state":"SUCCEEDED","payload":999999}
{"error":{"code":"STALE_ATTEMPT","message":"the attempt is no longer current"}}
HTTP 409
== 4. the forged result, with the token the API just handed us (1+2+3 is not 999999)
body: {"attempt_number":1,"claim_token":"a74c1c00-60d7-48f4-8d39-f5ad9bfd365e","attempt_state":"SUCCEEDED","payload":999999}
{"Disposition":"ACCEPTED","WorkflowID":"forge-1","NodeID":"pure.add","Iteration":0,"AttemptNumber":1,"AttemptState":"SUCCEEDED","Payload":999999}
HTTP 200
== 5. replay the same result, then replay it with a different payload
{"Disposition":"ACCEPTED", ... "Payload":999999}
HTTP 200
{"error":{"code":"RESULT_CONFLICT","message":"result conflicts with the durable receipt"}}
HTTP 409
Then the real workers were thawed, picked up the second step, and echoed what they were given:
node_id | state | accepted_result
-----------+-----------+-----------------
pure.add | SUCCEEDED | 999999
pure.echo | SUCCEEDED | 999999
node_id | attempt | state | worker_id
-----------+---------+-----------+-------------------
pure.add | 1 | SUCCEEDED | not-a-real-worker
pure.echo | 1 | SUCCEEDED | worker-a-1
Step by step:
- Step 2 is the whole attack. The claim endpoint took a name I made up and gave me a claim token. The token is the fence for worker results, and the API hands it to whoever asks first.
- Step 3 is the control, and it passed. A result with a token I invented was refused. The token check works; you can’t guess your way in.
- Step 4 is the finding. With the token from step 2, a false answer was accepted. From the engine’s point of view, nothing unusual happened: the current attempt’s holder reported a result.
- Step 5 shows the replay protection is real, too. Sending the same result again returns the same receipt (idempotent, as designed). Sending a different result for the same attempt is refused with
RESULT_CONFLICT. Once a result is in, it can’t be changed, by me or by anyone. - The real worker then built on the forged value.
pure.echofaithfully echoed 999999, and the workflow endedSUCCEEDED.
Two honest caveats about how I set this up. I froze both real workers before submitting, so my curl would win the claim. In a live system a forger has to beat the real worker to the claim, which normally happens within milliseconds of the task being dispatched. That’s a race, not a wall: a worker pool that’s busy, restarting, or stuck (see step 6, where a task sat unclaimed for a minute) leaves the window open. And I ran curl from the Mac against 127.0.0.1:8080, which is where the Compose file publishes the port. Inside the Docker network, every container can reach runtime-a:8080 directly, so “localhost-bound” describes the host, not the network the services share.
Then the part that makes this a lesson and not just a gotcha. I ran the project’s invariant checker on the forged workflow:
$ ../lab/gorun.sh go run ./cmd/labcheck forge-1
forge-1 valid=true violations=[]
The checker is right. Revisions are in order. Epochs never went backwards. There’s one accepted result per attempt, from the attempt’s current holder. Every rule the system promises was kept. The answer is still wrong.
This is the same shape as the forged receipt in the proofbundle post, where a signature check printed CRYPTO: OK for a receipt I’d signed with a key I made up: the check was correct about what it checked, and silent on whose key it was. A fencing token is a statement about time: this is the newest attempt. It was never a statement about identity. If a design review says “we have fencing, so stale or forged results can’t land,” those are two different claims and only the first one is covered.
11. So what, and how to do better
When this doesn’t matter. On one laptop, or on a private network where only the engine’s own services can reach the API, a forger has to already be inside, and someone inside has easier targets (the database password is in an environment variable on three of the containers). The project says not to expose this API, and means it.
When it does. The moment workers run somewhere the schedulers don’t fully trust: another team’s cluster, a shared network, a CI runner, a machine that also runs other people’s code. A workflow engine’s entire job is to act on results. If the result of “did the security scan pass?” or “is the backup verified?” can be supplied by anyone who can reach a port, the durability machinery will faithfully preserve the wrong answer.
Finding it after the fact. I looked for a durable trace that tells my forged claim apart from a real one, and there’s only one: the name. detect.sql has two checks.
workflow_id | node_id | attempt | claimed_identity | at
-------------+----------+---------+-------------------+----------
forge-1 | pure.add | 1 | not-a-real-worker | 14:25:16
workflow_id | input | accepted_result | recomputed
-------------+-----------+-----------------+------------
add-1 | [1, 2, 3] | 6 | 6
forge-1 | [1, 2, 3] | 999999 | 6
The first query lists results recorded by a worker name that isn’t on the list of real ones. It caught me, and it would not catch anyone careful, because the name is whatever the caller types. A forger who calls itself worker-a-1 is invisible to it. I’m including it because it’s cheap and catches accidents and lazy mistakes, not because it’s a control.
The second is stronger: the engine stores each activity’s input next to its accepted result, so for a deterministic activity you can recompute the answer and compare. forge-1 says 999999 where the input says 6. That works for pure functions. It does nothing for “I restarted the server,” where the only evidence is the worker’s word.
Preventing it. The real fix is to make the worker prove who it is, and the project has started on that since the Rabbit Hole Generator picked it. On November 4 it added an authentication mode for its Kubernetes deployment (RUNTIME_TOKEN_AUTH=enabled). In that mode the API validates each caller’s Kubernetes ServiceAccount token (a short-lived credential the cluster issues to a pod) by asking the cluster’s own TokenReview API whether it’s genuine, and takes the worker’s identity from the verified token instead of from the request body. The code also refuses to turn authentication on unless the worker-facing routes are split from the operator-facing ones.
I read that code; I did not run it. It needs a Kubernetes API server to check tokens against, the local Compose file doesn’t enable it (RUNTIME_TOKEN_AUTH appears zero times in it), and the project lists its Kubernetes deployment work as unfinished. So: the right mechanism exists in the source, and I can’t tell you how it behaves.
The critique asked for more than authentication, and the gap is worth naming. It wanted each completion message “cryptographically bound” to the actor, the workflow, the attempt token, the decision, and an expiry. Authentication tells you a legitimate worker called. It doesn’t stop a legitimate worker from reporting on a task it wasn’t given, and it leaves nothing behind that a third party could verify later. The approval design in Oracle Patch Guard is what the stronger version looks like: a signature over the exact facts being approved, checked again right before the risky step. This project does something close to that for its approval-gated effects (an approval is tied to a hash of the exact proposal). Its ordinary worker results don’t get the same treatment.
Where this fits in a real environment
As software to run, this isn’t something to deploy, and its author would be the first to say so. It’s a study project with a PowerShell-first toolchain, a development-only API, and a single database.
As something to read, it’s one of the better things the Rabbit Hole Generator has handed me. If your team is choosing a workflow engine, building a job queue, or reviewing someone’s “exactly-once” claim, this repository is a compact, honest reference for what the claim costs: three separate fences, an outbox, an inbox, a history table, a checker that isn’t the code under test, and a README that states what each piece of evidence does not show. The habit of linking every number to a file, and committing the raw traces so a stranger can replay the checker (lab step 3), is worth copying into any project that makes reliability claims. The NEEDLE post covered a tool with the same instinct applied to coding agents: fix every step around the unreliable part, and don’t take the worker’s word that it finished.
The lab also gives you a short list of questions for any engine in this category, including the commercial ones. What stops a paused worker’s late write, and can I see the row that proves it wasn’t stored (step 5)? What does a worker do when its API is gone (step 6)? Does the health check need the database (step 7)? How many database round trips is one workflow, and where does the scheduler sit relative to the database (Reality Check 3)? Who is allowed to report a result, and what proves it was them (Reality Check 6)? Who deletes the outbox rows (Reality Check 2)?
Actionable Takeaways
- Derive the number, don’t search for it. “48 cases passed” was the length of a list, not a field. Write the 40-line script that computes each claim from the artifact, and note which commit the artifact came from.
- Break the checker once. 48 passes meant something only after a tampered snapshot produced a named violation and a non-zero exit.
- Look at test durations, not just
ok. A fencing package that passes in 0.005 seconds didn’t test fencing. Find out what a suite skips without its database. - Check the row, not the log line. A
409in a worker log is a claim. The attempt row still sayingTIMED_OUTwith no result is the evidence. - Test failover with
docker pause, not onlydocker kill. A dead process is the easy case. A frozen one that wakes up and writes is the case fencing exists for. - Keep schedulers next to the database. About 300 sequential round trips per workflow turned 80 ms of latency into 34 seconds.
- Ask “fresh” and “authentic” as separate questions. Fencing tokens answer the first. Only authenticated, ideally signed, results answer the second, and an invariant checker will pass a forged result that follows the rules.
- Point health checks at something that needs the database. Both replicas said
okwhile every real request returned503.
A fence keeps out the writer who used to belong there. It takes something else to keep out the one who never did.