Skip to content

fix(sessions): guard sync transcript rewrite against concurrent commits - #124899

Closed
a-yeyang wants to merge 11 commits into
openclaw:mainfrom
a-yeyang:fix/sync-transcript-rewrite-snapshot-guard
Closed

a-yeyang wants to merge 11 commits into
openclaw:mainfrom
a-yeyang:fix/sync-transcript-rewrite-snapshot-guard

Conversation

@a-yeyang

@a-yeyang a-yeyang commented Aug 16, 2026 •

Copy link
Copy Markdown
Contributor

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().replaceEvents already refuses
this exact race: it captures a row snapshot, revalidates it with
assertSqliteTranscriptSnapshotUnchanged inside the write transaction right
before the destructive replace, and throws SqliteTranscriptMutationConflictError
on divergence. The synchronous path used by SessionManagerPersistence.removeTrailingEntries
-> SessionManagerCore.replacePersistedTranscript had no equivalent guard, so it
was the one call site of replaceTranscriptEventsSync that could still silently
drop a foreign row.

The fix mirrors the safety property already proven by the async sibling instead
of inventing a new mechanism:

  • replaceTranscriptEventsSync gains an optional 3rd expectedSnapshot
    parameter. When provided, it is revalidated (not re-read) inside the write
    transaction via the existing assertSqliteTranscriptSnapshotUnchanged helper,
    immediately before the destructive replace. SqliteTranscriptMutationConflictError
    is now exported so callers can catch it by type.
  • SessionManagerCore tracks its own last-known-good row snapshot
    (persistedRowSnapshot), set at load time and passed into
    replaceTranscriptEventsSync on rewrite. On conflict, replacePersistedTranscript
    reloads durable state via the existing reloadPersistedTranscript() self-heal
    before rethrowing, so callers never see in-memory state that no longer matches
    what was actually persisted.
  • session-manager-branching.ts's createBranchedSession refreshes the tracked
    snapshot 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.ts classifies the new conflict as a coordination error, not
    a 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 was
originally refreshed by a separate, out-of-transaction read
(refreshPersistedRowSnapshot()) immediately after each append committed. A
foreign 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 fileEntries never 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.ts adds
    appendTranscriptEventWithSnapshotSync / appendTranscriptMessageWithSnapshotSync,
    which return { result, snapshot } where snapshot is read from the same
    write 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 in
    persistSqliteRecord() (leaf control entries, non-message indexed entries,
    and message entries) now use the *WithSnapshotSync variants and adopt the
    returned snapshot via a new SessionManagerCore.applyPersistedRowSnapshot(),
    instead of the old append-then-separately-refresh two-step.
  • refreshPersistedRowSnapshot() is retained only for the one remaining
    caller 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 withTranscriptWriteLock already 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
SessionManager opens an empty transcript it defers the header: it starts
with zero entries and an empty tracked snapshot, and the header row was
previously committed by a separate appendTranscriptEventSync call before
the 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 later
replacePersistedTranscript would 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.ts exports a
    PendingTranscriptHeader type ({ event, expectedSnapshot }) and a
    foldPendingTranscriptHeaderInTransaction(...) helper that first revalidates
    the manager's tracked (empty) snapshot via assertSqliteTranscriptSnapshotUnchanged
    and then appends the header — both inside the first record's own write
    transaction, before it commits.
  • appendTranscriptEventWithSnapshotSync / appendTranscriptMessageWithSnapshotSync
    take an optional trailing pendingHeader; the raw-event append path
    (session-accessor.sqlite-transcript-event-write.ts) folds it in immediately
    before the record insert.
  • session-manager-persistence.ts resolves the pending header once per
    persistSqliteRecord (resolvePendingTranscriptHeader) and threads it through
    all 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.
  • New child-process regression driving the exact SessionManager
    header-then-first-record sequence (sync-initial-header-race): a worker opens
    an empty-transcript manager, a foreign appendTranscriptMessage lands in the
    gap (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

loadTranscriptRowSnapshotSync was exported through both transcript barrels
(session-accessor.transcript.ts, session-accessor.ts) but its only caller
was the new concurrency test support. It is deleted from
session-accessor.sqlite-read.ts and both barrels; the test-support worker now
models the legacy post-write refresh with
loadTranscriptEventsWithRowSnapshotSync(scope).rows, so no production API
exists 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 — took
the appendTranscriptEventWithSnapshotSync path with no snapshot guard at
all
. 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 later replacePersistedTranscript
validated 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.ts now resolves one resolveAppendGuard(scope, additive) per record. Raw and leaf appends pass additive: false and always
    revalidate this manager's tracked snapshot inside the append's own write
    transaction (folding a still-deferred header when pending). Message appends
    pass additive: true and guard only while a header is still deferred —
    they reconcile an adopted/rebound parent via effectiveParentId rather than
    trusting 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).
  • persistSqliteRecord now wraps the append in a try/catch: on
    SqliteTranscriptMutationConflictError it calls the existing
    reloadPersistedTranscript() to resync in-memory state from the authoritative
    DB 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. (replacePersistedTranscript already had this
    reload-on-conflict; this extends the same self-heal to the append path.)
  • Two new child-process regressions, both confirmed to fail on pre-fix code for
    the intended reason (verified via git stash):
    • rejects a manager raw append when a foreign row lands before it: opens a
      populated (non-deferred-header) transcript, lands a foreign
      appendTranscriptMessage in the gap, drives a raw appendModelChange, and
      asserts 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 appendMessage
      a 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 of
      looping on the stale snapshot.

Production LOC for this follow-up is net-positive (persistence
session-manager-persistence.ts and 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 resolveAppendGuard
owner 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: resolveAppendGuard
folds the still-deferred header into the first append's guard, but nothing
ever cleared persistenceHeaderPending afterward. So on a freshly opened
transcript, the first append succeeded and folded the header correctly, but
the flag stayed stuck true — every later append (including an
active-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
SqliteTranscriptMutationConflictError where it should have gracefully
rebased 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.ts adds clearHeaderPendingAfterFold(guard),
    called after each of the three persistSqliteRecord append call sites
    (leaf control, raw/non-message, message) once their guarded append commits.
    It flips persistenceHeaderPending to false only when the guard it was
    given actually carried a header (guard?.event), mirroring the other two
    places that already clear this same flag on a successful header persist
    (replacePersistedTranscript, branch()).
  • New regression, "rebases the append after a header fold onto a foreign row instead of rejecting it" (session-manager.test.ts): opens a fresh
    transcript, 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 that
    still 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 SqliteTranscriptMutationConflictError
and 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

  • New regression test in src/config/sessions/session-accessor.reply-init-concurrency.test.ts:
    a real child-process worker opens a SessionManager, reports readiness over
    IPC, and pauses. While paused, the test's main process commits a foreign
    assistant append via appendTranscriptMessage. The worker then calls
    removeTrailingEntries, which is asserted to reject with
    SqliteTranscriptMutationConflictError, and the transcript is asserted to
    still 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.
  • New per ClawSweeper's "before merge" ask: two deterministic child-process
    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 a
    useAtomicSnapshot-parameterized worker scenario:
    • useAtomicSnapshot: false reproduces the old bug shape (append, then a
      separate post-handshake snapshot read) and proves the foreign row is
      silently dropped by the next rewrite.
    • useAtomicSnapshot: true exercises the shipped fix
      (appendTranscriptMessageWithSnapshotSync + applyPersistedRowSnapshot)
      and proves the rewrite is correctly rejected with the foreign row intact.
    • Repaired child-process run (redacted, this branch, head 6f58bdcb16d5):
      $ node scripts/run-vitest.mjs src/config/sessions/session-accessor.reply-init-concurrency.test.ts -- --reporter=verbose
      
       ✓ session accessor cross-process concurrency > observes a child that exited before the waiter attached 38ms
       ✓ session accessor cross-process concurrency > commits after same-session activity from another process 350ms
       ✓ session accessor cross-process concurrency > rejects a transcript rewrite after another process commits an append 79ms
       ✓ session accessor cross-process concurrency > preserves locked replaceEvents without a prior readEvents call 39ms
       ✓ session accessor cross-process concurrency > guards a second replace after replacing without a prior read 68ms
       ✓ session accessor cross-process concurrency > refreshes a read snapshot after an append in the same locked callback 48ms
       ✓ session accessor cross-process concurrency > rejects a sync transcript rewrite after another process commits an append 81ms
       ✓ session accessor cross-process concurrency > silently drops a foreign append when the rewrite snapshot is a stale post-handshake refresh 86ms
       ✓ session accessor cross-process concurrency > rejects the rewrite and preserves a foreign append when the snapshot is captured atomically 82ms
       ✓ session accessor cross-process concurrency > silently drops a foreign append when a second rewrite's snapshot is a stale post-commit refresh 81ms
       ✓ session accessor cross-process concurrency > rejects a second rewrite and preserves a foreign append when its snapshot is captured atomically 84ms
       ✓ session accessor cross-process concurrency > rejects the first record and preserves a foreign append when the deferred header folds atomically 86ms
      
       Test Files  1 passed (1)
            Tests  12 passed (12)
      
    • The worker/process machinery was extracted to a new sibling
      session-accessor.reply-init-concurrency.test-support.ts (following the
      repo's existing *.test-support.ts convention) to keep the growing test
      file under the oxlint max-lines test-file cap.
  • New test in src/agents/failover-error.test.ts covering both a direct and a
    nested (cause-wrapped) SqliteTranscriptMutationConflictError, asserting
    resolveModelFallbackError classifies it as { kind: "coordination" }.
  • New per ClawSweeper's latest review: two child-process regressions for the
    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 a
      populated (non-deferred-header) transcript, lands a foreign
      appendTranscriptMessage in the gap, drives a raw appendModelChange, and
      asserts 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 appendMessage a
      second 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.
    • Adding these two scenarios pushed the concurrency test-support file over the
      repo's 700-line test-file cap, so the emitted child-worker source
      (createConcurrencyWorkerScript plus the shared SESSION_KEY/AGENT_ID
      constants it interpolates) was extracted to a new sibling
      session-accessor.reply-init-concurrency.worker-script.ts, per AGENTS.md's
      "split, don't suppress" policy; the harness that spawns and drives the worker
      stays in *.test-support.ts and re-exports the two constants so the test
      file's imports are unchanged.
  • Full concurrency suite green on this branch (14/14, up from 12 with the two
    new regressions):
    $ node scripts/run-vitest.mjs src/config/sessions/session-accessor.reply-init-concurrency.test.ts -- --reporter=verbose
    ...
     ✓ rejects the first record and preserves a foreign append when the deferred header folds atomically
     ✓ rejects a manager raw append when a foreign row lands before it
     ✓ reloads the manager after a deferred-header conflict so a retry succeeds
    
     Test Files  1 passed (1)
          Tests  14 passed (14)
    
  • Full focused suite green locally on this branch's head: src/config/sessions,
    src/agents/sessions (including session-manager.test.ts 25/25, the additive
    "keeps stale appenders valid across a reset" invariant),
    src/agents/failover-error.test.ts (66/66) all passing.
  • pnpm tsgo:core and pnpm tsgo:core:test: clean.
  • Full local check:changed --dry-run sweep 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-ratchet and
    check:assertion-safety report pre-existing origin/main baseline drift
    unrelated to this branch (confirmed via git stash control: identical
    failures with this branch's changes removed).
  • Local autoreview --mode local (Codex gpt-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 replaceTranscriptEventsSync
and the raw-event append path pushed session-accessor.sqlite-transcript-write.ts
over the repo's ~700-line split guideline. Per AGENTS.md's "split, don't
suppress" policy, the raw (non-message) transcript event append family
(appendTranscriptEvent, appendTranscriptEventSync,
appendTranscriptEventWithSnapshotSync, and their shared internal helpers) was
extracted 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.txt was 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:core and
pnpm tsgo:core:test clean; a single full node scripts/check-changed.mjs
gate 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) and
session-manager.test.ts (25/25), plus session-accessor.test.ts and
session-transcript-search.test.ts. The session-accessor.sqlite-transcript-write.ts
assertion-safety baseline count was pruned (shrink-only, 7 → 5) to record the
assertions that moved into the new session-accessor.sqlite-transcript-event-write.ts
sibling; no assertions were added or left uncommented.

Fresh local autoreview --mode branch --base origin/main (Codex gpt-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 with
    SqliteTranscriptMutationConflictError) and pass after the fix.
  • Rebased onto current origin/main (32 commits ahead at rebase time; 10
    commits rebased, zero conflicts).
  • Fresh autoreview --mode branch --base origin/main (Codex gpt-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)
:

  • Rebase: rebased onto current origin/main (11 commits, zero conflicts).
    Head is now 00839aae4cb5 (0 commits behind, 11 ahead as of this update);
    gh pr view reports mergeable: MERGEABLE.
  • Newest commit (00839aae4cb5, "reconcile id-less foreign rows before
    active-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_identities and is blind to a row with no non-blank id
    (e.g. an extensions/msteams FeedbackEvent, appended via a raw
    appendTranscriptEvent() call with no options). Such a row gets no
    identities 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 a
    foreignRowDetected signal from the snapshot guard through both append
    cores into PersistRecordResult, and into appendEntry's existing
    reload-trigger check, so a detected row-count mismatch forces a reload
    before the stale in-memory view can be trusted by a subsequent rewrite.
  • Test evidence — session-accessor.reply-init-concurrency.test.ts
    --reporter=verbose on 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 msteams FeedbackEvent shape
      racing 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"
  • Full local check:changed gate on the rebased head: green end-to-end
    for 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:core and
    tsgo:core:test, native state schema version, database-first legacy-store
    guard, 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):

File +/- Net Why
session-accessor.sqlite-transcript-event-write.ts +254/-0 +254 New file, but not new logic — this is the mandated extraction of the raw (non-message) transcript-event append family (appendTranscriptEvent, appendTranscriptEventSyncCore, appendTranscriptEventSync, appendTranscriptEventWithSnapshotSync, resolveTranscriptEventAppendParent, assertNonMessageTranscriptEvent) out of session-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.ts +128/-28 +100 Owner of appendEntry's reload-trigger check and the caller-held snapshot fields threaded into PersistRecordResult — 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.ts +176/-126 +50 The actual snapshot-validation fix (the same invariant the async withTranscriptWriteLock().replaceEvents sibling already enforces), applied to the sync rewrite/replace path plus the moved-out lines' replacement stubs.
session-manager-core.ts +66/-8 +58 Wires the reload-trigger check into the existing active-branch append/rewrite call sites; no new call sites added.
session-accessor.sqlite-read.ts +33/-0 +33 New read helper for the snapshot comparison (transcript_event_identities + id-less row count), reused by every guarded write path rather than duplicated per-caller.
session-accessor.transcript.ts +17/-1 +16 Type/interface surface for the snapshot shape shared by all callers.
session-manager-branching.ts +18/-4 +14 Propagates the same snapshot fields through branch-switch, the other caller of the active-branch append guard.
failover-error.ts +11/-0 +11 Classifies the new SqliteTranscriptMutationConflictError as a coordination error (not a provider failure) in the existing resolveModelFallbackError — reuses the existing error-classification seam, no new one.
session-manager-entries.ts +8/-1 +7 Passes the snapshot through the entries accessor already used by both append paths.
session-accessor.ts +7/-0 +7 Barrel re-export for the new sibling file — required by the split, not new logic.
session-manager.ts +7/-4 +3 Call-site wiring only.
session-accessor.entry-mutation.ts +1/-1 0 net-zero.

Net 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's appendEntry/PersistRecordResult,
and session-accessor.sqlite-transcript-write.ts's write-transaction
callbacks) — 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().replaceEvents invariant this PR extends.

@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 labels Aug 16, 2026
@a-yeyang
a-yeyang marked this pull request as ready for review August 16, 2026 23:13
@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: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. 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, 2:32 AM ET / 06:32 UTC.

ClawSweeper review

What this changes

The PR adds transactional SQLite row-snapshot checks and cross-process regressions so SessionManager rewrites and appends preserve rows committed concurrently by another process.

Regression provenance

Possible 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
Reviewed head: 46d16d1305d503b7cd51138a5d06453efbf5173b

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) The exact branch has strong deterministic concurrency coverage and no discrete correctness finding, but requires a rebase-and-rerun because the active persistence implementation has moved substantially.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (terminal): The supplied redacted terminal evidence and exact-head regression source exercise the real SessionManager and SQLite accessors across a child-process boundary, inject a foreign append before the destructive rewrite, and observe closed rejection with the foreign row intact; rerun it after rebase because current-main drift changes the exercised code.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (terminal): The supplied redacted terminal evidence and exact-head regression source exercise the real SessionManager and SQLite accessors across a child-process boundary, inject a foreign append before the destructive rewrite, and observe closed rejection with the foreign row intact; rerun it after rebase because current-main drift changes the exercised code.
Evidence reviewed 6 items Current-main defect remains: Current main still calls the synchronous replacement directly after deriving entries from SessionManager state, without a caller-owned transcript row snapshot or post-replace snapshot capture.
Fix at the destructive-write owner: The PR passes the manager-owned snapshot into the synchronous replacement transaction, revalidates it immediately before replacement, and captures the resulting rows inside that transaction.
Cross-process regression coverage: The exact head contains deterministic child-process cases for the original rewrite race, atomic append/rewrite snapshots, deferred headers, raw events, id-less events, and side-mode appends; each asserts preservation or closed rejection of the foreign row.
Findings None None.
Security None None.

How this fits together

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

Before merge

  • Resolve merge risk (P1) - Current main is 5,450 commits ahead and rewrote the central transcript writer and manager paths after this head; without a pinned test merge, rebasing could alter durable session-state behavior.
  • Resolve merge risk (P1) - The PR adds production +726/-173 (net +553) around a hot persistence boundary. The added snapshot transfer is tied to eliminating separate-read race windows; no smaller net-neutral owner refactor is evident from the reviewed writer and manager boundaries.
  • Complete next step (P2) - Rebase onto current main and rerun the focused cross-process transcript concurrency proof on the resolved head.
  • Add data-model compatibility proof - Confirm migration or upgrade compatibility proof before merge.
Agent review details

Security

None.

PR surface

Source +553, Tests +1290, Other 0. Total +1843 across 20 files.

View PR surface stats
Area Files Added Removed Net
Source 12 726 173 +553
Tests 7 1709 419 +1290
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 1 1 1 0
Total 20 2436 593 +1843

Review metrics

Metric Value Why it matters
Production versus test LOC production +726/-173; tests and test support +1709/-419 The production growth implements snapshot ownership across append and rewrite paths; the larger test delta covers deterministic cross-process interleavings.

Stored data model

Persistent data-model change detected: serialized state: src/agents/sessions/session-manager-persistence.ts, serialized state: src/config/sessions/session-accessor.sqlite-read.ts, unknown-data-model-change: src/agents/sessions/session-manager-branching.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 the active candidate fix for the canonical synchronous transcript-rewrite race.

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 with concurrency proof (recommended)
    Rebase the durable transcript changes onto current main and rerun the focused child-process concurrency suite before considering merge.

Technical review

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

Labels

Label justifications:

  • P2: The PR addresses a bounded but real silent-loss risk for concurrently committed session transcript rows.
  • merge-risk: 🚨 session-state: The branch changes rejection, reload, and snapshot ownership for durable SQLite session transcript mutations.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🦞 diamond lobster and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (terminal): The supplied redacted terminal evidence and exact-head regression source exercise the real SessionManager and SQLite accessors across a child-process boundary, inject a foreign append before the destructive rewrite, and observe closed rejection with the foreign row intact; rerun it after rebase because current-main drift changes the exercised code.
  • proof: sufficient: Contributor real behavior proof is sufficient. The supplied redacted terminal evidence and exact-head regression source exercise the real SessionManager and SQLite accessors across a child-process boundary, inject a foreign append before the destructive rewrite, and observe closed rejection with the foreign row intact; rerun it after rebase because current-main drift changes the exercised code.

Evidence

What I checked:

Likely related people:

  • steipete: 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.

  • Rebase onto current main.
  • Rerun the focused child-process transcript concurrency suite on the conflict-resolved 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 (22 earlier review cycles; latest 8 shown)
  • reviewed 2026-08-19T03:18:39.807Z sha 945791531b7188f43d80a368de03844b058adb1f :: needs changes before merge. :: [P1] Detect opaque concurrent rows before adopting a snapshot
  • reviewed 2026-08-19T07:01:38.379Z sha 8d917c1244cf13f2bc0a7ad7fd08f40026e69e91 :: needs maintainer review before merge. :: none
  • reviewed 2026-08-19T07:21:24.007Z sha bb579a3b68af8ca5892279a603200db38653ad28 :: needs maintainer review before merge. :: none
  • reviewed 2026-08-19T10:17:16.781Z sha b5b2f4f3e269753b7587cdd122b2360c0807ccf8 :: needs maintainer review before merge. :: none
  • reviewed 2026-08-22T18:54:20.774Z sha b5b2f4f3e269753b7587cdd122b2360c0807ccf8 :: needs maintainer review before merge. :: none
  • reviewed 2026-08-23T14:16:42.296Z sha 00839aae4cb543dd8e2b76303972b8a0eb0f1bf3 :: needs maintainer review before merge. :: none
  • reviewed 2026-08-23T15:48:24.695Z sha 46d16d1 :: needs maintainer review before merge. :: none
  • reviewed 2026-08-29T16:14:45.400Z sha 46d16d1 :: needs maintainer review before merge. :: none

@a-yeyang

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:

@clawsweeper clawsweeper Bot added rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. and removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. labels Aug 17, 2026
@a-yeyang
a-yeyang force-pushed the fix/sync-transcript-rewrite-snapshot-guard branch from 4acb9fb to ca40f31 Compare August 17, 2026 23:43
@clawsweeper clawsweeper Bot added proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. 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
@a-yeyang

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. 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: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Aug 18, 2026
@a-yeyang

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Aug 23, 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:

chenshiyang.10 and others added 11 commits August 23, 2026 15:41
…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.
@a-yeyang
a-yeyang force-pushed the fix/sync-transcript-rewrite-snapshot-guard branch from 00839aa to 46d16d1 Compare August 23, 2026 15:41
@a-yeyang

Copy link
Copy Markdown
Contributor Author

Rebased onto current origin/main (was 25 commits behind) to resolve the P1 "branch is behind main / incomplete check rollup" item from the latest review. Zero conflicts. New head: 46d16d1305d.

Post-rebase focused tests, green:

node scripts/run-vitest.mjs src/config/sessions/session-accessor.reply-init-concurrency.test.ts src/agents/sessions/session-manager.test.ts
 ✓ session-accessor.reply-init-concurrency.test.ts (16 tests)
 ✓ session-manager.test.ts (26 tests)

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 (session-accessor.sqlite-transcript-write.ts, session-manager-core.ts) — this is new owner-boundary protection current main lacks, not logic that could be absorbed into an existing writer without the same net surface.

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Aug 23, 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:

@VACInc

VACInc commented Sep 7, 2026

Copy link
Copy Markdown
Member

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.

@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: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. size: XL status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

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