Skip to content

fix(gateway): keep managed media referenced by inactive transcript branches - #117266

Closed
yetval wants to merge 1 commit into
openclaw:mainfrom
yetval:fix/managed-media-branch-retention
Closed

yetval wants to merge 1 commit into
openclaw:mainfrom
yetval:fix/managed-media-branch-retention

Conversation

@yetval

@yetval yetval commented Aug 1, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Rewinding or resetting a conversation could permanently delete generated media that was no longer on the active transcript path but was still reachable through an inactive branch or a live compaction checkpoint.

Cleanup treated absence from the active projection as proof that the media was orphaned. It deleted the SQLite record and the backing file. Restoring the branch or the checkpoint brought the message and its URL back, but the bytes were already gone.

Root Cause

Managed-media cleanup, HTTP serving, and artifact download shared one attachment index built from the active/restorable message projection. That projection is correct for what the operator can open immediately, but it is not the lifecycle owner for destructive retention.

The session owner already records the facts retention needs: the full SQLite transcript event tree, reset and compaction boundaries, live compaction checkpoint source sessions and fork boundaries, and the transcript rewrite generation and maximum sequence. The bug was using a consumer projection as a garbage-collection authority instead of asking the session owner which messages can become reachable again.

Canonical Fix

  • Split managed-media lookup into restorable and retained modes. HTTP serving and artifact download stay on the immediate restorable projection.
  • Destructive cleanup asks the session owner for the retained event set, walking complete canonical paths for every live transcript tip including reset-hidden ancestry that remains checkpoint-reachable.
  • Read current transcript rows, the authoritative session entry, and every live compaction checkpoint source in one deferred SQLite transaction.
  • Fail closed for destructive cleanup when checkpoint retention is incomplete, legacy file-backed, or unreadable.
  • Bypass the process-global attachment cache for retained-mode reads, because checkpoint metadata and source sessions can change without advancing the current transcript watermark.

No schema, config, migration, protocol, or changelog change is required.

Fencing Deletion Against Checkpoint Publication

The previous review found a real P1 on top of the retention change: the retention snapshot and the irreversible delete were separated by an unfenced window. Checkpoint publication commits through updateSessionEntry, which the cleanup queue does not serialize, so a snapshot that reported media unreferenced could be obsolete by the time the record and file were removed.

The session owner now derives a retention fence inside the same deferred transaction that produces the retention snapshot, from the transcript generation, the maximum sequence, and the published checkpoint set. Destructive cleanup carries that fence to the point of deletion and revalidates it there, retaining the record when the fence moved or cannot be read. This reuses the optimistic-concurrency shape already used by the checkpoint and message-cut expected-state fences rather than introducing a second independent guard.

Scope note for the maintainer: this fences the snapshot-to-delete window, which is where the reported loss occurs. It does not make deletion atomic with respect to checkpoint publication; a checkpoint committing between the fence revalidation and the unlink remains theoretically possible. Closing that last gap requires the session owner to own media deletion inside its own write transaction, which is a lifecycle redesign beyond this fix.

Safety Guards Preserved From Current Main

Every newer safeguard on the surfaces this touches is carried into the resolved integration rather than replaced.

Verification

Run from the rebased worktree at head ff07bd20f864bdfc8a85d77cdb69bd6c751e4e4d, base 1623683f478b1e4a2e3d5632585f006ea142e08c:

  • node scripts/run-vitest.mjs src/config/sessions/session-accessor.sqlite-restorable-messages.test.ts src/config/sessions/transcript-tree.test.ts src/config/sessions/session-accessor.sqlite-message-cut.test.ts - 3 files, 50 tests passed.
  • node scripts/run-vitest.mjs src/gateway/managed-image-attachments.branch-retention.test.ts src/gateway/managed-image-attachments.test.ts - 2 files, 132 tests passed.
  • oxfmt on the 12 changed files - clean.
  • oxlint --tsconfig config/tsconfig/oxlint.core.json on the 12 changed files - clean.
  • The two new fence cases fail on pristine base and pass on this head.

Real behavior proof

Behavior addressed: after sessions.rewind, managed media still referenced by the inactive transcript branch is permanently deleted by managed-media cleanup, so switching back to that branch restores a message whose bytes no longer exist.
Real environment tested: the real production entry points driven end to end against one temporary state directory with a real SQLite session store, on pristine main 1623683f478b1e4a2e3d5632585f006ea142e08c and on the rebased head ff07bd20f864bdfc8a85d77cdb69bd6c751e4e4d. Real upsertSessionEntryCore and appendTranscriptMessage build the transcript, real rewindSessionToMessage, listSessionBranches and switchSessionBranch drive the branch lifecycle, real cleanupManagedOutgoingMediaRecords performs the sweep, real resolveManagedOutgoingMediaArtifactDownload mints the scoped URL, and the bytes are fetched over a real loopback HTTP server running the real handleManagedOutgoingMediaHttpRequest. Nothing is stubbed; the only synthetic input is the seeded conversation.
Exact steps or command run after this patch: seed a six-turn session whose assistant turn carries a managed image, commit the managed record and its file, rewind to the user turn before it, sweep, switch back to the inactive branch leaf, mint an artifact URL and fetch it over authenticated loopback HTTP, publish a compaction checkpoint and re-read the session retention fence, then sweep a second record referenced by no branch at all.
Evidence after fix:

# BEFORE (pristine main 1623683f478b1e4a2e3d5632585f006ea142e08c)
[1] seeded real SQLite session store at oc-media-branch-ITSICe
    media file on disk: true
[2] rewind to turn u2 -> status=created
    branches: 2 (inactive leaf=a3 messages=6)
    the image on turn a2 is now reachable only from the inactive branch
[3] cleanup sweep -> {"deletedRecordCount":1,"deletedFileCount":1,"retainedCount":0}
    media file still on disk: false
    durable records remaining: 0
[4] switch back to the inactive branch -> status=created
    artifact download minted: false
[5] loopback HTTP GET of the managed media -> status=404 bytes=9
[6] retention fence exposed by the session owner: absent on this build
[7] deletion control: media referenced by no branch -> {"deletedRecordCount":1,"deletedFileCount":1,"retainedCount":0}
    orphan file removed: true
    branch-referenced file kept: false

# AFTER (this patch, identical inputs, head ff07bd20f864bdfc8a85d77cdb69bd6c751e4e4d)
[1] seeded real SQLite session store at oc-media-branch-dsKy2H
    media file on disk: true
[2] rewind to turn u2 -> status=created
    branches: 2 (inactive leaf=a3 messages=6)
    the image on turn a2 is now reachable only from the inactive branch
[3] cleanup sweep -> {"deletedRecordCount":0,"deletedFileCount":0,"retainedCount":1}
    media file still on disk: true
    durable records remaining: 1
[4] switch back to the inactive branch -> status=created
    artifact download minted: true
[5] loopback HTTP GET of the managed media -> status=200 bytes=8
[6] retention fence moved when a checkpoint was published: true
[7] deletion control: media referenced by no branch -> {"deletedRecordCount":1,"deletedFileCount":1,"retainedCount":1}
    orphan file removed: true
    branch-referenced file kept: true

Observed result after fix: on pristine main the rewind sweep destroys the inactive-branch record and its bytes, and the later branch switch restores a message whose artifact URL can no longer be minted and whose bytes answer 404; with this patch the same sweep keeps the record and the file, the restored branch mints a scoped URL and serves the bytes over authenticated loopback HTTP with status 200, the session retention fence visibly moves when a compaction checkpoint is published so a stale retention verdict is detectable at the point of deletion, and media referenced by no branch at all is still removed, so the change does not over-retain.
What was not tested: no live model provider or network media generation; the full production build and the complete repository suite were not run, only the affected suites; the residual window between fence revalidation and file removal is argued from the code path rather than observed, because forcing that interleaving deterministically would require a test-only hook in the cleanup loop.

@openclaw-barnacle openclaw-barnacle Bot added gateway Gateway runtime size: M labels Aug 1, 2026
@yetval
yetval marked this pull request as ready for review August 1, 2026 06:42
@yetval

yetval commented Aug 1, 2026

Copy link
Copy Markdown
Contributor Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 77409208d8

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@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. P1 High-priority user-facing bug, regression, or broken workflow. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. labels Aug 1, 2026
@clawsweeper

clawsweeper Bot commented Aug 1, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: found issues before merge. Reviewed September 2, 2026, 2:11 PM ET / 18:11 UTC.

ClawSweeper review

What this changes

The PR prevents cleanup from deleting managed attachments still reachable through transcript branches and checkpoints by adding retention-aware transcript snapshots and a revalidation fence.

Regression provenance

Possible regression — suspected (reviewed change). No predecessor PR is attributed.

Merge readiness

⚠️ Needs maintainer review before merge - 3 items remain

The retention repair remains necessary and the checkpoint fence addresses the prior finding, but the new read-only snapshot opens the writable agent database on cleanup and artifact-read paths. That reintroduces lease, WAL, schema, and cached-handle lifecycle work for a read-only operation.

Priority: P1
Reviewed head: ff07bd20f864bdfc8a85d77cdb69bd6c751e4e4d

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) The retention behavior is strongly demonstrated, but the new reader bypasses the existing read-only database lifecycle.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (terminal): The PR body provides a source-independent before/after terminal trace through real media storage, SQLite transcript persistence, cleanup, artifact resolution, and loopback HTTP. The remaining blocker is an introduced database-lifecycle regression, not missing proof of the retention repair.
Patch quality 🦐 gold shrimp (3/6) 1 actionable review finding remain.

Verification

Check Result Evidence
Real behavior Verified Sufficient (terminal): The PR body provides a source-independent before/after terminal trace through real media storage, SQLite transcript persistence, cleanup, artifact resolution, and loopback HTTP. The remaining blocker is an introduced database-lifecycle regression, not missing proof of the retention repair.
Evidence reviewed 6 items Introduced writable read path: The new retention snapshot used by cleanup and artifact resolution directly calls the writable database opener before issuing only read queries.
Observable writable opener effects: A cold writable open claims a database lease, opens a read-write connection, configures WAL and pragmas, ensures schema, registers the database, and retains a cached handle.
Canonical read-only owner: The established read-only owner avoids creation, registration, migration, and writable lifecycle admission; the watermark reader already uses it.
Findings 1 actionable finding [P1] Use the read-only session database for retention reads
Security None None.

How this fits together

Managed attachments are stored alongside transcript/session state and served through artifact URLs. Gateway cleanup and artifact reads consult transcript history to decide whether those media bytes remain reachable.

flowchart LR
A[Transcript and checkpoint state] --> B[Retention snapshot]
B --> C[Managed attachment index]
C --> D[Gateway cleanup]
C --> E[Artifact download]
D --> F[Keep or delete media]
E --> G[Serve retained media]
Loading

Before merge

  • Use the read-only session database for retention reads (P1) - The new snapshot is only used to read transcript/checkpoint reachability, but it calls openOpenClawAgentDatabase. On a cold or evicted handle this claims a lease, initializes WAL/schema, registers a writer handle, and retains it; the established read-only owner exists specifically to avoid those effects. Use withOpenClawAgentDatabaseReadOnly for both the snapshot and fence reader, preserving fail-closed behavior on absent or unreadable stores.
  • Resolve merge risk (P1) - Until the snapshot uses the read-only database owner, cold or evicted cleanup and artifact reads can claim leases, initialize WAL and schema, register writer handles, and contend with session writes despite performing no mutation.
  • Complete next step (P2) - Move the retention snapshot and fence readers onto the canonical read-only agent database owner, then prove cold reads do not enter the writer lifecycle.

Findings

  • [P1] Use the read-only session database for retention reads — src/config/sessions/session-accessor.sqlite-restorable-messages.ts:77
Agent review details

Security

None.

PR surface

Source +561, Tests +1617. Total +2178 across 12 files.

View PR surface stats
Area Files Added Removed Net
Source 8 722 161 +561
Tests 4 1708 91 +1617
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 12 2430 252 +2178

Review metrics

Metric Value Why it matters
Production vs test LOC production +722/-161 (net +561); tests +1,708/-91 (net +1,617) The sizable production addition introduces a new retention-reader owner, making its database lifecycle boundary important before merge.

Merge-risk options

Maintainer options:

  1. Use the read-only database owner (recommended)
    Adapt the retention snapshot and fence reader to borrow or open the existing session store read-only, then rerun the focused retention proof.
  2. Accept write-lifecycle overhead
    Merge with the retention correctness fix while accepting writable database initialization during cleanup and artifact reads.
Copy recommended automerge instruction
@clawsweeper automerge

Special instructions:
Use the canonical read-only agent database owner for retention snapshot and fence reads; preserve fail-closed retention behavior and add a cold-read lifecycle regression check.

Technical review

Best possible solution:

Keep the retention and fence logic, but run both snapshot and fence reads through the canonical read-only session database owner.

Do we have a high-confidence way to reproduce the issue?

Yes: a cold or evicted agent database followed by managed-media cleanup reaches the introduced snapshot, whose direct writable open has observable lifecycle effects; this read-only review did not execute the scenario.

Is this the best way to solve the issue?

No: the retention fence is the right deletion-boundary repair, but the new read-only reader must use the canonical read-only database owner before it is the best complete solution.

Full review comments:

  • [P1] Use the read-only session database for retention reads — src/config/sessions/session-accessor.sqlite-restorable-messages.ts:77
    The new snapshot is only used to read transcript/checkpoint reachability, but it calls openOpenClawAgentDatabase. On a cold or evicted handle this claims a lease, initializes WAL/schema, registers a writer handle, and retains it; the established read-only owner exists specifically to avoid those effects. Use withOpenClawAgentDatabaseReadOnly for both the snapshot and fence reader, preserving fail-closed behavior on absent or unreadable stores.
    Confidence: 0.96

Overall correctness: patch is incorrect
Overall confidence: 0.96

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning high; reviewed against 1212f991db46.

Labels

Label changes:

  • add P1: The proposed fix affects cleanup of active transcript media and can reintroduce writer lifecycle contention on recurring Gateway paths.
  • add merge-risk: 🚨 availability: The introduced read-only operation may initialize and retain writable database handles, creating avoidable contention and maintenance work in production.
  • remove P0: Current review triage priority is P1, so this older priority label is no longer current.
  • remove merge-risk: 🚨 session-state: Current PR review merge-risk labels are merge-risk: 🚨 availability.

Label justifications:

  • P1: The proposed fix affects cleanup of active transcript media and can reintroduce writer lifecycle contention on recurring Gateway paths.
  • merge-risk: 🚨 availability: The introduced read-only operation may initialize and retain writable database handles, creating avoidable contention and maintenance work in production.
  • 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 provides a source-independent before/after terminal trace through real media storage, SQLite transcript persistence, cleanup, artifact resolution, and loopback HTTP. The remaining blocker is an introduced database-lifecycle regression, not missing proof of the retention repair.
  • proof: sufficient: Contributor real behavior proof is sufficient. The PR body provides a source-independent before/after terminal trace through real media storage, SQLite transcript persistence, cleanup, artifact resolution, and loopback HTTP. The remaining blocker is an introduced database-lifecycle regression, not missing proof of the retention repair.

Evidence

Acceptance criteria:

  • [P1] Add and run the focused managed-media retention tests.
  • [P1] Add a cold-read lifecycle test showing snapshot and fence reads do not claim a lease, configure WAL, register a writer handle, or create a database.

What I checked:

Likely related people:

  • steipete: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)
  • vincentkoc: 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.

  • Move the snapshot and retention fence reads onto the canonical read-only database owner and preserve the fail-closed semantics.
  • Add a cold-read lifecycle test proving these reads do not claim a lease, initialize WAL, register a database, or leave a retained writer handle.

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 (23 earlier review cycles; latest 8 shown)
  • reviewed 2026-08-08T11:43:27.335Z sha 9d04baab18c3538f734aa1e118d628e3c64d393b :: found issues before merge. :: [P1] Preserve current GC safety guards during the rebase
  • reviewed 2026-08-09T18:48:55.457Z sha 0469ce301257a5be210e6bac6a6593999045f545 :: needs maintainer review before merge. :: none
  • reviewed 2026-08-14T16:15:02.111Z sha 0469ce301257a5be210e6bac6a6593999045f545 :: needs maintainer review before merge. :: none
  • reviewed August 15, 2026, 5:51 PM ET / 21:51 UTC sha unknown :: needs changes before merge. :: [P1] Preserve current managed-media owner resolution on rebase
  • reviewed August 19, 2026, 12:37 AM ET / 04:37 UTC sha unknown :: needs changes before merge. :: [P1] Preserve the compatibility owner before destructive cleanup | [P1] Publish the managed record only after media preparation succeeds | [P1] Retain the checkpoint expected-state mutation fence | [P1] Keep the message-cut expected-state fence during the rebase
  • reviewed 2026-08-19T04:37:46.552Z sha 0469ce301257a5be210e6bac6a6593999045f545 :: needs changes before merge. :: [P1] Preserve the compatibility owner before destructive cleanup | [P1] Publish the managed record only after media preparation succeeds | [P1] Retain the checkpoint expected-state mutation fence | [P1] Keep the message-cut expected-state fence during the rebase
  • reviewed 2026-08-22T19:52:11.750Z sha 2d04e11581b7657e2cd82d7484ffbc0a07d92d14 :: found issues before merge. :: [P1] Fence deletion against checkpoint publication
  • reviewed 2026-08-29T01:02:45.234Z sha 2d04e11581b7657e2cd82d7484ffbc0a07d92d14 :: needs changes before merge. :: [P1] Fence deletion against checkpoint publication

@vincentkoc vincentkoc self-assigned this Aug 1, 2026
@clawsweeper clawsweeper Bot added rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. and removed 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. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. labels Aug 1, 2026
@vincentkoc

Copy link
Copy Markdown
Member

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Aug 1, 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 repository_dispatch).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

Re-review progress:

@vincentkoc

Copy link
Copy Markdown
Member

@clawsweeper re-review

@clawsweeper clawsweeper Bot added proof: sufficient ClawSweeper judged the real behavior proof convincing. 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: 🦪 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 1, 2026
@vincentkoc

Copy link
Copy Markdown
Member

@clawsweeper re-review

@clawsweeper clawsweeper Bot added status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. and removed 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. labels Aug 15, 2026
@yetval
yetval force-pushed the fix/managed-media-branch-retention branch from 0469ce3 to 2d04e11 Compare August 22, 2026 19:46
@yetval

yetval commented Aug 22, 2026

Copy link
Copy Markdown
Contributor Author

Rebased and re-proved. New head 2d04e11581b7657e2cd82d7484ffbc0a07d92d14 on base d0700b3bc26bc409e4d7aaaf38f7e1d71053b2f3. The verdict was produced against the stale head 0469ce30125, and all four P1 findings were about what a mechanical merge of that head would do to main. The rebase was resolved toward keeping both behaviors, so each one is preserved rather than reasserted.

[P1] Preserve the compatibility owner before destructive cleanup - preserved. resolveManagedSessionOwnerAgentId plus tryResolveSessionCompatibilityOwnerAgentId from #123257 are the owner resolver in all three places: the cleanup filter, getSessionManagedOutgoingAttachmentIndex, and resolveManagedOutgoingMediaArtifactDownload. The older resolveDefaultAgentId and resolveAgentIdFromSessionKey fallback this branch carried is gone from the file, import included. An ownerless compatibility or global record can no longer be resolved through the wrong store.

[P1] Publish the managed record only after media preparation succeeds - preserved. insertManagedImageRecord still runs after the fallible playback and mode preparation, exactly as #124048 ordered it. A preparation failure cannot leave stale durable metadata.

[P1] Retain the checkpoint expected-state mutation fence - preserved. restoreCompactionCheckpointSession and branchCompactionCheckpointSession keep the required expectedState parameter and the conflict result from #122597, unchanged in count and shape against current main. The retention coverage was adapted to that API, not the other way round: the branch-retention case now supplies expectedState and imports from session-accessor.sqlite-checkpoint.js. Conflict-path coverage already lives in src/gateway/session-compaction-checkpoints.test.ts and is untouched.

[P1] Keep the message-cut expected-state fence during the rebase - preserved. The optimistic-concurrency validation in session-accessor.sqlite-message-cut.ts is byte-identical to current main. This diff only moves branch-tip and restorable-path selection into shared transcript-tree helpers.

[P1] Resolve merge risk (mechanical merge would reintroduce the above) - resolved by not taking a mechanical merge. The conflicts in managed-image-attachments.ts and session-transcript-readers.ts were resolved hunk by hunk: the thumbnail cache helpers from bad30d5a741 and bc4ed8dcaf4 are kept whole, the read-only serve guard keeps the resolved stateDir from main and adds the fail-closed handling on top, and only the mtime and size based cache key is replaced, by a transcript generation and sequence revision, because a file stat cannot distinguish two branch states of one transcript.

[P1] Resolve merge risk (dirty branch, stale required checks) - the branch now applies cleanly to d0700b3bc26. Renames that landed while it was behind were followed rather than reverted: session-accessor.sqlite.js to session-accessor.sqlite-checkpoint.js, restoreSqliteCompactionCheckpointSession to restoreCompactionCheckpointSession, upsertSessionEntry to upsertSessionEntryCore, loadSessionEntryReadOnly to loadGatewaySessionEntryReadOnly, and normalizeSqliteNumber to coerceSqliteNumber.

[P1] The isolated autoreview helper could not run from a grafted checkout - not author-actionable, and the underlying reason is gone: this head has a real merge base on d0700b3bc26, so the helper should run on a normal fetch now.

Two suites added to main after this branch forked needed extending, not fixing: managed audio filename stability and the bounded thumbnail ticket both drove only the legacy reader seam, so they now set the retained-mode snapshot alongside it. Both pass.

Proof repeated on the exact head. The PR body carries a fresh before/after captured on pristine d0700b3bc26 and on this head with one identical driver: real transcript append, real rewindSessionToMessage, real listSessionBranches and switchSessionBranch, real cleanupManagedOutgoingMediaRecords, real resolveManagedOutgoingMediaArtifactDownload, and a real loopback HTTP GET through handleManagedOutgoingMediaHttpRequest. On base the rewind sweep deletes the inactive-branch record and file and the restored branch can neither mint nor serve the artifact; on this head the file survives, the restored branch serves it with status 200, and media referenced by no branch is still deleted.

One environment limit to name. src/gateway/session-compaction-checkpoints.test.ts and one conformance case fail identically on pristine d0700b3bc26 and on this head, with Windows EBUSY and EPERM on temporary SQLite teardown. That is this machine, not this diff; both need a Linux runner to be observed green. The tsgo diagnostics are likewise byte-identical between base and head and come from a local dependency tree behind the lockfile.

Root-cause cluster is unchanged and still accurate. Current main has no retained-mode reader, so the defect is live: the before run above deletes the file on d0700b3bc26.

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Aug 22, 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: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. and removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. labels Aug 22, 2026
@openclaw-barnacle

Copy link
Copy Markdown

This assigned pull request has been automatically marked as stale after being open for 27 days.
Please add updates or it will be closed.

@openclaw-barnacle openclaw-barnacle Bot added the stale Marked as stale due to inactivity label Aug 29, 2026
…anches

Rewinding or resetting a conversation could permanently delete generated
media that was no longer on the active transcript path but was still
reachable through an inactive branch or a live compaction checkpoint.
Cleanup treated absence from the active projection as proof the media was
orphaned, deleted the SQLite record and the backing file, and a later
branch or checkpoint restore brought back a message whose bytes were gone.

Managed-media lookup is now split into restorable and retained modes. HTTP
serving and artifact download stay on the immediate restorable projection.
Destructive cleanup asks the session owner for the retained event set,
walking complete canonical paths for every live transcript tip including
reset-hidden ancestry that remains checkpoint-reachable, and fails closed
when checkpoint retention is incomplete, legacy file-backed, or unreadable.

The retention snapshot and the irreversible delete were also separated by an
unfenced window, because checkpoint publication commits through a session
write path that the cleanup queue does not serialize. The session owner now
derives a retention fence from the transcript generation, the maximum
sequence, and the published checkpoint set inside the same deferred
transaction that produces the snapshot. Cleanup carries that fence to the
point of deletion and revalidates it there, retaining the record when the
fence moved or cannot be read.

Integration with current main preserves every newer safeguard on these
surfaces rather than reasserting this branch's older shape: compatibility
owner resolution for destructive cleanup, publication of the managed record
only after media preparation succeeds, the checkpoint expected-state conflict
fence, read-only database reads for the transcript watermark, the canonical
transcript projection helper, and the separation of display media from model
history in the attachment index. The tri-state session-store availability
read still retains a record when reachability cannot be determined, and an
aged transient record is still retained while its session has an active run.

Co-authored-by: Vincent Koc <[email protected]>
@yetval
yetval force-pushed the fix/managed-media-branch-retention branch from 2d04e11 to ff07bd2 Compare September 2, 2026 17:53
@yetval

yetval commented Sep 2, 2026

Copy link
Copy Markdown
Contributor Author

Rebased and re-proved. New head ff07bd20f864bdfc8a85d77cdb69bd6c751e4e4d on base 1623683f478b1e4a2e3d5632585f006ea142e08c.

Answering the verdict at 2d04e11581b7657e2cd82d7484ffbc0a07d92d14 item by item.

[P1] Fence deletion against checkpoint publication - fixed.
The session owner now derives a retention fence inside the same deferred transaction that produces the retention snapshot, from the transcript generation, the maximum sequence, and the published checkpoint set. Destructive cleanup carries that fence to the point of deletion and revalidates it there, retaining the record when the fence moved or cannot be read. This uses the optimistic-concurrency shape already established by the checkpoint and message-cut expected-state fences rather than adding a second independent guard, which also answers the "consolidate rather than add another parallel guard" note.

Interleaving regressions added:

  • keeps media when a checkpoint publication moves the retention fence before deletion - the snapshot is taken at one fence, publication moves it, and the sweep retains instead of deleting.
  • deletes media when the retention fence is unchanged at deletion - the control, so the fence does not simply disable cleanup.
  • moves the retention fence when a checkpoint is published after a retention read - drives the real session store and the real fence reader.

Coverage gap on the pre-seeded checkpoint test - addressed. The new cases above interleave publication with the retention decision instead of pre-seeding an already-persisted checkpoint.

Residual, and it is a maintainer call. The fence closes the snapshot-to-delete window, which is where the reported loss happens. It does not make deletion atomic with respect to checkpoint publication: a checkpoint committing between the fence revalidation and the unlink is still theoretically possible. Making that impossible means moving media deletion inside the session owner's write transaction, which is a lifecycle redesign rather than a fix to this defect. Flagging it explicitly rather than widening this PR.

[P1] Branch is dirty against current main - cleared. Rebased onto 1623683f47. Conflicts were in session-accessor.sqlite-transcript-watermark.ts, session-accessor.sqlite-message-cut.ts (+ its test), and managed-image-attachments.ts, each resolved toward keeping both behaviors:

  • watermark: kept main's withOpenClawAgentDatabaseReadOnly and throwOnMissingTable from perf(sessions): avoid database maintenance during reads #128631, applying this branch's atomic generation-and-sequence pair inside it rather than replacing it.
  • managed-image-attachments: kept main's archive-revision cache helpers, replacing only the cache key.
  • The retention snapshot reader now uses main's canonical projectSqliteHistoryEvents; refactor: simplify transcript reads and recovery state #135392 had removed the helpers this branch called, so the retained index was silently empty after the rebase. Caught by the exact-head runtime proof, not by the suites.

Scope reduction. The earlier revision also routed listSessionBranches and validateBranchTip through the new shared branch-tip selector. On current main that changes which rows count as branches and fails the large-shared-graph assertion added by #123541 (expected ... to have a length of 1362 but got 2), because the shared selector excludes side appends that main lists as branches. Retention does not depend on it, so session-accessor.sqlite-message-cut.ts and its test are dropped from this PR and #123541 is left intact. The PR is now 12 files instead of 14.

Not superseded. #119764 (merged) covers uncommitted generated media while a session run is live, a liveness dimension, and its hasActiveSessionRun guard is preserved here. #128033 covers attachments.ttlHours deleting inbound media in src/media/store.ts, a different store and a time-based policy. Current main still builds the managed-media cleanup index from the active projection only, so this retention surface is still unfixed; the before/after trace in the body reproduces the loss on 1623683f47.

Proof in the body is regenerated against this exact head: on pristine main the rewind sweep deletes the inactive-branch record and its bytes and the restored branch answers 404; with this patch the same sweep retains, the restored branch serves the bytes with status 200, and media referenced by no branch is still deleted.

@clawsweeper clawsweeper Bot added P1 High-priority user-facing bug, regression, or broken workflow. merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. and removed P0 Emergency: data loss, security bypass, crash loop, or unusable core runtime. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. labels Sep 2, 2026
@openclaw-barnacle openclaw-barnacle Bot removed the stale Marked as stale due to inactivity label Sep 3, 2026
@openclaw-barnacle

Copy link
Copy Markdown

This assigned pull request has been automatically marked as stale after being open for 27 days.
Please add updates or it will be closed.

@yetval

yetval commented Sep 6, 2026

Copy link
Copy Markdown
Contributor Author

Closing this while it sits assigned, stale, and conflicting.

The defect is unchanged on current main (c44cca40ee8): cleanupManagedOutgoingMediaRecords still decides deletion from the active/restorable attachment index built at managed-image-attachments.ts:1160, and treats absence from that projection as proof the media is orphaned. It is now tracked in #139670, which carries the root cause, the scope boundary against #119090 and #124047, and the remaining atomicity limit noted in this PR.

@vincentkoc you are the assignee here. The branch fix/managed-media-branch-retention is preserved. Given the XL size and the conflicts, rebuilding against a current base is probably cheaper than reviving it, but say so and I will rebase and reopen.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

gateway Gateway runtime merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. P1 High-priority user-facing bug, regression, or broken workflow. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. size: XL stale Marked as stale due to inactivity 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.

2 participants