Session state record and row writer design¶
- Kind: decision
- Date: 2026-10-15
- Source: moved from
how-it-works/session-state-record.md; #11798, #11799, #12511, #12543, #15526, #15528, #15535, #11355, #11361, #11557, #11784, #12463, #12465, #12547, #12581, #15456 - Shaped: Session state record
Context¶
Section references (§) point at the design note as it was written; its current-state parts are now the Session state record page.
Design note for #11798 (one explicit state record per session UUID) and the two
“Not verified” questions of #11799 (one per-UUID row writer with deadline-bounded
serialization). Part A, SessionSlots (S1-S9), is implemented; the SessionRowWriter
migration (Part B) is partly implemented, see §6. Function names refer to
src/daemon/sessionManager.ts unless a path says otherwise; the note deliberately
omits line numbers because they rot.
- A session UUID’s lifecycle was the conjunction of membership in ~17 maps and sets plus flags on three records, read by six hand-written predicates each using a different subset.
SessionSlotsholds oneSessionSlotper UUID, a discriminated union with explicit transitions that assert the from-state. No I/O and no durable-row logic.-
11799’s
intents; the writer owns every status-changingSessionRowWritersits beside it, not inside it. Slots emit “desired row”¶device_sessionswrite for the UUID; slots only readrowPending. - Verdict 1: the journal is durable enough for terminal intents only on the daemon path and only when its append succeeded, so the writer must be told whether it did. Verdict 2: freeing the device before the terminal row lands is acceptable only when the intent is durable, and already is the norm for non-terminal releases and two terminal paths.
State before the migration¶
1.1 Per-UUID lifecycle state (original inventory)¶
U = keyed by UUID, S = keyed by Session object identity (WeakMap/WeakSet).
Groups marked “now SessionSlots” have moved.
| Concern | Fields | Key |
|---|---|---|
| Published | sessions |
U |
| Device index | deviceSessionMap (stays beside the store) |
U / device |
| Assignment | pendingSessionAssignments, sharedSessionAssignments (now SessionSlots) |
U |
| Creation | pendingSessionCreations, pendingPersistedRecoveries, claimedRecoverableRows (now SessionSlots) |
U / S |
| Rebind | pendingSessionRebinds, deferredRebindCleanups (now SessionSlots) |
U |
| Release before publish | pendingSessionReleases (now SessionSlots) |
U |
| Release in flight | releasePromises, activeReleasePromises, releasingSessions (now SessionSlots) |
U / set / S |
| Terminal fence | terminalReleaseSnapshots, terminalReleaseReasonStates, terminalReleaseReservations (now SessionSlots) |
U |
| Finalized identity | finalizedSessionReleases (stays an S-keyed side table), latestFinalizedSessionIdentities, finalizedSessionIdentityRegistry (now SessionSlots) |
S / U |
| Forced release | forcedNonTerminalReleases (now SessionSlots) |
S |
| Journal recovery | recoveredTerminalReleaseIntents, adoptedDeadDaemonJournals, adoptedTerminalReleaseOwners (now SessionSlots) |
U / daemon |
| Row facet (1.3) | 17 fields | U / S |
Flags on records carry more lifecycle: forced, commitFenced, commitDeclined,
stage (SessionReleaseOperation) and terminalPersisted, lateTerminalRelease,
finalizedSnapshot (ReleaseReasonState).
Out of scope (UUID-keyed but not lifecycle): derived-label maps
(derivedLabelSessionsByBase, endedLabelBases, planLabelMints,
runningPlanLabelSessions), restore queues and mutation chains (clock*,
rotation*, screenReader*, networkCondition*), per-device cleanup bookkeeping.
Only endedLabelBases is touched by a transition.
1.2 Hand-written predicates (replaced by tag reads in S7)¶
| Predicate | Read |
|---|---|
isCurrentSession |
sessions, terminalReleaseSnapshots |
isAdmittedForAutomation |
the above + releasingSessions |
isLatestSessionIdentity |
sessions, pendingSessionCreations, pendingSessionAssignments, releasePromises, latestFinalizedSessionIdentities |
isSessionBeingRecreated |
sessions, pendingSessionCreations, pendingSessionAssignments |
getAllKnownSessionIds |
six maps |
getHeldDeviceSessions |
deviceSessionMap, sessions, releasePromises |
“Releasing” was tracked three ways (by object, id, operation). waitOutRecreationOf
is a workaround for the scatter (yields because another continuation clears the
maps). The getSession call is not a query: getSessionInternal starts a release when it
finds an expired session (releaseExpiredSessionLazily). It had 31 in-class and ~84
external callers, versus the side-effect-free peekSession.
1.3 Durable row writes (the row facet)¶
| Write | Site | Repository call |
|---|---|---|
| Create / recovery claim | persistSession via persistAndPublishSession |
upsertActiveSession |
| Rebind | persistAndPublishRebind -> persistSession |
upsertActiveSession |
| Superseded-row rewrite | reassertSupersededLiveRow, replaceSupersededReleaseRow |
upsertActiveSession |
| Activity | persistSessionActivity |
recordActivity |
| Activity repair | rePersistSessionActivity |
upsertActiveSession |
| Release (terminal and not) | persistSessionRelease |
markReleased |
| Release retry | retryTerminalReleaseWrite |
markReleased |
| Startup / peer-dead intents | applyRecoveredTerminalReleaseIntents, fenceDeadDaemonIntents |
markReleased |
| Expired persisted | terminalizeExpiredPersistedSession, tryReleaseUnrecoveredReissuableRow |
markReleased |
| Liveness owner | several sites | recordLivenessOwnership, replaceLivenessOwnership |
Guards live in SQL, not memory (src/db/deviceSessionRepository.ts):
expectedRowGeneration, unlessTerminal, unlessTerminalOrOwnedByLivePeer, and
(since #12463) activity_seq: an activity write overwrites activity columns only if
its session-clock sequence is not older, and recordActivity matches only
status = active. Activity writes are therefore commutative and cannot revive a
terminal row; they need no writer serialization, only a way to report “row not
active”. Issue #12465 made every DeviceSessionPersistence method required, so a writer
builds on one complete interface and one complete fake
(test/fakes/FakeDeviceSessionPersistence.ts).
The #11799 “patch-on-patch” chain: supersededReleaseReasons,
pendingSupersededRowReasserts, supersededRowsUnderPendingRelease,
supersededReasonsBeingRewritten, owedSupersededRowReasserts,
releaseReasonPredecessors, refusedReleaseWrites, their backoff, and two
same-shaped retry record types (TerminalReleaseRetry, OwedSupersededRowReassert).
1.4 Release ordering today (releaseSessionInternal)¶
- Teardown, then the first supersede fence.
- Terminal only:
persistTerminalReleaseWithinDeadlineraises the in-memory fence (terminalReleaseSnapshots.set), thenpersistSessionReleaserecords the journal intent before issuingmarkReleased. The bound isSESSION_RELEASE_PERSIST_TIMEOUT_MS=SESSION_RELEASE_DRAIN_TIMEOUT_MS(5 s) + 1 s = 6 s (not the 10 sSESSION_RELEASE_TEARDOWN_CAP_MS, a different bound). At the deadline the device is freed anyway. - Final supersede fence, synchronous with the commit; a decline here forces
abandonReleaseSupersededAfterPersistand the rewrite chain. commitReleaseRemovalremoves the session and frees the device.- Non-terminal only: the row is written after the commit
(
completeReleasePersistence), retried viapendingNonTerminalReleaseSnapshots(#11557).
A forced stuck release (forceStuckRelease) also frees the device first and persists
later (persistForcedReleaseFence).
The two #11799 questions¶
Q1. Is the journal durable enough for “ended but row not yet written”?¶
Verdict: not everywhere. Yes for terminal intents on the daemon path, provided the append succeeded; the writer must be told whether it did.
Holds (src/daemon/terminalReleaseJournal.ts):
FileTerminalReleaseJournal: one append-only JSONL file per daemon in<dataDir>/terminal-release-intents/.appendDurable= write +fsyncSync, run before the DB write is issued. Compaction: write sibling, fsync, rename, fsync dir.- Crash after intent, before row: next start applies it
(
applyRecoveredTerminalReleaseIntents, first inrehydratePersistedSessions). A dead peer’s file is adopted at startup or when found dead later (readDeadDaemon,fenceDeadDaemonIntents, #11355). - Shutdown:
drainReleasePromisesawaits releases, parked late writes and one retry round before the DB closes; a timed-out drain keeps the DB open and the intent on disk. - Tests:
sessionManager.releasePersistDeadline.test.ts(crash after the intent restarts the UUID terminal; torn tail ignored).
Gaps:
record()swallows an append failure (warn) andpersistSessionReleasewrites regardless: no crash safety and nothing says so; under free-before-row this is a revival window.- Default is
NoopTerminalReleaseJournal; the only attach is inDaemon.startOnand the onlynew SessionManager(is indaemon.ts. Anything else (and every unit test not opting in) has no durability. - The first append to a new file does not fsync the parent directory (only compaction does).
- A corrupt mid-file line drops that intent at debug level; only a torn final line is handled deliberately.
- If compaction and the lift-marker append both fail, a stale intent can terminalize a live session on restart.
- Terminal intents only. A non-terminal “ended, row not written” (device restart)
lives in
pendingNonTerminalReleaseSnapshots; a crash leaves the row active and rehydration recovers it, which is intended.
A missing intent after a crash leaves a stale active row with no reason;
markStaleActiveSessionsExpired (daemon.ts) expires it to daemon-restart, making
it recoverable, and rehydration reserves its device by stable id. The failure is a
revived UUID and a phantom hold on a device possibly owned by another session.
Journal replay runs before the listing; that ordering was read, not run, and is
checked in W1.
Required: record() returns "durable" | "volatile"; Noop returns "volatile";
fsync the directory on first create; warn on a corrupt mid-file line (W1,
journal-only).
Q2. Is freeing the device before the terminal row lands acceptable?¶
Verdict: acceptable when the intent is durable. It already happens on three paths; the proposal makes it the single path for terminal releases and adds the missing condition.
Already happens:
- the terminal deadline path: the device is freed after 6 s with the row unwritten,
and the in-memory fence keeps the UUID from routing. The test
sessionManager.releasePersistDeadline.test.tsasserts held 1 ms before the deadline, freed at it, snapshot kept. forceStuckRelease.- every non-terminal release.
Why safe:
- Device allocation does not read
device_sessions:getSessionForDeviceandgetHeldDeviceSessionsread onlydeviceSessionMap;devicePool.tscalls the repository only formarkAutolockSession. A stale row cannot double-assign. - The in-memory fence is raised before the write and never depends on it.
- Peers:
markStaleActiveSessionsExpiredspares a live peer’s active rows andclaimRecoverableSessionrequires a non-active row with a re-issuable reason.
Risks and bounds:
- Crash between free and row landing: covered only if the intent is durable. Rule:
free before the row only when
journal.recordreturneddurable; otherwise write first, bounded by the existing deadline, as today. On Noop and after a failed append the order is unchanged (direct mode and unit tests see no change). - Ghost
activerow between free and landing. Readers: startup rehydration, UUID-only recovery (readPersistedSession), admission (createUnseenSessiontreats only a terminal row as blocking), video-recording reclaim (operational phantom hold only), appearance sweep (cosmetic). In a live process the in-memory fence decides. - Existing gap to close: a terminal write carries no generation.
releaseWritePreconditionsetsexpectedRowGenerationonly for non-terminal anddaemon-shutdownreleases, andlivePeerDaemonSessionIdsis hard-coded empty. A parked terminal write can land on a row the same daemon re-upserted for the same UUID after the fence was lifted; only the in-memory fence prevents it. No test reproduces it. W2 owner decision: a write frees its slot at its deadline; the SQL generation guard, not in-process serialization, closes the late-overwrite gap. Before the deadline a later desire waits for the issued write; after it, a later write may issue while the parked statement stays tracked for callbacks and drain. Whether productionmarkReleasedcan interleave at all (bun:sqlite is synchronous) is confirmed in W2; if not, the gap exists only on retry/park paths. - Wedged writer: one coalesced intent per UUID; physically unsettled parked writes tracked separately; a deadline-expired write no longer occupies the issuing slot (at most one unexpired write at a time).
- Part two of #11799 removes the superseded-after-persist path: after a
free-before-row commit a later supersede is refused (release already won) rather
than rewritten. Sound only because final fence, journal append and commit are
synchronous (no
awaitbetween).
A fault-injection test (W2) makes this checkable: fail the journal append, the row write and the process at each await and assert the post-restart row equals the in-memory outcome.
Options¶
Not recorded. The row writer was placed beside SessionSlots, not inside it.
Decision¶
- One
SessionSlotper UUID inSessionSlots, with explicit, asserted transitions;SessionRowWriterbeside it owning status-changing row writes, with slots reading onlyrowPending. - Free the device before the terminal row only when
journal.recordreturneddurable; otherwise write first, bounded by the existing deadline. - W2 owner decision: a write frees its slot at its deadline; the SQL generation guard, not in-process serialization, closes the late-overwrite gap.
- Open decision 2 (Windows):
volatileis the right answer where the directory fsync is skipped; no weaker guarantee is documented. - W5a (owner, 2026-10-26, #11799): no supersede fence is evaluated once a row statement is issued, for any intent, the volatile one included.
Where existing state moved:
| Existing | New home |
|---|---|
sessions |
state.session of live / rebinding / releasing |
pendingSessionAssignments, sharedSessionAssignments |
assigning |
pendingSessionCreations, pendingPersistedRecoveries, claimedRecoverableRows |
creating.creation, creating.recovery |
pendingSessionReleases |
releaseRequested on assigning / creating |
pendingSessionRebinds, deferredRebindCleanups |
rebinding.rebind or releasing.rebind (cleanups a per-slot list) |
releasePromises, releasingSessions, forced, commitFenced, stage |
releasing.op (releasingSessions is tag === "releasing") |
activeReleasePromises |
releasing.op plus retiring (derived set across slots) |
terminalReleaseSnapshots, terminalReleaseReasonStates |
fenced.snapshot / fenced.reason; releasing.fence |
terminalReleaseReservations |
fenced.reservation |
latestFinalizedSessionIdentities, registry |
ended.identity / fenced.identity |
finalizedSessionReleases (S-keyed) |
stays an identity-keyed side table |
recoveredTerminalReleaseIntents, adoptedTerminalReleaseOwners, adoptedDeadDaemonJournals |
fenced with source: "journal" / "peer-journal" (adopting owner stays on the snapshot); the dead-daemon set stays daemon-level |
forcedNonTerminalReleases |
ended.source = "forced" plus snapshot; the stuck op lives on in retiring |
Row facet (pendingTerminalReleaseRetries, lateReleaseWrites, releaseDrainStarted, pendingNonTerminalReleaseSnapshots, the superseded-row fields, refusedReleaseWrites, releaseRowGenerations, persistedRowGenerations, issuedActivityWrites, retiredCreationRows, activityRowRePersists, retry backoffs) |
SessionRowWriter (#11799); #11798 does not move them |
Consequences¶
Staged migration¶
Principles: introduce in parallel, assert agreement, switch reads, delete maps one
group per PR. Every PR is behaviour-preserving, adds no public API, keeps unit tests
under 100 ms (FakeTimer, FakeDeviceSessionPersistence,
FakeTerminalReleaseJournalFileSystem). #11784 (per-file line-count ratchet) lands
first so extracted modules cannot grow back. New code goes in SessionSlots /
SessionRowWriter so sessionManager.ts shrinks monotonically.
Part A: #11798 (all landed)¶
| # | Step | Status / notes |
|---|---|---|
| S1 | Types, transition table, pure deriveSlotTag(legacyView) |
landed |
| S2 | Shadow probe lifecycleTagOf(uuid) plus seeded random-interleaving agreement test under FakeTimer |
landed (§4 findings) |
| S3 | Assignment and creation group in SessionSlots |
landed |
| S4 | Rebind group | landed |
| S5 | Release group (releasing.op, retiring); highest risk |
landed |
| S6 | Fence and identity group; finalizedSessionReleases stays a side table; GC test through a fake FinalizationRegistry seam |
landed |
| S7 | Predicates become tag reads; settled lands but all three waitOut*Of stay; illegal transitions throw in test, warn+count in production |
landed |
| S8 | findSession is the pure lookup; expireIfDue keeps lazy expiry at retained admission/routing sites (#12581); retained readers are listed in test/lint/findSessionNoRelease.test.ts; external getSession callers migrate by directory (RETAINED_SERVER_EXPIRY_READERS ratchet) |
landed, tracked separately |
| S9 | Slot code reads no row-facet field; rowPending(uuid) is the only row signal, wired to SessionRowWriter.pending in W2 |
landed, closes #11798 |
Part B: #11799¶
Implemented: SessionRowWriter owns the drain-write set (formerly lateReleaseWrites),
terminal retry scheduling and the non-terminal snapshot map (adapter surface:
noteRelease, noteLive, canIssueRelease, scheduleRetry; in production
pending(uuid) means only “retry owed”). W3 moved create/rebind upserts, activity and
ownership statements behind upsertLive, recordLiveActivity,
replaceLiveOwnership (pass-through, same await sequence). It also moved the
superseded-row state into SessionRowWriter.superseded
(src/daemon/supersededRowReasserts.ts). That state covers remembered superseded reasons, release-reason
predecessors, refused release writes, pending-rewrite counts, rows under pending
non-terminal releases, owed rewrites with backoff/timers/drain attempt, keyed off the
writer’s drain flag). Row policy stays with the manager as per-entry callbacks
(retry, retryDuringDrain) so every read, statement and await keeps its order; the
rewrite chain is deleted in W5.
The per-UUID desire/settled/drain engine in sessionRowWriter.ts is test-exercised;
production first-attempt writes do not use it yet and stay manager-side until W3/W4
finish. The past-deadline-frees-the-slot decision is implemented in that engine.
Production still has no per-UUID serialization.
Behavior-preserving adapter: first-attempt persistence, deadline/fallback and late
callbacks stay on the manager; the writer owns retry scheduling and drain tracking. At
synchronous issue a still-current terminal snapshot remains writable; otherwise first
and retried statements consult the writer’s snapshot desire sequence. Publish and
rebind publish call noteLive synchronously; the current terminal fence takes
precedence over a rebind live sequence. A sequence refusal after a lift is a named
subtype of DeviceSessionRowNotReleasableError and follows
handleReleaseWriteFailure -> confirmReleaseWrite, resolving the journal without
SQL-miss reclassification. Forced snapshots capture the session’s known SQL generation
and weak incarnation identity for the same-session rebind classifier. Real statement
refusals keep their read/classify/retry sequence; no new manager awaits or promise
hops.
| Path | Terminal guard form |
|---|---|
persistSessionRelease (incl. forced fence, creation rollback) |
Current terminal fence, else snapshot desire/live sequence at the synchronous issue boundary; captured expectedRowGeneration plus unlessTerminalOrOwnedByLivePeer at SQL when known |
| Writer-scheduled manager retry | Same current-fence/desire/live check, cancellation identity, fresh retriedReleaseWritePrecondition read; SQL generation whenever known |
| Refused-row fallback / physically parked statement | Same sequence check before a further statement issues; issued SQL keeps its original generation guard; same-incarnation SQL classification and W3/W5 compensation remain |
| No captured generation and no newer in-process live generation | Existing unlessTerminalOrOwnedByLivePeer only; no invented generation |
| Standalone writer desires / retries | Monotonic desire/live sequence checked after async preconditions and immediately before every issue; supplied SQL generation forwarded unchanged |
| Startup replay / peer adoption | Existing statement ownership/terminal guards; replay precedes live publication; resolution routes through liftTerminalFence |
liftTerminalFence performs deletion, volatile-intent clearing, journal resolution and
writer cancellation in one synchronous turn. Successful writes, refusals,
rejected-creation fence adoption and startup replay keep the terminal admission fence
(resolving an intent must not make an ended UUID reusable). They cancel only the matching
snapshot without eagerly removing the manager retry entry. Actual lifts remove the
snapshot and cancel terminal desires and scheduled retries together. Plan-label minting
keeps its shadow probe and reason-state deletion between snapshot deletion and journal
resolution. Startup keeps recovered-intent/probe/adopted-owner deletion before
resolution. Retry-drop keeps cancel-retry and superseded bookkeeping before resolution.
A durable record clearing the volatile signal is not a fence lift.
Two behavior changes:
- a non-terminal commit now also deletes the volatile intent, resolves the journal and cancels a terminal retry (skipped when no terminal snapshot is fenced);
- forced terminal snapshots now capture
expectedRowGenerationandreleaseRowSessions.
At most one unexpired standalone desire per UUID may issue; parked statements stay
tracked for callbacks and drain. Production bun:sqlite is synchronous, so the
overwrite regression parks injected statements and retry/precondition work around the
actual manager lift/publication. Fault tests use in-memory persistence and journal
files only. The synchronous journal fake models hang/delay as a whole-process pause
(an injected supervisor advances FakeTimer without firing JS callbacks; an in-process
rebind cannot run inside it). Rejected journal syscalls yield the W1 volatile result.
Persistence hang/delay suspends across FakeTimer turns. Crash cases discard the manager
and replay the committed disk prefix via rehydratePersistedSessions.
| # | Step | Size | Test plan |
|---|---|---|---|
| W1 | Journal hardening, independent: record() returns durable/volatile; directory fsync on first create (skipped on win32 like compaction); warn on mid-file corruption; Noop returns volatile; verify and pin restart ordering of markStaleActiveSessionsExpired vs journal replay |
S | Journal unit tests with FakeTerminalReleaseJournalFileSystem: failed append gives volatile, crash simulation, torn and mid-file corruption; restart-ordering test including the deadlineAt break case where unapplied intents meet the stale-active sweep |
| W2 | SessionRowWriter for release rows only; replaces pendingTerminalReleaseRetries, lateReleaseWrites, pendingNonTerminalReleaseSnapshots; same ordering (terminal row before commit); adds the terminal generation guard (Q2 risk 3), named in the PR title |
L | releaseRowRetry, releasePersistDeadline, rowInvariant unchanged; fault injection failing each write kind at each await; regression test for same-UUID overwrite |
| W3 | Create / rebind / activity-repair writes move to the writer; superseded-row fields and OwedSupersededRowReassert deleted |
L | supersededRowReassertRetry, rowWritesRemainingCases; fault injection extended |
| W4 | Behaviour change, isolated: terminal write after the final fence when journal.record is durable (§5); the only PR that changes ordering |
M | Crash after free; record failure falls back to write-first; supersede after commit is refused; Linux and macOS CI |
| W5 | Delete abandonReleaseSupersededAfterPersist, reassertSupersededLiveRow and the dead rewrite chain |
S | Dead-code check; full row-invariant suites |
W4 as landed¶
A terminal release whose journal.record returned durable now fences and records its intent
synchronously (fenceTerminalRelease), runs the final supersede fence, commits the removal, and only
then writes the row (persistCommittedTerminalRelease). The manager frees the device (notifySessionRelease)
without waiting for the row; the release still awaits the row afterwards, bounded by the persist
deadline, so drainReleasePromises and the late-write tracking are unchanged. A final fence that
declines lifts the fence and resolves the intent in one turn and has nothing to undo. The manager
therefore calls abandonReleaseSupersededAfterPersist with rowWritten = false, and it rewrites nothing.
A row write that fails after the commit cannot keep the session: the device is already freed, the
retry is scheduled (scheduleTerminalReleaseRetry), and the release rejects with the write error.
Before W4 the session stayed published and the device held until a later release retried.
A volatile intent keeps the write-first order exactly as before, including the final fence after
the row landed and the rewrite chain behind it. Decision (open decision 2, Windows): volatile is the
right answer where the journal skips the directory fsync; the design documents no weaker guarantee.
W5 removes the chain by dropping the post-persist re-check for volatile releases (the writer refuses
a supersede after the row landed: the release already won). It also deletes supersededRows.ts’
release-driven half. The rebind and activity overlap repair stays, re-modelled as the writer
replacing an unwritten live desire.
W5a (decided by the owner, 2026-10-26, #11799): once the writer issues a row statement, no
supersede fence runs, for any intent: the volatile one included. This is a behaviour change, not a
dead-code removal. A volatile release whose row statement went out has won. A newer identity
confirmation that arrives during that write is too late; before, it ended with the live session
rewritten over the terminal row. A durable release still declines at the one fence before its row
exists. A faulted journal write reports volatile, so this reaches durable-journal daemons too
whenever that write fails, not only Windows. W5a deletes abandonReleaseSupersededAfterPersist.
The release-driven rewrite chain (reassertSupersededLiveRow and the owed-retry machinery) is now
unreachable from a release. It stays until the next slice, whose tests drive it directly, and the
rebind/activity overlap repair keeps using it.
W5b deletes the release-driven half of that chain:
restoreNonTerminalRowOverSupersededReleaseand itsLaterformreplaceSupersededReleaseRow- the ledger’s row-under-pending-release record
- the three call sites that reasserted a live row when a late terminal write landed
(
trackLateReleaseWrite), when a non-terminal commit settled, or after a fence’s row was rewritten
What remains is the rebind/activity overlap repair (oweSupersededRowReassert(session,
[]), its retries, drain and activity hook).
The superseded-reason plumbing that the overlap repair still carries (remember,
expectReassert’s reasons, the statement guard’s supersededReasons) was always empty from
production callers, and W5c removes it. The ledger no longer remembers reasons (remember,
isOwedFor, isBeingRewritten, the owed entry’s reasons). After W5c,
reassertSupersededLiveRow takes only the session, and the live-row rewrite’s statement guard
refuses every terminal row. What stays is the release write’s supersededReasons, which carries
only a terminal upgrade’s own earlier reasons (predecessors).
W5c also closes the gap the W5b review found. A finishing rewrite restores a terminal fence’s row only for a volatile release (whose row was written first) or one that has committed. It never does so for a durable release that has not committed and may still decline.
Risks¶
- Concurrency core: orderings that exist only as comments (a non-terminal release must not yield after freezing its reason; the fence “with no await in between”) become methods that must stay synchronous. Each has a test asserting no microtask boundary (the S2 harness counts awaits).
- Dual representation during S3-S6 could disagree; mitigated by the S2 agreement test and deleting each group’s legacy maps in the PR that made its slice authoritative.
- Weak references:
endedrecords must not extend aSession’s lifetime (GC seam test in S6). settledpromises can hide unhandled rejections; they resolve, never reject.- W4 changes durability semantics. It is gated on
durable(Noop and failed append keep today’s order), and W1 lands first. A bug in thedurablesignal is the worst case (a revived UUID), so the fault-injection test fails the signal itself. - Multi-daemon rows: no SQL guard is removed in any step; W2 adds the generation guard against late parked statements. A wedged write delays that UUID’s next issued row only until its persistence deadline.
- Unchanged and out of scope: derived-label maps, restore queues, per-device cleanup
bookkeeping, the
Sessionshape and the MCP surface.
Open decisions¶
- Is one
fencedstate enough for theforced,journalandpeer-journalsources, or must a forced terminal release stay distinguishable (#11361)?sourcestays a field so it can split later. - W4 on Windows: the journal’s directory fsync is skipped there. Decide whether
volatileis the right answer on Windows or document the weaker guarantee.