Skip to content

Second-writer fence and thread expiry

Status: decided, 2026-11-13: option (a) was taken on every decision in §8 (ADR-0017 to ADR-0024). It answers the questions the fence and expiry design left open for features 8 and 9. Upstream here means langgraph-checkpoint-postgres 3.2.0, langgraph-checkpoint 4.3.1 and langgraph 1.2.20 on PostgreSQL 16.16. No product code changes in this spike; the three experiments it rests on (E1–E3) are reproduced in full in the appendix with their output, and were run once on the spike's commit (measured below means "by that run"; the appendix is the record).

Answer in brief

  • One row per thread, opc_thread_head, keyed by thread_id alone: the root namespace's head checkpoint id, a generation number drawn from one global sequence, and the time of the last write on the database's clock. It is the fence's lock and the expiry clock in one row.
  • Fence: every read mints an opaque token [thread_id, generation, checkpoint_id] into the returned config and parent_config. A root-namespace put that carries a token is admitted only if its parent is the current head, or if nothing of ours wrote since the read and the put starts from the checkpoint that was read. The check is a few CTEs inside the existing single PUT_SQL statement. A refused put writes nothing and raises a new, non-retryable ThreadConflictError. A put with no token (upstream's conformance suite, direct callers) is admitted as today.
  • Expiry: inactivity on the database clock. asweep_expired(idle_for=…) deletes whole threads idle longer than idle_for, one thread per statement, and in that statement re-checks the generation it chose, the idle time, and the checkpoint table, so a thread deleted and re-created is never swept.
  • rehydrate leaves head rows alone; they hold nothing upstream must read, and deleting them would make every running saver of ours refuse its next put.

1. What upstream does that the design depends on

# Fact Evidence
U1 The configurable of the tuple a run reads (saved.config) is merged into every put of that run, unchanged; the config aput returns is discarded. A token minted at the read therefore rides on every put of the run and is stale after the first. E1 (measured): the read's probe on all puts of a turn; RETURNED-BY-APUT on none. pregel/_loop.py:1883-1892 merges saved.config; _checkpointer_put_after_previous (_loop.py, async loop) awaits aput and drops its result
U2 update_state(as_node="__copy__") puts against saved.parent_config, so a fork from the head's parent carries whatever the read put in parent_config. E1: the fork put carries the /parent probe; pregel/main.py:2375-2378
U3 Each Pregel path's first put: a new invoke writes input from the head it read; a resume writes loop from the head it read (no input put); update_state writes update; time travel writes fork from the old checkpoint; durability="exit" writes one loop put whose parent is the checkpoint read (or none on a new thread). Every later put of the run has the run's own previous put as parent. E1
U4 A subgraph writes its own namespace (node:<task id>, new per parent checkpoint); its first put has no parent and no token. Parallel subgraph tasks write separate namespaces concurrently. E1; plan's wiki concept scope-by-thread-and-namespace
U5 When a put raises: under durability="async" (the default) and "exit" every node of the run has already run when the error surfaces; under "sync" no node runs after the refused put. A node RetryPolicy never retries a saver error; the error leaves ainvoke. E3 (measured)
U6 aput_writes can commit before the aput of its own checkpoint. write-ordering.md column 6 (measured)
U7 Upstream's conformance suite puts many unparented checkpoints, with sources input, loop and update, into one thread, and never passes a token. langgraph/checkpoint/conformance/spec/test_list.py:31,283, test_utils.py:55-106
U8 "Latest" is the highest checkpoint_id in a namespace under the column's collation (en_US.utf8 in the test container); checkpoint ids are client-side uuid6, and copy_thread keeps them. Upstream's ORDER BY checkpoint_id DESC; aio.py acopy_thread; E2.9

U1 is the constraint the premortem called unconfirmed. It holds, and it rules out any design that checks a token on every put: a token is only fresh for the run's first put.

2. Fence (feature 8)

2.1 The head row

CREATE SEQUENCE opc_head_seq;
CREATE TABLE opc_thread_head (
    thread_id  text PRIMARY KEY,
    head_id    text,                -- root namespace's head; NULL for a row put_writes made
    seq        bigint NOT NULL,     -- generation: nextval on every head move; 0 = row made by put_writes
    touched_at timestamptz NOT NULL DEFAULT now()
) WITH (fillfactor = 70);

Keyed by thread_id alone, for two reasons. The race the fence exists for is two runs on one thread, and both always write the root namespace (U3); subgraph namespaces are new per parent checkpoint (U4), so they never collide between racing runs, and a counter shared across them would make parallel subgraph tasks conflict with each other (premortem item 1). And expiry is per thread, not per namespace (per-namespace expiry leaves subgraph rows behind). Only root namespace puts move the row; a subgraph put, like aput_writes, only creates it when it is missing (§3.1).

No column is indexed except the key, so every update can be HOT: 1,005 updates of one row in E2.11 were all HOT at fillfactor 70 (measured).

2.2 The token

aget_tuple and alist read the row's seq with the checkpoint (one more primary-key probe, joined into the existing statement) and add to configurable, for root namespace tuples only:

  • config: __opc_head = '["<thread_id>", <seq>, "<checkpoint_id>"]'
  • parent_config: the same with the parent's id (U2: __copy__ reaches the check only this way).

seq is 0 when the thread has no row (an adopted thread upstream wrote). The __ prefix keeps it out of checkpoint metadata (langgraph/checkpoint/base/__init__.py:798), as attempt 1 found. The value is an opaque string so it survives JSON and msgpack round trips. A token whose thread does not match the put, or that is malformed, is treated as absent. This is attempt 1's helper pair (_mint_head_token / _head_token_seq), qualified by thread instead of namespace and extended with the checkpoint id.

2.3 The admission rule

For a root namespace put with parent P, new checkpoint N and token (s, A):

Arm Admit when Covers
idempotent head_id = N A retried put whose first attempt committed (one round trip per put, safe to retry: a retry is a no-op). Head unchanged
forward head_id = P, and P still exists Every put after the run's first (U3), and a first put from the current head
from the read seq = s, P = A, and A still exists A run's first put when nothing of ours wrote since its read: time travel, __copy__, and a resume after an upstream saver wrote during a rolling deploy (E2.4)
first write no row, and either no token, or s is 0, P = A and A still exists An adopted thread, a new thread
no token always Conformance (U7), direct aput callers, a run's first put on a new thread (its read returned nothing)

Unlike attempt 1, the rule never looks at metadata["source"]: the "from the read" arm covers every deliberate branch, because a branch is exactly a first put whose parent is the checkpoint the run read. Admitting moves head_id to N, sets seq = nextval('opc_head_seq') and touched_at = now().

It runs inside PUT_SQL, in the same statement and round trip, as an UPDATE … RETURNING CTE plus an INSERT … ON CONFLICT DO UPDATE … WHERE … RETURNING CTE for the no-row case. The blob, patch and checkpoint inserts carry WHERE <admitted>, the pattern PUT_SQL already uses for the opc_patching_off switch. Under READ COMMITTED (autocommit) a second writer blocks on the first writer's row lock and then re-evaluates the arms against the committed row, so it fails the forward arm. A racing insert on a thread with no row conflicts and meets the same arms on the committed row. The appendix's E2 statement is the prototype.

Case (E2, measured) Result
E2.1 Two runs read head H and race their first put First admitted; second blocked on the row lock, then refused; one checkpoint written
E2.2 The two runs' next puts Winner's forward put admitted, loser's refused
E2.3 The same race on an adopted thread with no head row First inserts the row; second refused
E2.4 Upstream wrote a newer checkpoint than our head; our run resumes from it Admitted (from the read)
E2.5 A run that read before delete_thread continues, before and after the thread is re-created Refused both times
E2.6 A put with no token from a non-head parent Admitted

Generation 0 needs the read checkpoint. A backfilled row, a row put_writes made and a thread with no row all carry generation 0, so the generation alone cannot tell a run that read a since-deleted thread from one that read an adopted thread. Without more, such a run was admitted after adelete_thread or a sweep, through the first-write arm or, once its own put_writes re-created a generation-0 row, through the from-the-read arm. Both arms therefore also require, at generation 0, that the checkpoint the run read still exists, and the first-write arm admits only the run's first put (P = A). Generation 0 stays for those rows: a run's writes can commit before its first put (U6), and a fresh generation on that row would refuse the run's own first put. Tests: test_a_run_that_read_an_adopted_thread_is_refused_after_delete_thread and test_a_run_on_an_adopted_thread_deleted_mid_run_is_refused_at_its_next_put, both failing before the change (measured).

A head row that appears during the put. On a thread upstream created after our setup(), the run's own put_writes often inserted the generation-0 row while its first put was in flight (U6): after the put's snapshot, so moved could not see it, and before the put's insert, which then conflicted and did nothing. The put was refused, and the head left at NULL. A loop of 20 such threads was refused 16 times on each of a plain, a DeltaChannel and a subgraph graph (measured). The insert now resolves its conflict with DO UPDATE … WHERE and moved's arms. Postgres evaluates that condition on the row's newest version under its row lock, so the run is admitted by the from-the-read arm, and a racing put of ours that moved the head is still refused (E2.3). The same path fixes a retry that overlaps its first attempt: it is now admitted and keeps the first's generation, where before it was refused. Tests: test_a_run_whose_writes_give_an_upstream_thread_its_head_row_first_is_admitted and test_a_retry_overlapping_its_first_attempt_on_a_thread_with_no_head_row_is_admitted, both failing before the change (measured).

A head row whose checkpoints were deleted under it. Upstream's delete_thread deletes only its own three tables, so our row stays and still names the deleted head, at a generation the run's token matches. A run that read the thread before the delete was admitted at its next put by the forward arm (head_id = P) and, for a fork, by the from-the-read arm at a non-zero generation, writing a checkpoint onto the deleted thread. Both arms now also require that P still exists, the probe the generation-0 rule already made for A (P = A in that arm). It covers our own delete_for_runs too, which leaves the head row when it deletes the head: a run still going from a deleted checkpoint is refused at its next put instead of writing a checkpoint with no parent. A put that commits while the delete runs still sees P in its snapshot and is admitted, as delete_for_runs expects (architecture.md §7). The probe moves from A to P, so the forward arm, every put after a run's first, pays one primary-key probe it did not before (inferred, not benchmarked). Tests: test_a_run_that_read_before_upstreams_delete_thread_is_refused, test_a_fork_from_a_checkpoint_upstreams_delete_thread_removed_is_refused and test_a_run_whose_parent_delete_for_runs_removed_is_refused_at_its_next_put, all three failing before the change (measured).

A tokenless put that waited on the sweep. A put without a token waits on the head row a sweep holds; once the sweep has deleted the thread, moved finds no row and created's "no row yet" check, read in the statement's snapshot, still sees the deleted one. The put was admitted with no head row, and its checkpoint was never swept. created now also inserts for a tokenless put that moved did not admit: moved admits every tokenless put whose row exists, so admitting none means the row is gone. Test: test_a_put_without_a_token_that_waited_on_the_sweep_still_expires, failing before the change (measured).

2.4 What the fence does not cover

  1. Two first runs on a thread that does not exist yet. Their reads return nothing, so no token exists, and conformance (U7) rules out refusing an unparented put on an existing thread. Both are admitted, as today.
  2. Upstream savers during a rolling deploy. They take no lock on our row. A race between one of theirs and one of ours is not detected. Their writes never cause a false refusal (E2.4).
  3. Puts without a token (by design, U7).
  4. Subgraph namespaces. Not fenced; a race is caught at the root namespace's next put.
  5. Double execution. The fence picks the winner; it does not stop the loser's nodes (U5).

2.5 What the loser sees

ThreadConflictError(CheckpointerError) in _errors.py, raised from aput, with the thread, the put's parent and the current head. Nothing of the put is written. The saver does not retry it (a retry with the same config is refused again), and it is not a subclass of anything a retry loop catches. Its message says what U5 measured: under the default durability="async" the run's nodes have already run, so their side effects (tool calls, model spend) happened and are lost from the thread. An application that needs the loser to stop before its side effects uses durability="sync". The application decides whether to re-read and run again; for a racing chat turn that means re-submitting the message on top of the winner's turn.

2.6 Interactions

  • full_copies_only and opc_patching_off: the fence and the head row work the same in every mode (decision D6). The switch's refusal and the fence's refusal must be distinguishable in PUT_SQL's result (a status column), since one retries with full copies and the other raises.
  • aput's ForeignKeyViolation retry (a base deleted under a patching writer): the first attempt rolled back whole, head move included, so the retry meets the same rule.
  • Rolling deploy (ADR-0009): our replicas fence each other from the first deploy; see §2.4 item 2 for upstream's replicas.

2.7 Alternatives weighed

Alternative Why not
Check the token on every put U1: stale after the first put, so every second put of every run is refused
Attempt 1's shape: CAS on head for loop, token only for fork/update/input from a non-head parent Refuses a resume after an upstream write in a rolling deploy (a loop first put from a checkpoint our head does not know); needs source, which the "from the read" arm makes unnecessary
Per-row counter instead of a global sequence delete_thread then a new write restarts it, and a stale token matches again (attempt 1's ABA, premortem item 5)
head_id as the version, no counter copy_thread keeps checkpoint ids, so a deleted and re-copied thread can get its old head_id back
Compare the parent with the newest checkpoint_id in checkpoints, no head row A statement's snapshot does not see a concurrent uncommitted put, so both racers pass; and ids are client clocks (U8)
A unique index on (thread_id, checkpoint_ns, parent_checkpoint_id) Forbids deliberate forks; misses two input puts with different parents; a write cost on upstream's table
An advisory lock plus a check in a second statement Two round trips per put (feature 2); the lock taken mid-statement does not refresh the snapshot
Fence every namespace One row per subgraph call (one per parent checkpoint, U4) for a race the root already catches

3. Expiry and the sweeper (feature 9)

3.1 Model

A thread expires as a whole when no root namespace put of ours touched it for idle_for, on the database's clock (touched_at = now() in the put's statement). Client clocks are never used: checkpoint ids are client uuid6 and copy_thread keeps them, so a fresh copy would look old (U8, premortem item 3). Expiry has a writer by construction (every put), which an earlier design lacked. An explicit per-thread expires_at is the alternative (decision D3).

Who writes touched_at:

Writer How
Root namespace aput The fence's head move
aput_writes, and a subgraph aput INSERT … (thread_id, NULL, 0, now()) ON CONFLICT DO NOTHING in its statement, so a thread whose only rows are writes (U6), or a run that wrote after its thread was swept, has a row and expires. It does not refresh an existing row; it holds it FOR KEY SHARE, so a sweep skips a thread whose writes are still uncommitted, which it could not see to delete (before, they were left with no row, as were a swept run's later subgraph checkpoints: test_writes_racing_the_sweep_of_their_thread_still_expire, test_a_subgraph_put_after_its_thread_was_swept_still_expires, both failing before the change, measured)
acopy_thread Creates or replaces the target's row with a new generation and now()
The ledger migration that creates the table Backfills one row per existing thread: head_id the newest root checkpoint, generation 0, now(). Adopted threads then expire idle_for after adoption unless written (decision D4). head_id must be set: the sweep's confirmation treats a NULL head as "no checkpoint of ours" and skips any thread that has a root checkpoint, which suits a row put_writes made but would put every adopted thread's expiry off by one more idle_for

3.2 The method

async def asweep_expired(self, idle_for: timedelta, *, max_threads: int = 100) -> SweepReport

The application calls it (on a schedule of its choosing); the saver starts no task. One call:

  1. Picks up to max_threads candidates: SELECT thread_id, seq FROM opc_thread_head WHERE touched_at < now() - idle_for ORDER BY touched_at LIMIT max_threads. No index (decision D8): a scan of one small row per thread.
  2. For each candidate, one transaction of two statements (the E2 SWEEP_ONE prototype, split 2026-11-18, below): lock the row FOR UPDATE SKIP LOCKED where seq is still the chosen one and it is still idle; then, in a snapshot taken after the lock, confirm against checkpoints that no root checkpoint newer than head_id exists and delete the row and every row of the thread in all four upstream tables (patch side rows cascade). The thread goes whole, in one statement, as adelete_thread deletes it. When a newer root checkpoint does exist, that statement sets the row's touched_at to now() instead: upstream writing is activity, and a thread left looking idle would be picked first on every pass, so max_threads of them would starve every other candidate (test_a_thread_upstream_still_writes_is_not_picked_again_by_the_next_sweep failed before the change, measured). It also moves head_id to the newest root checkpoint and keeps seq (see "A head behind the newest root checkpoint", below).
  3. Returns counts: swept, skipped because busy or changed, skipped on a ForeignKeyViolation or SerializationFailure (left for the next call), and whether more candidates remain.
Case (E2, measured) Result
E2.7 Candidate chosen; thread deleted and re-created before the delete statement Not swept; the new thread's checkpoint stays
E2.8 A put holds the row when the sweep statement runs Skipped without waiting (0.001 s, measured); not swept after the put commits either
E2.9 Upstream wrote a newer root checkpoint than our head Not swept; its touched_at is refreshed and its head moved to that checkpoint, so it is not picked again until it has been idle for idle_for once more, and then it is swept unless something wrote it
E2.10 Idle threshold 1 hour against a just-written thread; then 0 Not swept; swept; the running run's next put is refused

The generation from one global sequence is what makes E2.7 hold: a re-created thread can never get the chosen seq back. The checkpoint-table confirmation covers what our row cannot see: upstream's delete_thread leaves our row, and upstream re-creating the thread writes newer checkpoints. The comparison is the same one upstream uses for "latest" (U8); a client clock running behind can make it miss an upstream write, which only matters while upstream savers still write.

A head behind the newest root checkpoint. The refresh used to set only touched_at, so a thread whose newest root checkpoint sorts above its head was refreshed by every idle pass and never expired. Upstream's replica writing a thread last during a rolling deploy leaves it so, and so do puts of ours: the head is the last admitted put, not the highest id, so tokenless puts committing out of id order (two first runs on a new thread, an import copying alist() newest first) or a fenced put from a host whose clock is behind leave it on an older id. The refresh now also moves head_id to the newest root checkpoint, by the same collation as "latest" (U8), so the thread is swept one idle_for after the last write. It keeps seq: a token read before the refresh still matches the from-the-read arm, and only the forward arm of a run idle longer than idle_for loses its parent, which ADR-0023 already accepts. Keeping a tokenless put from moving the head back in PUT_SQL was rejected: it covers neither the upstream nor the lagging-clock case and adds conditions to the fence's statement. Tests: test_a_thread_upstream_wrote_last_expires_one_idle_period_later, test_a_thread_whose_tokenless_puts_left_its_head_behind_still_expires and test_a_thread_whose_fenced_put_came_from_a_lagging_clock_still_expires, all failing before the change (measured).

Isolation and locking. READ COMMITTED, one transaction per thread. Under REPEATABLE READ a row updated after the snapshot makes FOR UPDATE raise a serialization failure instead of skipping (inferred from PostgreSQL's documentation of FOR UPDATE at that level), and the skip is what keeps a pass moving past busy threads. The head row is the per-thread lock; no advisory lock is needed. copy_thread to a thread being swept sees it occupied and refuses; copy_thread from it reads one snapshot, as today.

Batching and cancellation. A pass is bounded by max_threads; each thread is its own transaction, so cancelling the call rolls back at most one thread and a re-run continues. The old repository's "sweeper cancellation fix" was psycopg>=3.3.6, which this repository already requires (pyproject.toml). The sweeper uses the saver's own pool, so an earlier design's lost connection settings cannot recur, and its failures raise typed errors or are counted, never swallowed. Rows are not bounded within one thread: a thread is deleted whole or not at all, the same unit as adelete_thread. Splitting a large thread across statements would show half-deleted threads to readers.

Composition with stage 4. adelete_thread and aprune(strategy="delete") delete the head row in the same statement (DELETE_THREADS_SQL gains a CTE), so a run still holding a token is refused at its next put (E2.5). _retain (prune, thinning, delete_for_runs) does not touch the row: it never moves the head, and a run continuing from a head checkpoint delete_for_runs removed is admitted, as the lifecycle rules intend. Such a run is now refused at its next put; see "A head row whose checkpoints were deleted under it". A patching writer racing the sweep's delete of a base makes that one thread's statement fail with ForeignKeyViolation; the sweeper counts it and moves on.

A delete racing a put or a write. DELETE_THREADS_SQL waited on the head row a put (its head move) or a write (FOR KEY SHARE) held, then deleted that row, but deleted the other rows only as its snapshot, taken before the writer committed, saw them. The writer's checkpoint and values, or its writes, were left with no head row, so no sweep ever found them, and aget_tuple on the deleted thread could return that checkpoint with its unchanged channels' values gone. adelete_thread and aprune(strategy="delete") now run one transaction: SELECT … FOR UPDATE on the head rows, ordered by thread_id so two deletes cannot deadlock, then DELETE_THREADS_SQL, whose READ COMMITTED snapshot is taken after the lock and holds what those writers committed. A writer arriving later waits on the lock and finds the row gone: a fenced put is refused, a write or a tokenless put creates a new row, which expires. Unlike the sweep, delete waits: the user asked for this thread to go. Tests: test_a_put_racing_the_delete_of_its_thread_is_deleted_too and test_writes_racing_the_delete_of_their_thread_are_deleted_too, each for both callers, all failing before the change (measured).

A write committing inside the sweep's statement. The sweep ran one statement per thread: its snapshot was taken when it started, then it locked the head row FOR UPDATE SKIP LOCKED and deleted the thread's rows as that snapshot saw them. A write or a subgraph put holds the row only FOR KEY SHARE and never updates it, so one that committed after the snapshot and before the lock left no lock to skip and no newer row version to re-check: the sweep deleted the head row and left the write's rows with no head row, where no sweep finds them. The sweep now runs, per thread, one READ COMMITTED transaction: SWEEP_LOCK_SQL locks the head row under the same generation and idle filters, and SWEEP_DELETE_SQL, whose snapshot is taken after the lock, re-checks for a newer root checkpoint and refreshes or deletes. Every writer of ours needs the head row, so none commits between the two statements: one that committed before the lock is in the second statement's snapshot and goes with the thread, and one arriving later waits on the lock and then finds the row gone, as for adelete_thread above. The cost is one more round trip per candidate. Upstream's saver never touches the head row, so the lock does not order its writes: an upstream root checkpoint committed before the second statement's snapshot is seen and refreshes the thread, one committed after it is left with no head row, as before this change (inferred from the statements). Tests: test_a_write_committing_after_the_sweeps_snapshot_but_before_its_lock_is_swept_too, for a write and a subgraph put, holds the statement that locks between its snapshot and its lock (a now() ahead of pg_catalog on the sweeper's search path, which the idle filter calls) while the write commits; both cases failed before the change, each leaving one row behind (measured). test_a_write_arriving_while_the_sweep_holds_the_head_row_waits_then_still_expires holds the sweep between its two statements and shows the write waits, then gets a head row of its own; it fails if the first statement does not lock, and the first test fails if both statements share one snapshot (measured, by changing the code and running the tests).

A thread that expires under a live run is deleted (decision D7). The run's next root put is refused (E2.10); its aput_writes in between land and re-create a row with generation 0, so those rows expire on a later pass. An earlier design's phantom row does not occur: a refused put writes nothing.

4. rehydrate

rehydrate leaves opc_thread_head and its sequence untouched (decision D5):

  • The rows hold nothing upstream must read, so the rollback promise (upstream reads every thread again) holds without them.
  • Deleting them would make every running saver of ours refuse its next put on every thread with a token in flight (E2.5a), and would drop expiry.
  • Savers of ours still running after a rollback (full-copies mode) keep writing them anyway, so a delete would not leave the table empty.

The compatibility promise carries this wording since 2026-11-13: rehydrate removes our patch and compressed-copy rows and the side rows naming them; head rows stay until the manual drop, which happens once no saver of ours runs (instead of "once every saver runs in full-copies-only mode", because a full-copies saver still writes head rows; decision D6). REHYDRATE_LEFT_SQL keeps counting only patches and tagged values.

5. Write cost: how stage 5 measures it

Not run in this spike. The dev host is IO-contended, so the run goes on an uncontended host from a clean commit.

  • Harness: benchmarks/s5_head_row.py (removed before publication), modelled on s4_run_index.py (removed before publication): the benchmark rule's arms, with ours at the stage 5 commit against ours at the stage 4 commit (head row absent), plain and DeltaChannel 400-step graphs, K = 1, 8, 32 threads on one saver.
  • Workloads beyond the benchmark rule's set (premortem item 9): a fan-out graph whose node Sends to N parallel subgraph tasks (subgraph puts do not touch the row, put_writes does), and a put_writes-heavy graph for the insert-if-absent probe.
  • Metrics: the benchmark rule's, plus put and put_writes p50 and p95 deltas against stage 4, head-row HOT ratio (pg_stat_user_tables), table bytes after VACUUM, and asweep_expired throughput (threads and rows per second at max_threads 100) on a thread fleet the size of s1's.
  • Judged against the acceptance put bars as they stand; the stage 4 delta is reported beside them.

What the cost should be, inferred from the shape: one HOT update of an 80-byte row, one nextval, and one primary-key probe per root put; one primary-key probe per put_writes; no new lock wait except between writers racing on one thread.

5.1 Result — measured

benchmarks/s5_head_row.py (removed before publication) on stage 5 against our stage 4 saver, both run in one invocation on an uncontended dedicated host (4 CPU, 8 GB, PostgreSQL 16.16, pool of 8, 3 repeats; contended: false; measured before public release). put p50 in ms is the median of the repeats; stage 4 runs in a child process loaded from the stage 4 tree, checked on every run (its database has no head table). Every thread's value was read back and checked.

Workload Upstream Stage 4 Stage 5 Stage 5 / stage 4
400-step plain graph 5.72 4.20 4.17 0.99×
400-step DeltaChannel graph 1.67 0.97 1.10 1.13×
K=1 plain / DeltaChannel 3.30 / 1.58 2.74 / 0.92 2.86 / 1.11 1.05× / 1.21×
K=8 plain / DeltaChannel 25.24 / 16.04 12.85 / 2.95 12.83 / 3.22 1.00× / 1.09×
K=32 plain / DeltaChannel 101.1 / 64.7 48.30 / 13.09 46.81 / 13.81 0.97× / 1.06×
Send fan-out to 50 subgraphs 96.5 36.12 34.94 0.97×
Send fan-out of 50 writes 15.79 12.73 12.50 0.98×
  • On the plain graph the head row costs nothing measurable (0.97–1.05×). On the DeltaChannel graph, whose puts store no value and so are cheap, it adds 0.13–0.72 ms at p50 (1.06–1.21×); ours stays faster than upstream there (1.10 against 1.67 ms sequentially).
  • put_writes is unchanged (p50 within 0.99–1.04× of stage 4 on every workload): its insert-if-absent finds the row present.
  • Every head-row update was HOT: 1,200 of 1,200 on a 400-step thread, 9,600 of 9,600 with 32 threads. Subgraph puts never touched the row: through 20 fan-out steps it saw 59 updates, the root namespace's puts alone, though each step also ran 50 subgraph tasks.
  • Disk: the head table is one 64 KiB relation at these sizes; a 400-step plain database grew from 9.40 to 9.51 MB above its empty schema.
  • Sweep: 50 idle threads of 1 MB (10,828 rows) went in one asweep_expired call in 226–262 ms, 191–221 threads and 41,000–48,000 rows a second.

Against the acceptance bars (stage 5): 400-step plain disk 6.9× smaller than upstream (bar 3×) and put 0.73× upstream's (bar 1.25×); 400-step DeltaChannel disk 0.93× upstream's (bar 1.05×) and put 0.66× (bar 1.10×); at K=32 put 0.46× and 0.21× upstream's (bar 0.5×) and turns per second above upstream's from K=8 up. The one miss is the known one: on the plain graph, K=8 put p50 is 4.49× our K=1 (bar 3×); stage 4 measures 4.69× in the same run, so the head row is not its cause. The miss was accepted at stage 3. The DeltaChannel graph passes it (2.90×). The 1–10 MB and memory rows are not this harness's workloads.

6. The premortem, item by item

# Item Disposition
1 Token stale after the first put; parallel subgraphs collide on a per-thread counter; check only branches, qualify, mint into parent_config Confirmed (U1, U2, U4). Token checked only on a first put ("from the read" arm); later puts use the forward arm; root namespace only; minted into parent_config
2 No head row on adopted threads, so two first runs both win; upstream never bumps our counter Refuted for runs that read a checkpoint: the read mints generation 0 and the racing insert conflicts (E2.3). Upstream writes cause no false refusal (E2.4). Residue: brand-new threads (§2.4 item 1). Checking the newest checkpoint_id instead: rejected (§2.7)
3 Use the database clock Adopted: touched_at = now()
4 What the loser experiences Measured (U5); §2.5 and decision D1
5 Delete then re-create restarts a counter Global sequence; E2.5 and E2.7
6 Writes-only threads never swept aput_writes inserts a row if absent (§3.1)
7 Sweeper against stage 4 and patching writers; SKIP LOCKED; advisory key family; copy_thread creates the target row Per-thread transactions, failures counted (§3.2); SKIP LOCKED (E2.8); no advisory lock, the head row is the lock; copy_thread writes the target row
8 rehydrate and head rows; does opc_patching_off stop head writes §4, decisions D5 and D6
9 Hot row cost inside the put statement; parallel-subgraph workload In PUT_SQL (§2.3); HOT (E2.11); §5

7. Stage 5 gate, made concrete

  • "Two racing forks cannot both win": integration tests through Pregel for two concurrent ainvoke, two aupdate_state, two __copy__, two time-travel invokes from one checkpoint, and a resume racing an invoke, each asserting exactly one winner and a ThreadConflictError for the other, plus E2's saver-level cases. Each guard mutation-checked (wiki guard-tests-must-be-able-to-fail). Upstream's conformance suite passes unmodified.
  • "A thread deleted and re-created is never swept": E2.7 and E2.9 as integration tests, through adelete_thread and through upstream's delete_thread.
  • "The write cost of the head row is recorded against the acceptance bars": §5.

8. Decisions

D1 — Fence check scope.

  • (a) Recommended. The rule in §2.3: puts with a token are checked (forward, from the read, idempotent, first write); puts without one are admitted. Pro: conformance unchanged; no dependence on source; tolerates upstream writes in a rolling deploy. Con: brand-new-thread races and token-less callers are not fenced.
  • (b) Attempt 1's: CAS for loop, token for fork/update/input from a non-head parent. Pro: proven in attempt 1. Con: refuses resumes after an upstream write (rolling deploy); relies on source.
  • (c) Every parented put must have the head as parent. Con: refuses time travel and forks; violates conformance.

Also confirm the loser's contract: ThreadConflictError, not retried by the saver, side effects under async durability documented, durability="sync" named as the way to stop them.

D2 — Token and generation.

  • (a) Recommended. Generation from one global sequence; token [thread_id, seq, checkpoint_id]. Pro: no ABA across delete, re-create or copy. Con: a nextval per root put.
  • (b) Per-row counter. Con: restarts after delete_thread; stale tokens match again.
  • (c) head_id as the version. Con: copy_thread can restore an old head_id.

D3 — Expiry model.

  • (a) Recommended. Inactivity on the database clock; the sweeper takes idle_for. Pro: a writer by construction; one parameter. Con: one retention period per call, no per-thread policy.
  • (b) Explicit expires_at per thread with a setter. Pro: per-thread or per-tenant retention. Con: dead without a caller; a second column and API.
  • (c) Both, expires_at overriding inactivity. Con: both costs; add when a caller asks.

D4 — Threads with no head row (written only by upstream).

  • (a) Recommended. The migration backfills a row per existing thread at now(); threads upstream creates later during a rolling deploy get a row on our first write or put_writes. Pro: no recurring scan. Con: a one-off INSERT … SELECT DISTINCT thread_id at setup() on a large database; a thread upstream created and nothing of ours ever touched does not expire.
  • (b) Each sweep also finds headless threads. Con: a scan of checkpoints per call.
  • (c) Never expire headless threads. Con: adopted databases keep their old threads forever.

D5 — rehydrate and head rows.

  • (a) Recommended. Leave them; reword the compatibility promise (§4 above). Pro: no fleet-wide refusals during a rollback; expiry survives. Con: the promise's "removes our side tables' rows except one" changes.
  • (b) Delete them. Con: every running saver of ours refuses its next put on threads in flight; expiry lost; running savers re-create them anyway.

D6 — Do full_copies_only and opc_patching_off stop head-row writes?

  • (a) Recommended. No: fence and expiry work in every mode; dropping our tables waits until no saver of ours runs. Pro: our replicas fence each other from the first deploy, and expiry works during a rollout and after a rollback. Con: the manual drop step needs our savers gone, not only in full-copies mode.
  • (b) Yes. Pro: the promise's drop step stays as worded. Con: no fence and no expiry during the rolling deploy or after rehydrate.

D7 — A thread that expires under a live run.

  • (a) Recommended. Delete it; the run's next put is refused loudly (E2.10). Pro: retention is what the operator set; no silent partial state. Con: a node longer than idle_for loses its turn. idle_for should exceed the longest run.
  • (b) Wait for the run. Con: no signal shows a live run except put_writes, which only puts a row in place if missing, so this needs a second clock column refreshed on every put_writes, a non-HOT-neutral write on a hot path.

D8 — Index on touched_at.

  • (a) Recommended. None; the sweeper scans the head table. Pro: every head update stays HOT (E2.11). Con: a scan per call, one small row per thread.
  • (b) Index it. Con: every root put becomes a non-HOT update. Revisit only if §5's sweep numbers show the scan matters.