Repository navigation
fix(sessions): detect concurrent transcript conflicts in sync rewrite (#124393) - #124749
wakqasahmed wants to merge 5 commits into
Conversation
|
🦞👀 Pull request received. I will update this pull request when review starts. |
|
Codex review: blocked before merge. Reviewed September 3, 2026, 3:06 AM ET / 07:06 UTC. ClawSweeper reviewWhat this changesThe PR tracks SQLite transcript-row snapshots across synchronous session loads, appends, and rewrites so conflicting concurrent writes are rejected and reloaded instead of silently overwritten. Merge readiness⛔ Blocked before merge - 6 items remain Keep this PR open. The snapshot design and supplied cross-process proof address the reported silent transcript-loss race, but the current head still contains an introduced unused binding that violates the repository lint rule and is dirty against current main. Priority: P2 Review scores
Verification
How this fits togetherSessionManager owns in-memory agent transcript state backed by SQLite. Its synchronous persistence calls load, append, and rewrite transcript rows through the session-accessor layer, which must preserve rows written by another process. flowchart LR
A[Session manager] --> B[Load or append transcript]
B --> C[SQLite transaction]
C --> D[Durable row snapshot]
D --> E[Rewrite request]
E --> F{Snapshot unchanged?}
F -->|yes| G[Replace transcript rows]
F -->|no| H[Reload durable state and report conflict]
Before merge
Findings
Agent review detailsSecurityNone. PR surfaceSource +238, Tests +429. Total +667 across 11 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 onto current main, port only the required atomic snapshot invariant into its canonical session implementation, remove the unused test binding, and rerun the focused cross-process conflict proof on the rebased head. Do we have a high-confidence way to reproduce the issue? No current-main reproduction was independently possible because the partial clone could not fetch current-main source blobs, but the reviewed head and supplied terminal trace provide a high-confidence cross-process source reproduction path. Is this the best way to solve the issue? Unclear for current main: the reviewed-head design aligns synchronous snapshot handling with the async sibling, but it must first be ported and rechecked against main's substantially rewritten session code. Full review comments:
Overall correctness: patch is incorrect AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning high; reviewed against 8ffa76c28032. 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 (9 earlier review cycles; latest 8 shown)
|
|
@clawsweeper re-review |
|
🦞🧹 I asked ClawSweeper to review this item again. Re-review progress:
|
|
Fixed in 6fa1d7f. Confirmed the gap: Threaded Added the foreign-before-own-append regression using a non-message leaf append (verified it fails without the fix, passes with it). Also ran the three acceptance-criteria test files from the review — all green: |
|
@clawsweeper re-review |
|
🦞🧹 I asked ClawSweeper to review this item again. Re-review progress:
|
…openclaw#124393) replaceTranscriptEventsSync rewrote a transcript's rows without revalidating them against a pre-rewrite snapshot, so a transcript row committed by another process between SessionManager's last append and the rewrite was silently deleted while the call still reported success. The async sibling withTranscriptWriteLock().replaceEvents already refuses this with SqliteTranscriptMutationConflictError. - replaceTranscriptEventsSync now accepts an optional expectedSnapshot and revalidates it inside the write transaction before deleting rows, throwing SqliteTranscriptMutationConflictError on mismatch. - Add readTranscriptSnapshotSync so a caller can capture its own last-known-durable transcript state. - SessionManagerCore tracks that snapshot across loads and every sync append, and passes it into replaceTranscriptEventsSync on rewrite. On conflict it reloads durable state (self-heals in-memory entries onto the foreign row) and rethrows instead of silently discarding it. - The other replaceTranscriptEventsSync call site (session-manager-branching.ts) targets a freshly created, empty transcript and is unaffected since it does not pass expectedSnapshot. Adds a cross-process concurrency test mirroring the existing async sibling's test, plus a same-process SessionManager test covering the conflict-then-self-heal path.
…4393) Add regression coverage for the atomic snapshot fix: SessionManager must record its last-known-good transcript snapshot from inside an append's own write transaction (onCommittedSnapshot), not by rereading storage afterward. A post-commit reread left a window where a foreign process's append could be silently absorbed into the "expected" snapshot and later get dropped by a rewrite without detection. - Assert no reread call happens after a synchronous append - Assert a rewrite correctly rejects when a foreign process commits right after our own last append, preserving the foreign row
…penclaw#124393) Move SqliteTranscriptSnapshotRow's definition into session-accessor.sqlite-contract.ts (the base contract leaf) instead of importing it into that file from session-accessor.sqlite-read.ts, which closed a cycle back through session-accessor.sqlite-scope.ts. session-accessor.sqlite-read.ts now re-exports the type so existing importers are unaffected.
…nclaw#124393) setSessionTarget() loaded transcript entries and refreshed the row snapshot via two separate SQLite reads, leaving a gap in which a foreign process's commit landed after the entries read but before the snapshot read: absent from fileEntries but present in the 'expected' snapshot, so a later rewrite would validate against it and silently delete the foreign row. Add loadTranscriptEventsWithSnapshotSync(), mirroring the existing deferred-transaction read pattern (inspectTranscriptEventsSync), to load events and the raw row snapshot together from one SQLite read transaction. Use it in SessionManagerCore#setSessionTarget and SessionManager.open(), installing the atomically-read snapshot directly instead of a separate refreshTranscriptSnapshot() call. Adds a regression asserting the old two-call path (loadTranscriptEventsSync then readTranscriptSnapshotSync) never runs during open().
…s committed snapshot clawsweeper[bot] flagged that a foreign row committed after this manager's last known snapshot but before its next synchronous non-message/leaf append (or message append) was absorbed into the callback snapshot without ever entering fileEntries. A later rewrite validated against that snapshot and could silently overwrite the foreign row. Thread expectedSnapshot through appendTranscriptEventSync and appendTranscriptMessageSync: revalidate the caller's prior snapshot inside the append transaction, and skip recording a new snapshot when it no longer matches so the caller's stale snapshot is left in place. A later replaceTranscriptEventsSync then detects the drift via its existing expectedSnapshot check and reloads, instead of silently dropping the foreign row. Adds a foreign-before-own-append regression using a non-message leaf append, which has no other reconciliation path (unlike a message append's effectiveParentId mismatch reload).
6fa1d7f to
c07af72
Compare
|
Rebased onto current Re-ran the full affected suite post-rebase on Node 24.15.0:
PR is now |
|
Superseded for the #124393 data-preservation repair by #138984, merged as b0ae5b6. Current main carries transaction-produced transcript versions through manager reads and writes, and validates the expected generation/raw sequence inside synchronous replacement before deletion. This supplies the caller-held freshness guarantee without retaining whole-transcript row snapshots or performing a post-commit snapshot reread. Closing this alternative implementation as superseded. Thank you for the cross-process reproduction and regression coverage. This closure does not assert that this PR's separate reload-on-conflict behavior was copied into main. |
What Problem This Solves
replaceTranscriptEventsSyncrewrote a transcript's rows without revalidating them against a pre-rewrite snapshot. A transcript row committed by another process betweenSessionManager's last append and the rewrite was silently deleted, and the call still returnedtrue(success). The async siblingwithTranscriptWriteLock().replaceEventsalready refuses the identical write withSqliteTranscriptMutationConflictError.Fixes #124393
Why This Differs From #124456
#124456 added a 4-line check that read a snapshot and immediately re-validated it inside the same write transaction:
That is a no-op: nothing can commit between two statements inside one transaction, so the assertion can never fail. It also doesn't cover the real race, which is the gap between
SessionManager's last own append (possibly much earlier) and the call toreplaceTranscriptEventsSync— not the few microseconds inside the function itself. A snapshot read at the top ofreplaceTranscriptEventsSync(whether inside or outside the transaction) already includes any foreign row committed before the function was even called, so it validates cleanly while the rewrite still silently drops that row. I confirmed this by writing a cross-process concurrency test with that exact shape before implementing the real fix, and watched it fail the same way #124456's approach would have.The actual fix has to carry the snapshot from the caller: it must be captured immediately after
SessionManager's own last confirmed commit (load or append), not re-read at rewrite time. This PR:readTranscriptSnapshotSyncso a caller can capture the transcript row snapshot it currently believes is durable.replaceTranscriptEventsSyncaccept that snapshot as an optionalexpectedSnapshotand revalidate it (not a freshly re-read one) inside the write transaction, right afterBEGIN IMMEDIATE— the same point the async sibling revalidates at.SessionManagerCoretrack this snapshot across every load/reload and every synchronous append (persistRecord), and pass it intoreplaceTranscriptEventsSyncon rewrite.SqliteTranscriptMutationConflictError,replacePersistedTranscriptcallsreloadPersistedTranscript()to resync in-memory entries onto the foreign row (the same self-healSessionManageralready performs elsewhere when it detects drift), then rethrows so the caller gets a non-success outcome instead of a silently-succeeded deletion.session-manager-branching.ts's other call site targets a freshly created, empty transcript and doesn't passexpectedSnapshot, so it's unaffected — matching the issue's note that this call site is already safe.Follow-up fix: atomic in-transaction snapshot capture (ClawSweeper P1)
ClawSweeper's review flagged a real gap in the first version of this PR:
SessionManagerCore/SessionManagerPersistencetracked the "expected" snapshot by callingpersistSqliteRecord()(which commits its own append transaction and returns) and then separately callingrefreshTranscriptSnapshot(), a brand-newreadTranscriptSnapshotSync()read. A foreign process's commit landing between that commit-and-return and the subsequent reread would be silently absorbed into the tracked "expected" snapshot without thisSessionManagerever having observed it in memory — defeating the whole point of the earlier fix for a second append that raced in after the first.Fixed by:
onCommittedSnapshottoappendTranscriptEventSync,appendTranscriptMessageSync, andreplaceTranscriptEventsSync(src/config/sessions/session-accessor.sqlite-contract.ts,session-accessor.sqlite-transcript-write.ts): the callback runs from inside each operation's own write transaction, immediately after the row is written, so it observes exactly that commit and nothing that could land afterward.SessionManagerCore#recordCommittedTranscriptSnapshot(session-manager-core.ts) and every append call site inSessionManagerPersistence#persistRecord(session-manager-persistence.ts) to useonCommittedSnapshotinstead of a post-hocrefreshTranscriptSnapshot()call. There is no longer any reread after a synchronous append — the tracked snapshot is only ever written from inside the transaction that produced it.Evidence
Real cross-process behavior trace (redacted temp paths), demonstrating: SessionManager's own append → a genuinely separate OS process committing its own foreign append to the same transcript → SessionManager's rewrite correctly rejecting on the stale in-memory snapshot → durable reload preserving the foreign row instead of losing it:
This was produced by a disposable script that opened a real SQLite-backed session, appended through
SessionManagerin the main process, forked a real child process that committed its own append viaappendTranscriptMessagedirectly against the same store, then calledmanager.removeTrailingEntries(...)back in the main process. The rewrite is refused (not silently accepted), the foreign row survives on disk, and the in-memory leaf resyncs to it. The script was run once to capture this trace and removed; it is not part of the repo.Tests
src/config/sessions/session-accessor.reply-init-concurrency.test.ts: cross-process test (rejects a sync transcript rewrite after another process commits an append) that spawns a real child process, mirroring the existing async-path test for the same scenario.src/agents/sessions/session-manager.transcript-snapshot-race.test.ts(new, split out ofsession-manager.test.ts): two same-process tests exercising the productionSessionManagerAPI directly —readTranscriptSnapshotSyncreread ever happens after a synchronous append (guards against the ClawSweeper P1 regressing),removeTrailingEntriesrejects withSqliteTranscriptMutationConflictErrorwhen a foreign process commits right after our own last append, and that the foreign row plus the manager's reloaded leaf id both reflect the durable state.Ran scoped to sessions (Node 24.15.0 — this repo's SQLite WAL-safety check rejects Node 22.22.0's embedded SQLite):
Test Plan
session-manager.transcript-snapshot-race.test.tscovers the ClawSweeper P1 follow-up: no post-commit reread, and correct rejection/reload when a foreign commit lands right after our own last append