Skip to content

fix(sessions): detect concurrent transcript conflicts in sync rewrite (#124393) - #124749

Closed
wakqasahmed wants to merge 5 commits into
openclaw:mainfrom
wakqasahmed:fix/sync-transcript-rewrite-conflict-124393
Closed

wakqasahmed wants to merge 5 commits into
openclaw:mainfrom
wakqasahmed:fix/sync-transcript-rewrite-conflict-124393

Conversation

@wakqasahmed

@wakqasahmed wakqasahmed commented Aug 16, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

replaceTranscriptEventsSync rewrote a transcript's rows without revalidating them against a pre-rewrite snapshot. A transcript row committed by another process between SessionManager's last append and the rewrite was silently deleted, and the call still returned true (success). The async sibling withTranscriptWriteLock().replaceEvents already refuses the identical write with SqliteTranscriptMutationConflictError.

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:

const snapshotRows = readTranscriptEventRows(database, resolved.sessionId);
assertSqliteTranscriptSnapshotUnchanged(database, resolved.sessionId, snapshotRows);

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 to replaceTranscriptEventsSync — not the few microseconds inside the function itself. A snapshot read at the top of replaceTranscriptEventsSync (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:

  • Adds readTranscriptSnapshotSync so a caller can capture the transcript row snapshot it currently believes is durable.
  • Makes replaceTranscriptEventsSync accept that snapshot as an optional expectedSnapshot and revalidate it (not a freshly re-read one) inside the write transaction, right after BEGIN IMMEDIATE — the same point the async sibling revalidates at.
  • Makes SessionManagerCore track this snapshot across every load/reload and every synchronous append (persistRecord), and pass it into replaceTranscriptEventsSync on rewrite.
  • Adds conflict recovery: on SqliteTranscriptMutationConflictError, replacePersistedTranscript calls reloadPersistedTranscript() to resync in-memory entries onto the foreign row (the same self-heal SessionManager already 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 pass expectedSnapshot, 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/SessionManagerPersistence tracked the "expected" snapshot by calling persistSqliteRecord() (which commits its own append transaction and returns) and then separately calling refreshTranscriptSnapshot(), a brand-new readTranscriptSnapshotSync() 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 this SessionManager ever 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:

  • Adding onCommittedSnapshot to appendTranscriptEventSync, appendTranscriptMessageSync, and replaceTranscriptEventsSync (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.
  • Wiring SessionManagerCore#recordCommittedTranscriptSnapshot (session-manager-core.ts) and every append call site in SessionManagerPersistence#persistRecord (session-manager-persistence.ts) to use onCommittedSnapshot instead of a post-hoc refreshTranscriptSnapshot() 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:

[main pid 149465] created session store at /tmp/openclaw-real-proof-XXXXXX/sessions.json
[main pid 149465] SessionManager committed own append: a1f9ca0a
[foreign pid 150004] committed foreign append: foreign-message
[main pid 149465] foreign process reported: { ok: true, messageId: 'foreign-message' }
[main pid 149465] attempting removeTrailingEntries on stale in-memory snapshot...
[main pid 149465] rewrite correctly rejected: SqliteTranscriptMutationConflictError: SQLite transcript changed while preparing rewrite for real-proof-session
[main pid 149465] durable transcript ids after rejected rewrite: [ 'real-proof-session', 'a1f9ca0a', 'foreign-message' ]
[main pid 149465] SessionManager leaf id after reload: foreign-message

This was produced by a disposable script that opened a real SQLite-backed session, appended through SessionManager in the main process, forked a real child process that committed its own append via appendTranscriptMessage directly against the same store, then called manager.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 of session-manager.test.ts): two same-process tests exercising the production SessionManager API directly —
    • asserts no readTranscriptSnapshotSync reread ever happens after a synchronous append (guards against the ClawSweeper P1 regressing),
    • asserts removeTrailingEntries rejects with SqliteTranscriptMutationConflictError when 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):

vitest run --config test/vitest/vitest.agents-support.config.ts src/agents/sessions/session-manager.test.ts
# 26 passed
vitest run --config test/vitest/vitest.agents-support.config.ts src/agents/sessions/session-manager.persistence-compat.test.ts
# 6 passed
vitest run --config test/vitest/vitest.agents-support.config.ts src/agents/sessions/session-manager.tool-result-replay.test.ts
# 4 passed
vitest run --config test/vitest/vitest.agents-support.config.ts src/agents/sessions/session-manager.transcript-snapshot-race.test.ts
# 2 passed
vitest run --config test/vitest/vitest.unit-fast.config.ts src/agents/sessions/session-manager.fork-rebase.test.ts src/agents/sessions/session-manager.user-idempotency.test.ts src/agents/sessions/session-manager-codec.test.ts
# 9 passed
vitest run --config test/vitest/vitest.runtime-config.config.ts src/config/sessions/session-accessor.reply-init-concurrency.test.ts
# 7 passed

Test Plan

  • New cross-process concurrency test covers the original race (two writers, one commits between snapshot and delete)
  • New session-manager.transcript-snapshot-race.test.ts covers the ClawSweeper P1 follow-up: no post-commit reread, and correct rejection/reload when a foreign commit lands right after our own last append
  • Real cross-process behavior trace captured and included above
  • Existing sessions/session-accessor test suites pass unchanged

@clawsweeper

clawsweeper Bot commented Aug 16, 2026

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

@openclaw-barnacle openclaw-barnacle Bot added agents Agent runtime and tooling size: M triage: needs-pr-context Candidate: external PR body lacks required problem context or evidence. labels Aug 16, 2026
@clawsweeper clawsweeper Bot added merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. P2 Normal backlog priority with limited blast radius. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Aug 16, 2026
@clawsweeper

clawsweeper Bot commented Aug 16, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: blocked before merge. Reviewed September 3, 2026, 3:06 AM ET / 07:06 UTC.

ClawSweeper review

What this changes

The 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
Reviewed head: c07af72821dadc46f86ae37ab1edad916f312987

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) The proof is strong for the reviewed head, but a definite lint failure and dirty current-main integration prevent merge readiness.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (terminal): The PR body supplies a redacted terminal trace of the changed production path: SessionManager appends, a separate OS process appends to the same SQLite transcript, and a later rewrite rejects the stale snapshot while the durable foreign row and reloaded leaf remain present. The source maps that scenario to the synchronous rewrite and snapshot callbacks; it was not rerun in this read-only review.
Patch quality 🦐 gold shrimp (3/6) 1 actionable review finding remain.

Verification

Check Result Evidence
Real behavior Verified Sufficient (terminal): The PR body supplies a redacted terminal trace of the changed production path: SessionManager appends, a separate OS process appends to the same SQLite transcript, and a later rewrite rejects the stale snapshot while the durable foreign row and reloaded leaf remain present. The source maps that scenario to the synchronous rewrite and snapshot callbacks; it was not rerun in this read-only review.
Evidence reviewed 6 items Snapshot invariant on the reviewed head: The synchronous rewrite validates the caller-held snapshot inside its write transaction, while synchronous event and message appends retain a stale snapshot rather than absorbing an unobserved foreign row.
SessionManager caller and recovery path: SessionManager loads events and snapshots in one read transaction, passes its tracked snapshot into rewrites, and reloads durable state when the conflict error is raised.
Boundary-level regression coverage: The added tests exercise the SessionManager conflict/reload behavior and a foreign-before-own-append case; the existing cross-process harness adds a synchronous rewrite scenario that asserts the foreign row survives.
Findings 1 actionable finding [P2] Remove the unused setup result
Security None None.

How this fits together

SessionManager 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]
Loading

Before merge

  • Remove the unused setup result (P2) - The append result assigned here is never read, while .oxlintrc.json enables eslint/no-unused-vars as an error. Removing the binding fixes the concrete lint failure without changing the scenario.
  • Resolve merge risk (P1) - The current head is dirty against main after substantial owner-path rewrites, so its snapshot state changes cannot be safely merged without a rebase and fresh integration review.
  • Resolve merge risk (P1) - This bug fix adds production +270/-32 (net +238); retain only the snapshot behavior required by the current owner boundary or justify the remaining growth after the rebase.
  • Resolve merge risk (P1) - Current-main source blobs could not be fetched from the partial clone because GitHub DNS resolution failed, leaving whether main has independently superseded any part of this approach unverified.
  • Complete next step (P2) - Rebase onto current main, remove the unused user binding in src/agents/sessions/session-manager.transcript-snapshot-race.test.ts, and rerun the focused cross-process transcript-conflict proof on the rebased head.
  • Add data-model compatibility proof - Confirm migration or upgrade compatibility proof before merge.

Findings

  • [P2] Remove the unused setup result — src/agents/sessions/session-manager.transcript-snapshot-race.test.ts:94-98
Agent review details

Security

None.

PR surface

Source +238, Tests +429. Total +667 across 11 files.

View PR surface stats
Area Files Added Removed Net
Source 8 270 32 +238
Tests 3 430 1 +429
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 11 700 33 +667

Review metrics

Metric Value Why it matters
Production versus test LOC production +270/-32; tests +430/-1 The net +238 production growth for a bug fix needs reassessment while porting onto the substantially rewritten current session owner.
Current-main drift 5,644 commits after the merge base The PR is currently dirty and every changed production owner path has diverged, so the original evidence must be refreshed after rebase.

Stored data model

Persistent data-model change detected: serialized state: src/agents/sessions/session-manager-persistence.ts, unknown-data-model-change: src/agents/sessions/session-manager-persistence.ts. Confirm migration or upgrade compatibility proof before merge.

Root-cause cluster

Relationship: fixed_by_candidate
Canonical: #124393
Summary: This PR is a candidate fix for the canonical concurrent synchronous transcript-rewrite issue.

Members:

Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything.

Merge-risk options

Maintainer options:

  1. Rebase and revalidate the snapshot fix (recommended)
    Resolve the current-main conflicts, remove the lint error, and post focused cross-process proof for the rebased owner path before merge.
  2. Pause this branch
    If current main already has an equivalent safer session rewrite, close this stale implementation in favor of that canonical path.

Technical review

Best 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:

  • [P2] Remove the unused setup result — src/agents/sessions/session-manager.transcript-snapshot-race.test.ts:94-98
    The append result assigned here is never read, while .oxlintrc.json enables eslint/no-unused-vars as an error. Removing the binding fixes the concrete lint failure without changing the scenario.
    Confidence: 0.99

Overall correctness: patch is incorrect
Overall confidence: 0.99

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning high; reviewed against 8ffa76c28032.

Labels

Label justifications:

  • P2: This addresses a bounded concurrent transcript-write defect that can otherwise silently discard session history.
  • merge-risk: 🚨 session-state: The PR changes conflict detection and reload behavior for persisted SQLite transcript rows, and its stale dirty head has not been integrated with current session code.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦞 diamond lobster and patch quality is 🦐 gold shrimp.
  • status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action. Sufficient (terminal): The PR body supplies a redacted terminal trace of the changed production path: SessionManager appends, a separate OS process appends to the same SQLite transcript, and a later rewrite rejects the stale snapshot while the durable foreign row and reloaded leaf remain present. The source maps that scenario to the synchronous rewrite and snapshot callbacks; it was not rerun in this read-only review.
  • proof: sufficient: Contributor real behavior proof is sufficient. The PR body supplies a redacted terminal trace of the changed production path: SessionManager appends, a separate OS process appends to the same SQLite transcript, and a later rewrite rejects the stale snapshot while the durable foreign row and reloaded leaf remain present. The source maps that scenario to the synchronous rewrite and snapshot callbacks; it was not rerun in this read-only review.

Evidence

What I checked:

  • Snapshot invariant on the reviewed head: The synchronous rewrite validates the caller-held snapshot inside its write transaction, while synchronous event and message appends retain a stale snapshot rather than absorbing an unobserved foreign row. (src/config/sessions/session-accessor.sqlite-transcript-write.ts:183, c07af72821da)
  • SessionManager caller and recovery path: SessionManager loads events and snapshots in one read transaction, passes its tracked snapshot into rewrites, and reloads durable state when the conflict error is raised. (src/agents/sessions/session-manager-core.ts:74, c07af72821da)
  • Boundary-level regression coverage: The added tests exercise the SessionManager conflict/reload behavior and a foreign-before-own-append case; the existing cross-process harness adds a synchronous rewrite scenario that asserts the foreign row survives. (src/agents/sessions/session-manager.transcript-snapshot-race.test.ts:83, c07af72821da)
  • Concrete lint blocker: The first user result is assigned but never read, while the repository enables eslint/no-unused-vars as an error. This is the same head reviewed previously. (src/agents/sessions/session-manager.transcript-snapshot-race.test.ts:94, c07af72821da)
  • Current-main integration drift: The PR head is not on current main; main is 5,644 commits ahead of the recorded merge base and all six touched production owner paths differ. The supplied GitHub state marks the PR dirty. The partial clone could not retrieve current-main source blobs because DNS resolution for GitHub failed, so equivalence with the rewritten current implementation remains unverified. (8ffa76c28032)
  • Recent area history: Recent session-accessor maintenance includes the session import-surface refactor by Peter Steinberger, making that history a useful routing signal; source-line introduction could not be independently established from the partial clone. (src/config/sessions/session-accessor.sqlite-transcript-write.ts:183, 29fd6aaf6bb3)

Likely related people:

  • Peter Steinberger: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)

Rank-up moves

Optional improvements that raise the rating; they are not merge blockers.

  • Remove the unused user binding in the new regression test.
  • Rebase onto current main and rerun the focused cross-process transcript-conflict proof on the resulting head.

Rating scale

Score Internal tier Crab rank Meaning
6/6 S 🦀 challenger crab Exceptional readiness
5/6 A 🦞 diamond lobster Very strong readiness
4/6 B 🐚 platinum hermit Good normal PR; ordinary maintainer review
3/6 C 🦐 gold shrimp Useful, but confidence is limited
2/6 D 🦪 silver shellfish Proof or implementation needs work
1/6 F 🧂 unranked krab Not merge-ready
N/A NA 🌊 off-meta tidepool Rating does not apply

Overall follows the weaker of proof and patch quality.
Shiny media proof means a screenshot, video, or linked artifact directly shows the changed behavior. Runtime, network, CSP, and security claims still need visible diagnostics.

Workflow

  • ClawSweeper keeps one durable marker-backed review comment per issue or PR.
  • Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
  • A fresh review can be triggered by eligible @clawsweeper re-review comments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.
  • PR/issue authors and users with repository write access can comment @clawsweeper re-review or @clawsweeper re-run on an open PR or issue to request a fresh review only.
  • Maintainers can also comment @clawsweeper review to request a fresh review only.
  • Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge.
  • Maintainer-only repair and merge flows require explicit commands such as @clawsweeper autofix, @clawsweeper automerge, @clawsweeper fix ci, or @clawsweeper address review.
  • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.

History

Review history (9 earlier review cycles; latest 8 shown)
  • reviewed 2026-08-17T08:19:52.744Z sha 58aa178e766e4de54573f79e6a5beddbb1c0fa89 :: needs changes before merge. :: [P1] Capture the load snapshot with the loaded events | [P2] Remove the unused test result
  • reviewed 2026-08-17T08:30:57.065Z sha e4ee51242a5359dac989f2f8aee7495f338f3d7d :: needs changes before merge. :: [P1] Capture the load snapshot with the loaded events
  • reviewed 2026-08-17T20:01:32.055Z sha 6644ee756ceed269dab9a5361ed5537810bc3b82 :: needs changes before merge. :: [P1] Validate the prior snapshot before recording an append snapshot
  • reviewed 2026-08-18T15:39:41.284Z sha 6fa1d7f060fb84590af9ea3ef8ad8881c789ed00 :: needs maintainer review before merge. :: none
  • reviewed 2026-08-22T14:29:14.605Z sha c07af72 :: needs maintainer review before merge. :: none
  • reviewed 2026-08-23T19:19:51.963Z sha c07af72 :: needs maintainer review before merge. :: none
  • reviewed 2026-08-29T19:50:33.674Z sha c07af72 :: needs changes before merge. :: [P2] Remove the unused setup result
  • reviewed September 3, 2026, 3:06 AM ET / 07:06 UTC sha unknown :: blocked before merge. :: [P2] Remove the unused setup result

@openclaw-barnacle openclaw-barnacle Bot removed the triage: needs-pr-context Candidate: external PR body lacks required problem context or evidence. label Aug 17, 2026
@clawsweeper clawsweeper Bot added proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. and removed rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Aug 17, 2026
@wakqasahmed

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Aug 17, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event exact_review_queue).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

Re-review progress:

@wakqasahmed

Copy link
Copy Markdown
Contributor Author

Fixed in 6fa1d7f. Confirmed the gap: appendTranscriptEventSync (and the same-shaped appendTranscriptMessageSync) unconditionally handed onCommittedSnapshot the full post-append row read, with no check against what the manager thought was still durable. A non-message append (e.g. appendThinkingLevelChange) has no effectiveParentId reconciliation the way a message append does, so a foreign row landing in that gap was silently absorbed into the trusted snapshot and a later rewrite could delete it.

Threaded expectedSnapshot through both append functions: they now revalidate the callers prior snapshot inside the append transaction (mirroring the async withTranscriptWriteLock().appendMessage sibling) and skip recording a new "trusted" snapshot when it no longer matches. The caller's stale snapshot then trips replaceTranscriptEventsSync's existing assertSqliteTranscriptSnapshotUnchanged check on the next rewrite, which throws SqliteTranscriptMutationConflictError and triggers the existing reload-on-conflict path instead of silently dropping the foreign row.

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: session-manager.transcript-snapshot-race.test.ts (4 passed), session-accessor.reply-init-concurrency.test.ts (7 passed), session-manager.test.ts (26 passed).

@wakqasahmed

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Aug 18, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event exact_review_queue).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

Re-review progress:

@clawsweeper clawsweeper Bot added rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Aug 18, 2026
…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).
@wakqasahmed
wakqasahmed force-pushed the fix/sync-transcript-rewrite-conflict-124393 branch from 6fa1d7f to c07af72 Compare August 22, 2026 14:22
@wakqasahmed

Copy link
Copy Markdown
Contributor Author

Rebased onto current main (was diverged 2/1034 commits and marked CONFLICTING) to resolve the merge-risk item flagged in review. One real conflict, in session-accessor.sqlite-contract.ts: main had independently added a new beforeCommitInTransaction field to the same TranscriptEventAppendOptions type this PR adds onCommittedSnapshot/expectedSnapshot to — kept both, they're unrelated options used by different call sites (verified against session-accessor.entry-mutation.ts and session-accessor.sqlite-transcript-write.ts, both already correctly reference their respective option). No other conflicts.

Re-ran the full affected suite post-rebase on Node 24.15.0:

  • session-manager.test.ts + session-manager.persistence-compat.test.ts + session-manager.tool-result-replay.test.ts + session-manager.transcript-snapshot-race.test.ts: 41/41 passing
  • session-accessor.reply-init-concurrency.test.ts (cross-process): 7/7 passing
  • session-manager.fork-rebase.test.ts + session-manager.user-idempotency.test.ts + session-manager-codec.test.ts: 15/15 passing

PR is now MERGEABLE against current main. @clawsweeper re-review

@clawsweeper clawsweeper Bot added rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. and removed rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels Aug 29, 2026
@VACInc

VACInc commented Sep 7, 2026

Copy link
Copy Markdown
Member

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.

@VACInc VACInc closed this Sep 7, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. size: L status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

sessions: sync transcript rewrite deletes concurrently committed transcript rows and reports success

2 participants