Repository navigation
Conversation
|
🦞👀 Pull request received. I will update this pull request when review starts. |
|
Codex review: blocked before merge. Reviewed September 3, 2026, 2:32 AM ET / 06:32 UTC. ClawSweeper reviewWhat this changesThe PR adds transactional SQLite row-snapshot checks and cross-process regressions so SessionManager rewrites and appends preserve rows committed concurrently by another process. Regression provenancePossible regression — probable (reproduction; reviewed change). No predecessor PR is attributed. Merge readiness⛔ Blocked before merge - 4 items remain Keep open: the exact head implements a concrete fix for a current-main SQLite transcript race, but it is 5,450 commits behind current main and its central session files were rewritten after the branch point. Rebase and rerun the cross-process proof before merge. Priority: P2 Review scores
Verification
How this fits togetherSessionManager keeps an in-memory transcript tree while SQLite stores the durable transcript. The changed path loads or appends rows, then can destructively rewrite them during recovery, compaction, or branch operations. flowchart LR
A[Session manager state] --> B[Append or recovery rewrite]
B --> C[SQLite write transaction]
C --> D[Compare row snapshot]
D -->|unchanged| E[Persist rows and snapshot]
D -->|foreign row detected| F[Reload durable transcript]
F --> G[Coordination error]
E --> H[Continued session flow]
Before merge
Agent review detailsSecurityNone. PR surfaceSource +553, Tests +1290, Other 0. Total +1843 across 20 files. View PR surface stats
Review metrics
Stored data modelPersistent data-model change detected: Root-cause clusterRelationship: Members:
Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything. Merge-risk optionsMaintainer options:
Technical reviewBest possible solution: Rebase the transactional snapshot design onto current SessionManager and transcript-writer shapes, preserve the single in-transaction snapshot source for every destructive rewrite, then rerun the child-process conflict scenarios on that resolved head. Do we have a high-confidence way to reproduce the issue? Yes, source-reproducible: the exact head contains deterministic two-process SessionManager and SQLite scenarios that place a foreign append between a manager read or write and its destructive rewrite. Is this the best way to solve the issue? Unclear on current main: the writer-owner snapshot guard is the right repair shape, but the stale branch must be rebased because current main substantially changed both sides of that owner boundary. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning high; reviewed against b637075f4e92. LabelsLabel justifications:
EvidenceWhat I checked:
Likely related people:
Rank-up movesOptional improvements that raise the rating; they are not merge blockers.
Rating scale
Overall follows the weaker of proof and patch quality. Workflow
HistoryReview history (22 earlier review cycles; latest 8 shown)
|
|
@clawsweeper re-review |
|
🦞🧹 I asked ClawSweeper to review this item again. Re-review progress:
|
4acb9fb to
ca40f31
Compare
|
@clawsweeper re-review |
|
🦞🧹 I asked ClawSweeper to review this item again. Re-review progress:
|
c60abd4 to
b5b2f4f
Compare
b5b2f4f to
00839aa
Compare
|
@clawsweeper re-review |
|
🦞🧹 I asked ClawSweeper to review this item again. Re-review progress:
|
…ts (openclaw#124393) replaceTranscriptEventsSync deleted and reinserted every transcript row without checking whether any row had been committed by another process since the caller last read the transcript, silently losing that foreign row while still reporting success. The async sibling withTranscriptWriteLock().replaceEvents already refuses this race via a tracked snapshot revalidated inside its write transaction; the synchronous path (SessionManagerPersistence.removeTrailingEntries -> SessionManagerCore.replacePersistedTranscript) had no equivalent guard. - replaceTranscriptEventsSync accepts an optional expectedSnapshot and revalidates it with the existing assertSqliteTranscriptSnapshotUnchanged helper after BEGIN IMMEDIATE, throwing the (now exported) SqliteTranscriptMutationConflictError on mismatch instead of proceeding. - SessionManagerCore tracks its own last-known-good row snapshot (persistedRowSnapshot), set at load and refreshed after every append or successful rewrite, and passes it into replaceTranscriptEventsSync. On conflict it reloads durable state before rethrowing so callers never see in-memory state that no longer matches what was actually persisted. - session-manager-branching.ts refreshes the tracked snapshot after creating a branched session so it does not compare the new session's rows against a stale, unrelated one. - failover-error.ts classifies the new conflict as a coordination error, not a provider failure, so model fallback does not blame or retry against a different provider for a local storage race the session layer already resynced from. - session-accessor.reply-init-concurrency.test.ts adds a real child-process regression test that commits a foreign append during a paused sync rewrite and asserts the foreign row survives and the conflict surfaces instead of being silently discarded. Fixes openclaw#124393.
ClawSweeper's P1 finding on this PR asked for a deterministic child-process regression proving a foreign append landing in the gap between an append commit and a stale out-of-transaction snapshot refresh is not silently dropped by the next sync transcript rewrite. Add a two-sided sync-append-race scenario to the existing cross-process concurrency worker: - useAtomicSnapshot: false reproduces the old bug shape (a snapshot refreshed separately, after a foreign commit) and shows the foreign row is silently lost. - useAtomicSnapshot: true exercises the fix already landed in session-manager-persistence.ts/session-manager-core.ts (snapshot captured inside the append's own write transaction, via appendTranscriptMessageWithSnapshotSync/applyPersistedRowSnapshot) and shows the rewrite is correctly rejected with the foreign row intact. Split the growing test file into session-accessor.reply-init-concurrency.test.ts (scenarios) and a new session-accessor.reply-init-concurrency.test-support.ts (worker/process machinery), following the repo's existing *.test-support.ts convention, to stay under the oxlint max-lines test-file cap. Co-Authored-By: Claude Fable 5 <[email protected]>
replaceTranscriptEventsSync previously left callers to read the post-rewrite row snapshot with a separate out-of-transaction call. A foreign process committing between this transaction's commit and that later read could silently fold into the tracked snapshot without ever appearing in the caller's in-memory entries, defeating the snapshot-guard the earlier fix in this branch relies on. Add replaceTranscriptEventsWithSnapshotSync, mirroring the existing appendTranscriptMessageWithSnapshotSync pattern: it captures the resulting row set inside the same write transaction immediately after a successful replace, so SessionManagerCore's tracked snapshot is always exactly what committed. Route createBranchedSession and replacePersistedTranscript through it and delete the now-redundant refreshPersistedRowSnapshot out-of-transaction read. Split the raw (non-message) transcript event append family out of session-accessor.sqlite-transcript-write.ts into a new session-accessor.sqlite-transcript-event-write.ts to keep the original file under the repo's 700-line limit; message and replace/rewrite writers stay in the original file. Update the session-accessor.transcript.ts import and the direct session-accessor.entry-mutation.ts consumer accordingly; prune the assertion-safety baseline to record the two safety-commented assertions moved into the new file. Add a cross-process regression test exercising the sync-rewrite race scenario to prove the atomic capture closes the gap.
The prior split-transaction path committed a session's transcript header row in one transaction, then the first record in a later one. A foreign process appending in that gap lands a row that this manager folds into its tracked snapshot but never sees in its in-memory entries -- so a subsequent replacePersistedTranscript silently deletes the foreign row. Fold the still-pending header into the same transaction as the first record via foldPendingTranscriptHeaderInTransaction, which revalidates the manager's tracked (empty) snapshot at BEGIN IMMEDIATE before appending the header. A foreign commit in the gap now fails the manager's first append closed with SqliteTranscriptMutationConflictError and the foreign row survives. Also removes the dead test-only loadTranscriptRowSnapshotSync production export (rewired its sole test-support consumer to loadTranscriptEventsWithRowSnapshotSync). Adds a SessionManager-driven cross-process regression (sync-initial-header-race) that fails on pre-fix code and passes after the fold. Co-Authored-By: Claude Fable 5 <[email protected]>
Raw (non-message) and leaf transcript appends captured a post-append row snapshot and trusted it, so a foreign row landing before the append was silently absorbed into the manager's tracked snapshot (absent from fileEntries) and a later rewrite deleted it -- the same silent foreign-row loss this branch fixes for the rewrite path, reproduced on the append path. Consolidate the three per-append guard-construction sites into one resolveAppendGuard(scope, additive) owner: raw/leaf appends always revalidate the tracked snapshot inside the append's own write transaction (folding a still-deferred header when pending); message appends stay additive and guard only while a header is deferred, since they reconcile an adopted/rebound parent via effectiveParentId rather than trusting a captured snapshot. persistSqliteRecord now reloads durable state on SqliteTranscriptMutationConflictError before rethrowing so a rejected append no longer leaves the manager permanently stale. Two child-process regressions (both fail pre-fix): a raw append rejects when a foreign row lands before it, and a deferred-header conflict reloads so a retry succeeds. The emitted worker source was split into session-accessor.reply-init-concurrency.worker-script.ts to stay under the max-lines cap (split, don't suppress). Co-Authored-By: Claude Fable 5 <[email protected]>
The extracted child-worker source is imported only by the concurrency test-support harness, but its plain `.ts` name made Knip's --production unused-files scan (deadcode:dependencies / deadcode:unused-files CI jobs) flag it as dead production code. Rename it to the repo's test-support convention (config/knip.config.ts ignoredTestSupportFiles) so the production scan excludes it, instead of adding an ignore entry. Co-Authored-By: Claude Fable 5 <[email protected]>
resolveAppendGuard skipped the snapshot-conflict guard entirely for raw/leaf transcript appends whenever no session header was deferred, because the additive flag inverted the guard condition for non-message append kinds. A raw append (e.g. model_change) landing after a foreign row raced the same session would silently succeed with no conflict detection and no rebase reconciliation, since the raw branch also unconditionally returned undefined instead of surfacing effectiveParentId. Fix: unify resolveAppendGuard so the guard applies whenever a header is still deferred, regardless of append kind, and make every append kind (raw, leaf, message) surface effectiveParentId so appendEntry's existing reload check can detect a foreign-row rebase and resync in-memory state instead of trusting a stale parent a later rewrite would silently drop. Also fixes the same bug class in session-manager.user-idempotency.test.ts > "adopts a keyed user persisted after the manager loaded", confirmed via local git-stash bisection to hit the identical guard path (verified against CI job logs for PR openclaw#124899).
…ript-event file Rebasing onto origin/main (which landed PR openclaw#125889's session-lifecycle authority check) conflicted with this branch's prior commit that split appendTranscriptEvent/appendTranscriptEventSyncCore out of session-accessor.sqlite-transcript-write.ts into a new file. Resolving that conflict by accepting the split-commit's deletion silently dropped the options.beforeCommitInTransaction?.() invocation the upstream change added inside the write-transaction callback, so the caller-supplied authority/participation check (session-accessor.entry-mutation.ts's commitGuard) would have silently no-op'd for every raw (non-message) transcript event append. Restore the call at the top of both transaction callbacks, matching upstream's placement, so the check still runs synchronously inside the transaction before the append proceeds.
… rows resolveAppendGuard unconditionally disabled snapshot revalidation once the session header existed, regardless of append kind. Only active-branch appends have an alternative foreign-row-detection mechanism (tail-rebase + effectiveParentId + appendEntry-triggered reload); side-mode, deliberate- branch (post-branch/resetLeaf), and leaf-control appends keep their exact declared parent and never rebase, so they had zero foreign-row detection. Add an isActiveBranchAppend parameter to resolveAppendGuard: active-branch appends keep relying on the rebase-and-reload path, while every other kind now gets a snapshot-only guard (no header to fold) that rejects and reloads on a foreign row committed since the manager's last read/append, instead of silently absorbing it into a snapshot a later rewrite could then delete it from. Adds a cross-process regression covering the side-mode-append race ClawSweeper flagged, and confirms the existing reply-init-concurrency suite runs in ~3s locally, not the 30s CI harness timeout the prior review hit.
clearHeaderPendingAfterFold clears persistenceHeaderPending only when a guard actually folded the deferred header event into its append. Without it, the flag stayed stuck true after the first append, so every later append kept taking the guarded "deferred header" revalidation branch instead of an active-branch append's intended unguarded tail-rebase path -- turning a graceful foreign-row rebase into a hard SqliteTranscriptMutationConflictError rejection. Adds a regression test that reproduces the exact sequence: fold the header on the first append, have a foreign writer append directly against the transcript, then make a second active-branch append that must rebase onto the foreign row instead of being rejected.
…writes The active-branch append guard already rebased a stale manager snapshot when a concurrent row moved the transcript tail, but that rebase reads transcript_event_identities and is blind to any row lacking a non-blank id (e.g. an extensions/msteams FeedbackEvent, appended via a raw appendTranscriptEvent() call with no options). Such a row never gets an identities entry, so no parentId mismatch is ever observed and a later full-table rewrite (removeTrailingEntries -> replacePersistedTranscript, built purely from the manager's in-memory fileEntries/opaqueFileEntries) silently drops it. Thread a foreignRowDetected signal from the snapshot guard (foldPendingTranscriptHeaderInTransaction's non-throwing branch) through both the raw-event and message append cores, into PersistRecordResult, and finally into appendEntry's existing reload-trigger check, so any detected row-count mismatch forces a reload before the stale in-memory view can be trusted by a subsequent rewrite. Adds a cross-process regression test that reproduces the real msteams FeedbackEvent shape racing a manager append, verified to fail pre-fix (the feedback row is silently omitted from the rewritten transcript) and pass post-fix.
00839aa to
46d16d1
Compare
|
Rebased onto current Post-rebase focused tests, green: CI is attached to the new head and running. The other P1 item (production LOC justification for the atomic snapshot-ownership change) is addressed in the PR body: the +726/-173 production delta implements the destructive-write guard and SessionManager snapshot-passing at their owning boundaries ( @clawsweeper re-review |
|
🦞🧹 I asked ClawSweeper to review this item again. Re-review progress:
|
|
Superseded for the reported #124393 foreign-row-loss repair by #138984, merged as b0ae5b6. The merged owner uses transaction-produced before/after generation and raw-sequence receipts. A manager cannot certify an unseen foreign append as part of its loaded view, and synchronous replacement validates the expected version before deletion. The raw sequence includes physical id-less rows as well as identified events. Closing this alternative snapshot implementation as superseded for that data-preservation invariant. Its separate coordination-error classification and reload/retry behavior are not being claimed as shipped by #138984. Thank you for documenting the initial-write, post-append, and id-less-row race variants. |
Closes #124393
What Problem This Solves
Fixes an issue where a synchronous transcript rewrite (e.g. dropping trailing
entries after a compaction retry or a mid-turn precheck failure) could silently
delete a transcript row committed by another process in the meantime, while
still reporting the rewrite as successful. Operators would see a message that
another writer (a channel mirror, a concurrent agent run, a different worker)
had just persisted simply vanish from the session transcript with no error,
no log, and no recorded reason — the exact silent-failure class this repo
treats as highest severity.
Why This Change Was Made
replaceTranscriptEventsSync(src/config/sessions/session-accessor.sqlite-transcript-write.ts)deleted and reinserted every transcript row for a session without checking
whether any row had been committed since the caller last read the transcript.
The async sibling
withTranscriptWriteLock().replaceEventsalready refusesthis exact race: it captures a row snapshot, revalidates it with
assertSqliteTranscriptSnapshotUnchangedinside the write transaction rightbefore the destructive replace, and throws
SqliteTranscriptMutationConflictErroron divergence. The synchronous path used by
SessionManagerPersistence.removeTrailingEntries->
SessionManagerCore.replacePersistedTranscripthad no equivalent guard, so itwas the one call site of
replaceTranscriptEventsSyncthat could still silentlydrop a foreign row.
The fix mirrors the safety property already proven by the async sibling instead
of inventing a new mechanism:
replaceTranscriptEventsSyncgains an optional 3rdexpectedSnapshotparameter. When provided, it is revalidated (not re-read) inside the write
transaction via the existing
assertSqliteTranscriptSnapshotUnchangedhelper,immediately before the destructive replace.
SqliteTranscriptMutationConflictErroris now
exported so callers can catch it by type.SessionManagerCoretracks its own last-known-good row snapshot(
persistedRowSnapshot), set at load time and passed intoreplaceTranscriptEventsSyncon rewrite. On conflict,replacePersistedTranscriptreloads durable state via the existing
reloadPersistedTranscript()self-healbefore rethrowing, so callers never see in-memory state that no longer matches
what was actually persisted.
session-manager-branching.ts'screateBranchedSessionrefreshes the trackedsnapshot after creating a branched session, so the next rewrite compares
against that session's own rows instead of a stale, unrelated one inherited
from the manager's previous target.
failover-error.tsclassifies the new conflict as acoordinationerror, nota provider failure — model fallback must not blame the model or retry against
a different provider for a local storage race the session layer already
resynced from.
ClawSweeper P1 follow-up: atomic snapshot capture on append
ClawSweeper's review of an earlier revision of this branch found a second,
narrower gap in the same invariant:
SessionManagerCore's tracked snapshot wasoriginally refreshed by a separate, out-of-transaction read
(
refreshPersistedRowSnapshot()) immediately after each append committed. Aforeign process could append in the gap between that commit and this
follow-up read; the refreshed snapshot would then silently include the
foreign row even though this manager's own
fileEntriesnever observed it —so the next rewrite would trivially "match" that snapshot and delete the
foreign row anyway, reproducing the exact bug this PR set out to fix, one
append later.
Fixed by capturing the snapshot inside the append's own write transaction
instead of re-reading afterward:
session-accessor.sqlite-transcript-write.tsaddsappendTranscriptEventWithSnapshotSync/appendTranscriptMessageWithSnapshotSync,which return
{ result, snapshot }wheresnapshotis read from the samewrite transaction as the insert, immediately after it, before that
transaction commits and before any other process can interleave.
session-manager-persistence.ts's three append call sites inpersistSqliteRecord()(leaf control entries, non-message indexed entries,and message entries) now use the
*WithSnapshotSyncvariants and adopt thereturned snapshot via a new
SessionManagerCore.applyPersistedRowSnapshot(),instead of the old append-then-separately-refresh two-step.
refreshPersistedRowSnapshot()is retained only for the one remainingcaller where it's actually safe: immediately after a rewrite commits, where
Node's single-threaded execution guarantees no other in-process code can
interleave, and a truly concurrent foreign OS process is the same residual
risk
withTranscriptWriteLockalready accepts for its own tracked snapshot.ClawSweeper P1 follow-up (2): fold the deferred initial header into the first record's transaction
ClawSweeper's next review found the initial-write variant of the same
invariant, one step earlier than the append case above. When a
SessionManageropens an empty transcript it defers the header: it startswith zero entries and an empty tracked snapshot, and the header row was
previously committed by a separate
appendTranscriptEventSynccall beforethe first snapshot-capturing record append. A foreign process appending in that
gap would be folded into the first record's captured snapshot without ever
appearing in this manager's
fileEntries— so a laterreplacePersistedTranscriptwould validate the absorbed row and delete it,reproducing the exact bug one write earlier than the case above.
Fixed by folding the deferred header into the same transaction as the first
record, rather than committing it separately first:
session-accessor.sqlite-transcript-write.tsexports aPendingTranscriptHeadertype ({ event, expectedSnapshot }) and afoldPendingTranscriptHeaderInTransaction(...)helper that first revalidatesthe manager's tracked (empty) snapshot via
assertSqliteTranscriptSnapshotUnchangedand then appends the header — both inside the first record's own write
transaction, before it commits.
appendTranscriptEventWithSnapshotSync/appendTranscriptMessageWithSnapshotSynctake an optional trailing
pendingHeader; the raw-event append path(
session-accessor.sqlite-transcript-event-write.ts) folds it in immediatelybefore the record insert.
session-manager-persistence.tsresolves the pending header once perpersistSqliteRecord(resolvePendingTranscriptHeader) and threads it throughall three append call sites. The old separate header append is gone: there is
now one canonical initial-write path, not a header write plus a record write.
SessionManagerheader-then-first-record sequence (
sync-initial-header-race): a worker opensan empty-transcript manager, a foreign
appendTranscriptMessagelands in thegap (auto-creating the canonical header), and the manager's first record is
asserted to reject closed with the foreign row (and its header) intact — so
the deferred header never commits into a separate racing transaction.
ClawSweeper P2 follow-up: remove the test-only snapshot reader from the public barrel
loadTranscriptRowSnapshotSyncwas exported through both transcript barrels(
session-accessor.transcript.ts,session-accessor.ts) but its only callerwas the new concurrency test support. It is deleted from
session-accessor.sqlite-read.tsand both barrels; the test-support worker nowmodels the legacy post-write refresh with
loadTranscriptEventsWithRowSnapshotSync(scope).rows, so no production APIexists solely to support a test.
ClawSweeper P1 follow-up (3): guard raw (non-message) appends and reload on conflict
ClawSweeper's latest review found that the deferred-header fold above only
guarded the first record of an empty transcript. Once a manager tracks a
non-empty snapshot, every subsequent raw (non-message) append — a
model_change, a leaf control entry, any non-message transcript event — tookthe
appendTranscriptEventWithSnapshotSyncpath with no snapshot guard atall. That path captures the post-append row set and then trusts it. So a
foreign row landing between the manager's last read and its raw append was
silently folded into the very snapshot the manager adopts as last-known-good —
absent from its
fileEntries— and a laterreplacePersistedTranscriptvalidated the contaminated snapshot and deleted the foreign row. This is the
exact bug the PR set out to fix, reproduced on the append path rather than the
rewrite path.
Direct code reading confirmed the gap regardless of the bot's summary text
(the 08:53 review dropped this from its prose, but the code path is real):
raw/leaf appends are capture-and-trust, so they must revalidate on every
append, not only when a header is pending.
Fixed by making the snapshot guard the default for capture-and-trust appends,
while keeping message appends additive:
session-manager-persistence.tsnow resolves oneresolveAppendGuard(scope, additive)per record. Raw and leaf appends passadditive: falseand alwaysrevalidate this manager's tracked snapshot inside the append's own write
transaction (folding a still-deferred header when pending). Message appends
pass
additive: trueand guard only while a header is still deferred —they reconcile an adopted/rebound parent via
effectiveParentIdrather thantrusting a captured snapshot, so a concurrent reset must not reject a late
reply the rewrite preserves anyway (the existing
session-manager.test.ts"keeps stale appenders valid across a reset"invariant).
persistSqliteRecordnow wraps the append in a try/catch: onSqliteTranscriptMutationConflictErrorit calls the existingreloadPersistedTranscript()to resync in-memory state from the authoritativeDB before the failure surfaces, then rethrows. Without this, a rejected
append left the manager's snapshot permanently stale, so every retry hit the
same conflict forever. (
replacePersistedTranscriptalready had thisreload-on-conflict; this extends the same self-heal to the append path.)
the intended reason (verified via
git stash):rejects a manager raw append when a foreign row lands before it: opens apopulated (non-deferred-header) transcript, lands a foreign
appendTranscriptMessagein the gap, drives a rawappendModelChange, andasserts it rejects closed with the foreign row intact — proving raw appends
now revalidate.
reloads the manager after a deferred-header conflict so a retry succeeds:drives the deferred-header fold into a conflict, then calls
appendMessagea second time on the same manager instance and asserts the retry
succeeds (transcript = foreign header + foreign reply + the retried row)
— proving
reloadPersistedTranscript()resynced the manager instead oflooping on the stale snapshot.
Production LOC for this follow-up is net-positive (persistence
session-manager-persistence.tsand the transcript-write helper together+73 / -26, net +47). Per this repo's net-≤0 bug-fix discipline, that growth is justified: it
buys two concrete invariants that cannot be expressed more simply — (a) raw and
leaf appends revalidate the tracked snapshot inside their own write transaction
(the actual missing guard), and (b) a rejected append resyncs the manager from
durable state so a retry can make progress. The three prior per-append
guard-construction sites were collapsed into the single
resolveAppendGuardowner to keep the addition as lean as possible; the remainder is the guard call
plus the reload-on-conflict wrapper, both load-bearing behavior rather than
padding.
ClawSweeper P1 follow-up (4): clear the deferred-header flag after a guarded fold
ClawSweeper's next review found that the raw-append guard follow-up above
introduced its own regression in the same invariant family:
resolveAppendGuardfolds the still-deferred header into the first append's guard, but nothing
ever cleared
persistenceHeaderPendingafterward. So on a freshly openedtranscript, the first append succeeded and folded the header correctly, but
the flag stayed stuck
true— every later append (including anactive-branch append, which is intentionally guard-free once a header exists
so it can take its own tail-rebase-and-reload path) kept taking the guarded
"deferred header" branch instead. A concurrent reset or a second active-branch
append against a fresh session therefore hit a hard
SqliteTranscriptMutationConflictErrorwhere it should have gracefullyrebased onto the foreign row, one append after the previous fix's fold.
Fixed by clearing the flag exactly when a guard actually folded a header:
session-manager-persistence.tsaddsclearHeaderPendingAfterFold(guard),called after each of the three
persistSqliteRecordappend call sites(leaf control, raw/non-message, message) once their guarded append commits.
It flips
persistenceHeaderPendingtofalseonly when the guard it wasgiven actually carried a header (
guard?.event), mirroring the other twoplaces that already clear this same flag on a successful header persist
(
replacePersistedTranscript,branch())."rebases the append after a header fold onto a foreign row instead of rejecting it"(session-manager.test.ts): opens a freshtranscript, makes a first append (folding the deferred header), lands a
foreign append directly against the transcript via
appendTranscriptMessage, then makes a second active-branch append thatstill declares the now-stale first append as its parent. Asserts the second
append succeeds and rebases onto the foreign row instead of throwing —
confirmed to fail on pre-fix code (the stuck flag rejects the second append)
and pass after the fix.
User Impact
A transcript rewrite that would previously silently drop a concurrently
committed message now fails loudly with
SqliteTranscriptMutationConflictErrorand resyncs in-memory state from the authoritative store first, so the caller's
next read reflects reality instead of a stale, incomplete removal. No new
config surface; no behavior change for the (overwhelmingly common) non-racing
case.
Evidence
src/config/sessions/session-accessor.reply-init-concurrency.test.ts:a real child-process worker opens a
SessionManager, reports readiness overIPC, and pauses. While paused, the test's main process commits a foreign
assistant append via
appendTranscriptMessage. The worker then callsremoveTrailingEntries, which is asserted to reject withSqliteTranscriptMutationConflictError, and the transcript is asserted tostill contain all three rows (header, original user message, and the foreign
append) — proving the foreign row survives and the conflict surfaces instead
of being silently discarded.
regressions for a foreign append landing after the local append commits
(
silently drops a foreign append when the rewrite snapshot is a stale post-handshake refresh/rejects the rewrite and preserves a foreign append when the snapshot is captured atomically), driven by auseAtomicSnapshot-parameterized worker scenario:useAtomicSnapshot: falsereproduces the old bug shape (append, then aseparate post-handshake snapshot read) and proves the foreign row is
silently dropped by the next rewrite.
useAtomicSnapshot: trueexercises the shipped fix(
appendTranscriptMessageWithSnapshotSync+applyPersistedRowSnapshot)and proves the rewrite is correctly rejected with the foreign row intact.
6f58bdcb16d5):session-accessor.reply-init-concurrency.test-support.ts(following therepo's existing
*.test-support.tsconvention) to keep the growing testfile under the oxlint
max-linestest-file cap.src/agents/failover-error.test.tscovering both a direct and anested (
cause-wrapped)SqliteTranscriptMutationConflictError, assertingresolveModelFallbackErrorclassifies it as{ kind: "coordination" }.raw-append guard + reload-on-conflict follow-up above, both confirmed to fail
on pre-fix code via
git stash:rejects a manager raw append when a foreign row lands before it— opens apopulated (non-deferred-header) transcript, lands a foreign
appendTranscriptMessagein the gap, drives a rawappendModelChange, andasserts it rejects closed with the foreign row surviving intact.
reloads the manager after a deferred-header conflict so a retry succeeds—drives the deferred-header fold into a conflict, then calls
appendMessageasecond time on the same manager and asserts the retry succeeds
(transcript = foreign header + foreign reply + retried row), proving the
reload-on-conflict resynced durable state.
repo's 700-line test-file cap, so the emitted child-worker source
(
createConcurrencyWorkerScriptplus the sharedSESSION_KEY/AGENT_IDconstants it interpolates) was extracted to a new sibling
session-accessor.reply-init-concurrency.worker-script.ts, perAGENTS.md's"split, don't suppress" policy; the harness that spawns and drives the worker
stays in
*.test-support.tsand re-exports the two constants so the testfile's imports are unchanged.
new regressions):
src/config/sessions,src/agents/sessions(includingsession-manager.test.ts25/25, the additive"keeps stale appenders valid across a reset" invariant),
src/agents/failover-error.test.ts(66/66) all passing.pnpm tsgo:coreandpnpm tsgo:core:test: clean.check:changed --dry-runsweep for the touched files (format,lint, coercion helpers, import cycles, deadcode exports, wrapper shadowing,
database-first legacy stores, native state schema version, plugin boundary
report, and the rest): all clean.
check:max-lines-ratchetandcheck:assertion-safetyreport pre-existingorigin/mainbaseline driftunrelated to this branch (confirmed via
git stashcontrol: identicalfailures with this branch's changes removed).
autoreview --mode local(Codexgpt-5.6-sol, high reasoning): clean,TruffleHog clean, no accepted/actionable findings.
File split forced by the repo's line-limit lint gate
Threading the atomic-snapshot-capture fix through
replaceTranscriptEventsSyncand the raw-event append path pushed
session-accessor.sqlite-transcript-write.tsover the repo's ~700-line split guideline. Per
AGENTS.md's "split, don'tsuppress" policy, the raw (non-message) transcript event append family
(
appendTranscriptEvent,appendTranscriptEventSync,appendTranscriptEventWithSnapshotSync, and their shared internal helpers) wasextracted to a new sibling file,
session-accessor.sqlite-transcript-event-write.ts;the message and replace/rewrite writers stay in the original file. Two type
assertions moved with that code; each now carries a same-line/above
// SAFETY:comment per
scripts/check-assertion-safety-ratchet.mts's exact-placement rule,and
config/assertion-safety-baseline.txtwas pruned (shrink-only,--prune)to record the resulting per-file count reduction — no assertions were added or
left uncommented.
Verified after rebasing onto current
origin/main:pnpm tsgo:coreandpnpm tsgo:core:testclean; a single fullnode scripts/check-changed.mjsgate green (format, lint, coercion helpers, import cycles, dead-export scan,
database-first legacy stores, native state schema version, and the rest); and
the touched-surface tests green —
session-accessor.reply-init-concurrency.test.ts(12/12) andsession-manager.test.ts(25/25), plussession-accessor.test.tsandsession-transcript-search.test.ts. Thesession-accessor.sqlite-transcript-write.tsassertion-safety baseline count was pruned (shrink-only,
7 → 5) to record theassertions that moved into the new
session-accessor.sqlite-transcript-event-write.tssibling; no assertions were added or left uncommented.
Fresh local
autoreview --mode branch --base origin/main(Codexgpt-5.6-sol,high reasoning) after the raw-append guard + reload-on-conflict follow-up:
clean, TruffleHog clean, no accepted/actionable findings — "patch is correct
(0.96)".
New per ClawSweeper's latest review (P1 follow-up 4,
clearHeaderPendingAfterFold):node scripts/run-vitest.mjs src/agents/sessions/session-manager.test.ts -- --reporter=verbose:26/26 passing (up from 25), including the new
"rebases the append after a header fold onto a foreign row instead of rejecting it"regression — confirmed to fail on pre-fix code (rejects withSqliteTranscriptMutationConflictError) and pass after the fix.origin/main(32 commits ahead at rebase time; 10commits rebased, zero conflicts).
autoreview --mode branch --base origin/main(Codexgpt-5.6-sol,high reasoning) on the rebased head: clean, TruffleHog clean, no
accepted/actionable findings — "patch is correct (0.96)".
Relationship to other work on this issue
I claimed this issue in a
comment at 2026-08-16T14:10:07Z
laying out the same root cause and the plan implemented here. PR #124456 (an
earlier attempt) only added snapshot validation before the sync replacement
begins, which does not close the race — a foreign row can still land between
that pre-check and the actual delete/reinsert. This PR instead revalidates the
snapshot inside the write transaction, immediately before the destructive
replace, which is the same guarantee the already-safe async sibling
(
withTranscriptWriteLock().replaceEvents) relies on.New per ClawSweeper's latest review (P1 rebase ask + P1 production-LOC
justification ask, reviewed head
b5b2f4f3e269):origin/main(11 commits, zero conflicts).Head is now
00839aae4cb5(0 commits behind, 11 ahead as of this update);gh pr viewreportsmergeable: MERGEABLE.00839aae4cb5, "reconcile id-less foreign rows beforeactive-branch rewrites"): closes a gap the prior follow-up left open — the
active-branch append guard rebased a stale manager snapshot when a
concurrent row moved the transcript tail, but that rebase check reads
transcript_event_identitiesand is blind to a row with no non-blank id(e.g. an
extensions/msteamsFeedbackEvent, appended via a rawappendTranscriptEvent()call with no options). Such a row gets noidentities entry, so no parentId mismatch is ever observed, and a later
full-table rewrite (built purely from the manager's in-memory
fileEntries/opaqueFileEntries) silently dropped it. Fix: thread aforeignRowDetectedsignal from the snapshot guard through both appendcores into
PersistRecordResult, and intoappendEntry's existingreload-trigger check, so a detected row-count mismatch forces a reload
before the stale in-memory view can be trusted by a subsequent rewrite.
session-accessor.reply-init-concurrency.test.ts--reporter=verboseon the rebased head: 16/16 passing (up from 14),including the 3 new cases this commit added:
"rebases and reloads a manager raw append when a foreign row lands before it""keeps an id-less foreign row alive after a manager active-branch append races it"— reproduces the real msteamsFeedbackEventshaperacing a manager append; confirmed to fail pre-fix (the feedback row is
silently omitted from the rewritten transcript) and pass post-fix.
"rejects a side-mode append and preserves a foreign append when a foreign row lands before it"check:changedgate on the rebased head: green end-to-endfor the 19 touched files (
node scripts/check-changed.mjs -- <files>,NUL-delimited to avoid shell word-splitting) — format, coercion helpers,
dependency pins, deprecated API usage, plugin boundaries, wrapper
shadowing, package patches, dead-export scan,
tsgo:coreandtsgo:core:test, native state schema version, database-first legacy-storeguard, media download helper guard, runtime sidecar loader guard, runtime
import-cycle guard (0 cycles), webhook body guard, and both pairing guards
all pass with no failures.
Production LOC justification (P1 ask: can a smaller shared mutation
boundary preserve the same invariant?)
Per-file production delta on the rebased head (
git diff --numstat origin/main...HEAD, non-test files):session-accessor.sqlite-transcript-event-write.tsappendTranscriptEvent,appendTranscriptEventSyncCore,appendTranscriptEventSync,appendTranscriptEventWithSnapshotSync,resolveTranscriptEventAppendParent,assertNonMessageTranscriptEvent) out ofsession-accessor.sqlite-transcript-write.ts, forced by the repo's ~700-line split guideline once the snapshot-guard fix pushed that file over the cap (documented above under "File split forced by the repo's line-limit lint gate"). It is a move, not new invariant-checking code.session-manager-persistence.tsappendEntry's reload-trigger check and the caller-held snapshot fields threaded intoPersistRecordResult— this is the shared mutation boundary; there is no smaller existing seam that both raw-event and message append paths already funnel through above this layer.session-accessor.sqlite-transcript-write.tswithTranscriptWriteLock().replaceEventssibling already enforces), applied to the sync rewrite/replace path plus the moved-out lines' replacement stubs.session-manager-core.tssession-accessor.sqlite-read.tstranscript_event_identities+ id-less row count), reused by every guarded write path rather than duplicated per-caller.session-accessor.transcript.tssession-manager-branching.tsfailover-error.tsSqliteTranscriptMutationConflictErroras a coordination error (not a provider failure) in the existingresolveModelFallbackError— reuses the existing error-classification seam, no new one.session-manager-entries.tssession-accessor.tssession-manager.tssession-accessor.entry-mutation.tsNet production total: +553, matching ClawSweeper's cited figure. Of that,
+254 (46%) is the mandated file split with no new logic, and +33 (6%) is one
shared read helper reused by every write path rather than duplicated. The
remaining ~+266 is the actual snapshot-capture/validate/reload invariant
applied at the two existing owner boundaries that already existed for this
data (
session-manager-persistence.ts'sappendEntry/PersistRecordResult,and
session-accessor.sqlite-transcript-write.ts's write-transactioncallbacks) — there is no smaller shared boundary above these that both the
raw-event and message append cores already pass through, and inventing a new
one purely to save LOC would add an abstraction layer rather than remove one.
No sibling mutation path was left unguarded: raw append, message append, sync
rewrite, and the deferred-header fold all now revalidate the same snapshot
inside their write transaction, matching the existing async
withTranscriptWriteLock().replaceEventsinvariant this PR extends.