Skip to content

fix(media): fail closed when managed-media cleanup cannot read the session store - #119260

Closed
wangmiao0668000666 wants to merge 4 commits into
openclaw:mainfrom
wangmiao0668000666:fix/managed-media-cleanup-unavailable-store
Closed

wangmiao0668000666 wants to merge 4 commits into
openclaw:mainfrom
wangmiao0668000666:fix/managed-media-cleanup-unavailable-store

Conversation

@wangmiao0668000666

@wangmiao0668000666 wangmiao0668000666 commented Aug 4, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Fixes #119090 (P0 data loss). Managed outgoing media cleanup deletes a session's generated media permanently when the owning SQLite session store is unreadable (permissions, I/O error, corrupt/locked database). The transcript survives with dead URLs; the originals and their SQLite records are gone with no archive or recovery path.

The sweep is reachable from an ordinary chat.history read.

Why This Change Was Made

Root cause: loadGatewaySessionLookupStoreUncached swallows any session-store read failure into {}. Cleanup then treats the missing session entry as "unreferenced" and force-removes the managed-media originals plus their records — an unreadable store is misread as proof of orphanhood.

This follows the ClawSweeper best-fix recommendation for #119090: only the destructive cleanup path (strictStore) translates store-read failures into the unavailable/retain outcome. Non-strict artifact and HTTP readers keep their pre-existing error contract: canonical-key migration errors still surface openclaw doctor --fix recovery guidance instead of degrading to an opaque 404.

User Impact

Before: a single chat.history read after any store read failure permanently deletes generated images/audio/video for that session, with surviving transcript URLs returning 404 and no recovery path.

After: an unreadable session store is treated as unknown retention state. Cleanup retains the records and backing files; a later sweep on a healthy store decides. Artifact/HTTP reads keep surfacing canonical migration errors with their recovery guidance.

Evidence

Real behavior proof: isolated gateway chat.history run (exact head, built from source)

Gateway built from this branch (pnpm build), run with an isolated OPENCLAW_STATE_DIR, token auth, real SQLite state. A managed media record + original file were seeded, then openclaw gateway call chat.history --params '{"sessionKey":"agent:main:main"}' was issued over the real WebSocket RPC (the operator path that schedules the cleanup sweep).

A/B result:

  • Healthy store (control): chat.history → sweep ran → original file deleted and record row removed (records table empty afterwards). This proves the sweep actually executes on this path and would have deleted the media.
  • Unreadable store (agent DB corrupted; gateway log shows database disk image is malformed): chat.history returned 200 with empty history → sweep ran → media file and record retained. A later sweep on a healthy store can decide.

Regression coverage (real SQLite boundary, no session-utils mock)

Test file: src/gateway/managed-image-attachments.unavailable-store.test.ts

  • retains a record when the session store is unreadable (chmod 000)
  • surfaces canonical migration errors on the artifact read path instead of a 404 — red on the previous head (returned null); green now: rejects with the migration-required error carrying openclaw doctor --fix guidance
  • retains managed media when the session store needs canonical-key repair — duplicate canonical-key rows make cleanup retain instead of delete
  • deletes an unreferenced record when the session store is healthy (control)

Test file: src/gateway/managed-image-attachments.test.ts

  • Updated the ticket/HTTP test to assert the restored contract: an escaping store-read error propagates to the caller; no ticket is minted and no media is served.

Test output (exact head)

src/gateway/managed-image-attachments.test.ts                     76 passed
src/gateway/managed-image-attachments.unavailable-store.test.ts    4 passed
src/gateway/session-utils.test.ts                                160 passed
src/gateway/sessions-history-http.test.ts                         72 passed (incl. the 409 migration_required contract)

@openclaw-barnacle openclaw-barnacle Bot added gateway Gateway runtime size: M labels Aug 4, 2026
@openclaw-barnacle openclaw-barnacle Bot closed this Aug 4, 2026
@openclaw-barnacle openclaw-barnacle Bot reopened this Aug 4, 2026
@clawsweeper clawsweeper Bot added 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. P0 Emergency: data loss, security bypass, crash loop, or unusable core runtime. labels Aug 4, 2026
@clawsweeper

clawsweeper Bot commented Aug 4, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs real behavior proof before merge. Reviewed August 5, 2026, 3:38 AM ET / 07:38 UTC.

ClawSweeper review

What this changes

The PR makes managed-media cleanup retain generated files and durable records when a session-store read is unavailable instead of treating it as proof that media is unreferenced.

Merge readiness

⛔ Blocked until stronger real behavior proof is added - 8 items remain

This PR improves configured-agent store failures but still permits permanent media deletion when a retired or unconfigured agent’s fixed/shared session store is unreadable; the strict read is never reached on that path.

Priority: P0
Reviewed head: 1886d7780540a0fbd1dbe3b4eca6446d316160f3

Review scores

Measure Result What it means
Overall readiness 🧂 unranked krab (1/6) The PR has useful exact-head evidence for one store shape but retains a high-confidence P0 data-loss path.
Proof confidence 🦐 gold shrimp (3/6) Needs stronger real behavior proof before merge: The final-head terminal transcript usefully proves configured-main table-missing handling, but it does not prove the known retired/unconfigured fixed/shared-store path; add redacted after-fix evidence for that owner boundary. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.
Patch quality 🧂 unranked krab (1/6) 1 actionable review finding remain.

Verification

Check Result Evidence
Real behavior Needs proof Needs stronger real behavior proof before merge: The final-head terminal transcript usefully proves configured-main table-missing handling, but it does not prove the known retired/unconfigured fixed/shared-store path; add redacted after-fix evidence for that owner boundary. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.
Evidence reviewed 6 items Discovery loses unavailable fixed/shared stores: Current main catches fixed/shared-store read failures and returns no target, collapsing unavailable state into absence before the media cleanup can distinguish it.
Strict mode is bypassed for retired owners: At the PR head, unconfigured agents with no discovered candidate return an empty store before the newly added strict loader option can run.
Empty lookup remains deletion-eligible: The PR head maps a missing session entry to an empty index, whose lookup resolves false; cleanup then deletes the original and durable record.
Findings 1 actionable finding [P0] Preserve unavailable retired stores before candidate discovery
Security None None.

How this fits together

Gateway chat.history schedules cleanup of generated outgoing media. Cleanup consults the agent session store and transcript references before either retaining media or permanently removing its file and SQLite record.

flowchart LR
A[Chat history request] --> B[Managed media cleanup]
B --> C[Session-store discovery]
C --> D{Store availability known?}
D -->|reference proven absent| E[Delete orphan media]
D -->|unavailable or unknown| F[Retain media and record]
E --> G[Managed media storage]
F --> G
Loading

Before merge

  • Add real behavior proof - Needs stronger real behavior proof before merge: The final-head terminal transcript usefully proves configured-main table-missing handling, but it does not prove the known retired/unconfigured fixed/shared-store path; add redacted after-fix evidence for that owner boundary. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.
  • Preserve unavailable retired stores before candidate discovery (P0) - For retired or unconfigured fixed/shared stores, discovery catches a failed read in targets.ts and returns no candidates, so this new strict option never executes; cleanup then treats the media as unreferenced and deletes it. Carry typed unavailable state through discovery and add a real SQLite retired-owner regression that retains both the row and original after restoration. This was visible at the prior reviewed head and is raised late.
  • Resolve merge risk (P1) - Merging still allows a chat.history cleanup to permanently delete generated media and its durable row when retired or unconfigured fixed/shared-store discovery fails.
  • Resolve merge risk (P1) - Open fix(media): keep the ttl sweep out of the managed outgoing tree #119127 may carry the broader repair, but its current head and exact-head proof were not available for supersession verification.
  • Complete next step (P2) - A focused owner-boundary repair and regression are concrete, but the open related PR must be checked at its exact current head before duplicating work.
  • Improve patch quality - Carry typed unavailable state from session-target discovery into cleanup.
  • Improve patch quality - Add a real-SQLite retired/unconfigured fixed/shared-store regression retaining the file and durable row after the store recovers.
  • Improve patch quality - Provide redacted after-fix operator-path evidence for that scenario.

Findings

  • [P0] Preserve unavailable retired stores before candidate discovery — src/gateway/session-utils-store-lookup.ts:272
Agent review details

Security

None.

PR surface

Source +108, Tests +292. Total +400 across 6 files.

View PR surface stats
Area Files Added Removed Net
Source 4 139 31 +108
Tests 2 293 1 +292
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 6 432 32 +400

Review metrics

Metric Value Why it matters
Production versus test delta production +108/-31; tests +293/-1 The added production surface is intended to establish a session-state ownership boundary, but it presently leaves one destructive ownership path unresolved.

Stored data model

Persistent data-model change detected: serialized state: src/config/sessions/session-accessor.sqlite-entry.ts, serialized state: src/gateway/session-utils-store-lookup.ts, serialized state: src/gateway/session-utils-store.ts, unknown-data-model-change: src/gateway/session-utils-store-lookup.ts. Confirm migration or upgrade compatibility proof before merge.

Merge-risk options

Maintainer options:

  1. Repair availability at the discovery boundary (recommended)
    Carry unavailable fixed/shared-store results out of target discovery and add a retired/unconfigured real-SQLite regression before merge.

Technical review

Best possible solution:

Preserve typed session-store availability at discovery, propagate it to destructive cleanup, and retain media unless absence is affirmatively proven; consolidate with the exact-current owner-boundary work in #119127 if it verifies cleanly.

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

Yes—source-reproducible: make a retired or unconfigured fixed/shared SQLite store unreadable, then run the history-triggered cleanup; discovery returns an empty store and deletion follows. This read-only review did not execute that scenario locally.

Is this the best way to solve the issue?

No. The strict accessor is a downstream mitigation; typed availability must survive target discovery so destructive cleanup never confuses an unreadable owner with an absent one.

Full review comments:

  • [P0] Preserve unavailable retired stores before candidate discovery — src/gateway/session-utils-store-lookup.ts:272
    For retired or unconfigured fixed/shared stores, discovery catches a failed read in targets.ts and returns no candidates, so this new strict option never executes; cleanup then treats the media as unreferenced and deletes it. Carry typed unavailable state through discovery and add a real SQLite retired-owner regression that retains both the row and original after restoration. This was visible at the prior reviewed head and is raised late.
    Confidence: 0.98
    Late finding: first raised on code an earlier review cycle already covered.

Overall correctness: patch is incorrect
Overall confidence: 0.98

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning high; reviewed against 05a03c66fe76.

Labels

Label changes:

  • add rating: 🧂 unranked krab: Overall readiness is 🧂 unranked krab; proof is 🦐 gold shrimp and patch quality is 🧂 unranked krab.
  • remove rating: 🦐 gold shrimp: Current PR rating is rating: 🧂 unranked krab, so this older rating label is no longer current.

Label justifications:

  • P0: The remaining path can permanently delete generated media and its SQLite record after an ordinary history read.
  • merge-risk: 🚨 session-state: The patch changes how persisted session-store availability controls deletion of session-linked media.
  • rating: 🧂 unranked krab: Overall readiness is 🧂 unranked krab; proof is 🦐 gold shrimp and patch quality is 🧂 unranked krab.
  • status: 📣 needs proof: The PR needs real behavior proof before ClawSweeper can clear the contributor ask. Needs stronger real behavior proof before merge: The final-head terminal transcript usefully proves configured-main table-missing handling, but it does not prove the known retired/unconfigured fixed/shared-store path; add redacted after-fix evidence for that owner boundary. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.

Evidence

Acceptance criteria:

  • [P1] node scripts/run-vitest.mjs src/gateway/managed-image-attachments.unavailable-store.test.ts src/gateway/managed-image-attachments.test.ts src/gateway/session-utils.test.ts src/config/sessions/targets.test.ts.
  • [P1] Run a redacted isolated Gateway chat.history scenario against the retired/unconfigured fixed/shared unavailable store and verify the media file, durable row, and restored session remain available.

What I checked:

Likely related people:

  • Jason (Json): The locally available grafted history attributes the current session-target, lookup, and managed-media paths to this commit; older provenance is unavailable in the shallow history. (role: recent current-main area contributor; confidence: medium; commits: ab7b3ffd1feb; files: src/config/sessions/targets.ts, src/gateway/session-utils-store-lookup.ts, src/gateway/managed-image-attachments.ts)
  • steipete: The PR discussion contains the same retired/fixed-store P0 analysis and identifies the broader owner-boundary repair shape. (role: direct area reviewer; confidence: high; files: src/config/sessions/targets.ts, src/gateway/session-utils-store-lookup.ts, src/gateway/managed-image-attachments.ts)

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 (11 earlier review cycles; latest 8 shown)
  • reviewed 2026-08-04T16:17:27.430Z sha f5ae7754251829f9bf38d02f8367551ef2d2d26e :: needs real behavior proof before merge. :: none
  • reviewed 2026-08-04T17:09:43.455Z sha 6fdd20e :: needs real behavior proof before merge. :: [P2] Preserve canonical-store errors outside cleanup
  • reviewed 2026-08-04T18:20:56.020Z sha 6fdd20e :: needs real behavior proof before merge. :: none
  • reviewed 2026-08-05T01:10:15.730Z sha 6fdd20e :: needs real behavior proof before merge. :: [P2] Preserve canonical-store errors outside cleanup
  • reviewed 2026-08-05T04:15:52.318Z sha 332eb20 :: needs real behavior proof before merge. :: none
  • reviewed 2026-08-05T05:04:56.972Z sha 332eb20 :: needs changes before merge. :: [P0] Preserve non-throwing unavailable store results
  • reviewed 2026-08-05T06:24:17.514Z sha 1886d77 :: needs real behavior proof before merge. :: none
  • reviewed 2026-08-05T06:36:27.892Z sha 1886d77 :: needs real behavior proof before merge. :: none

@clawsweeper clawsweeper Bot added rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. merge-risk: 🚨 security-boundary 🚨 May affect sandboxing, authorization, credentials, or sensitive data. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. and removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. labels Aug 4, 2026
@wangmiao0668000666

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

@clawsweeper

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

@clawsweeper clawsweeper Bot removed merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. merge-risk: 🚨 security-boundary 🚨 May affect sandboxing, authorization, credentials, or sensitive data. labels Aug 4, 2026
@wangmiao0668000666
wangmiao0668000666 force-pushed the fix/managed-media-cleanup-unavailable-store branch from f5ae775 to 6fdd20e Compare August 4, 2026 17:02
@wangmiao0668000666

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

@clawsweeper

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

@clawsweeper clawsweeper Bot added rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. and removed rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. labels Aug 4, 2026
@wangmiao0668000666

Copy link
Copy Markdown
Contributor Author

Real runtime evidence added

Boundary-level test with real SQLite (exact head: $(git rev-parse HEAD))

Test file: `src/gateway/managed-image-attachments.unavailable-store.test.ts`

Terminal output from running the test:

Test Files  1 passed (1)
Tests       2 passed (2)
Duration    28.57s

✓ retains managed media when the session store is unreadable (chmod 000)
✓ retains managed media records when the session store is unreadable

What this proves:

  1. Creates real SQLite session store with seeded session + managed media
  2. Makes store unreadable (chmod 000) - simulating real permissions/I/O failure
  3. Runs exact-head cleanup code path (same path used by chat.history)
  4. Asserts media files and records are RETAINED (not deleted)

This is the same destructive cleanup code path that Gateway uses in production. The test proves the repaired fail-closed behavior at the real SQLite boundary with exact-head code.

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Aug 5, 2026

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Command router queued. I will update this comment with the next step.

@wangmiao0668000666

Copy link
Copy Markdown
Contributor Author

Request for clarification on evidence format

@clawsweeper The PR body already contains:

  • Test file path: src/gateway/managed-image-attachments.unavailable-store.test.ts
  • Test terminal output: "Test Files 1 passed (1), Tests 2 passed (2), Duration 28.57s"
  • What the test proves: real SQLite store made unreadable, cleanup retains media

The existing evidence is from a boundary-level vitest test that uses real DatabaseSync SQLite, which is the same pattern used elsewhere in the codebase for migration evidence (e.g., src/state/openclaw-agent-db.test.ts).

Question: What specific evidence format is required?

  1. Screenshot of terminal running the test? - Would need to attach image to PR
  2. GitHub Actions CI log link? - Would need to run test in CI and capture log URL
  3. Video recording? - Would need screen capture setup
  4. Gist/pastebin of full test output? - Can create external artifact

The test output I provided in the comment above is copy-pasted terminal text. Is the issue that it needs to be:

  • Attached as a file artifact?
  • Linked from an external service (Gist, GitHub Actions log)?
  • Formatted differently?

Please clarify the exact evidence format expected, as "inspectable exact-head runtime artifact" is ambiguous.

@clawsweeper

clawsweeper Bot commented Aug 5, 2026

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Command router queued. I will update this comment with the next step.

@steipete

steipete commented Aug 5, 2026 •

Copy link
Copy Markdown
Contributor

[P0] Still present on current head 1886d7780540a0fbd1dbe3b4eca6446d316160f3: unreadable retired fixed/shared session stores permanently lose recoverable original attachments

Previous configured-agent table-missing and schema-missing: fixed. The contributor correctly updated src/config/sessions/session-accessor.sqlite-entry.ts:200-221 to fail closed for both non-database-missing owner results when strictStoreAvailable is requested, and src/gateway/session-utils-store-lookup.ts:185-200 now passes that strict option. The real DROP TABLE session_nodes regression at src/gateway/managed-image-attachments.unavailable-store.test.ts:148-166 confirms the configured-agent table case. Those earlier configured-agent findings are resolved; thank you for addressing them.

One independent P0 remains: every current test hard-codes configured agent main (src/gateway/managed-image-attachments.unavailable-store.test.ts:99-105), bypassing the retired/unconfigured agent discovery boundary:

  1. src/config/sessions/targets.ts:445-465 collapses an unavailable fixed/shared session.store or caught read failure/EACCES into [].
  2. src/gateway/session-utils-store-lookup.ts:249-265 uses only discovered targets for an unconfigured/retired owner and returns { store: {}, match: undefined } before the newly strict accessor at :192-199 can ever run.
  3. src/gateway/managed-image-attachments.ts:889-913 misclassifies that unknown, recoverable session as an empty attachment index; :651-670 consequently unlinks the original and deletes its durable managed-media row.

Observed production end-to-end reproduction, real SQLite + real file, no mocks:

{"discoveredBefore":1,"discoveredAfter":0,"gatewayEntry":null,"before":{"fileExists":true,"recordExists":true},"cleanup":{"deletedRecordCount":1,"deletedFileCount":1,"retainedCount":0},"after":{"fileExists":false,"recordExists":false},"recoveredSessionId":"recoverable-retired-session"}

Restoring the temporarily unreadable retired store recovers its owning session after both the original and its durable row have already been permanently deleted.

Canonical owner-boundary fix already exists: neighboring #119127 at exact head 61f4a00347ddff47190b0100be44a9dd6df5f7c4 preserves typed fixed-store availability in src/config/sessions/targets.ts:409-475, checks it before lossy media/session lookup in src/gateway/managed-image-attachments.ts:873-891, and allows destructive deletion only for an explicitly proven missing reference at :652-657. Its real retired fixed-store regression is src/gateway/managed-image-attachments.test.ts:2021-2053.

Required before landing: adopt that typed fixed/shared-store discovery and fail-closed media-owner contract; add a real retired/unconfigured fixed/shared SQLite unreadability regression that asserts both the original attachment and durable media row survive, with the owning session recoverable after the store is restored.

@clawsweeper clawsweeper Bot added proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. and removed 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. labels Aug 5, 2026
@wangmiao0668000666

Copy link
Copy Markdown
Contributor Author

P0 finding fixed: non-throwing table-missing stores now fail closed (head 1886d77)

The review was right: withOpenClawAgentDatabaseReadOnly reports a present-but-unusable store (missing session_nodes table, missing schema) as a typed non-throwing { found: false, reason } result, which the accessor flattened to an absent entry — so the strict cleanup path still deleted media for that failure mode.

Fix

  • src/config/sessions/session-accessor.sqlite-entry.ts: loadExactSqliteSessionEntryReadOnly accepts { strictStoreAvailable: true } and throws on found: false for table-missing / schema-missing. database-missing stays an absence because discovery legitimately probes candidate store paths that may not exist yet.
  • src/gateway/session-utils-store-lookup.ts: the store lookup threads strict into the exact-read seam, so the unavailable outcome propagates to the strict cleanup catch and becomes retain. Non-strict artifact/HTTP reads are unchanged (still an absent entry, no throw).

Regression coverage

  • New real-SQLite test retains a record when the session store is missing its session tables (src/gateway/managed-image-attachments.unavailable-store.test.ts): seeds a real session store, drops session_nodes, runs the real cleanup — media retained. Verified red on the previous head (record was deleted), green now.

Test output (exact head, node scripts/run-vitest.mjs)

src/gateway/managed-image-attachments.unavailable-store.test.ts    5 passed
src/gateway/managed-image-attachments.test.ts                     76 passed
src/gateway/session-utils.test.ts                                160 passed
src/gateway/sessions-history-http.test.ts                         72 passed
src/config/sessions/session-accessor.test.ts + .readonly.test.ts   all passed
src/commands/doctor-session-canonical-keys.test.ts                 all passed

@clawsweeper re-review

@clawsweeper

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

@clawsweeper clawsweeper Bot added 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. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. and removed proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. labels Aug 5, 2026
@wangmiao0668000666

Copy link
Copy Markdown
Contributor Author

Operator-path proof for the table-missing repair (exact head 1886d77)

Same live-Gateway setup as the earlier accepted transcript (exact-head pnpm build, isolated OPENCLAW_STATE_DIR, dedicated session.store file), now covering the final non-throwing failure mode: the store file opens fine but its session_nodes table is gone, which the read-only owner reports as a non-throwing table-missing result. The table is dropped live while the Gateway runs; the scheduled chat.history cleanup then faces the missing-table store.

== build provenance: dist was built from the PR head ==
$ cat dist/build-info.json
{
  "version": "2026.7.2",
  "commit": "1886d7780540a0fbd1dbe3b4eca6446d316160f3",
  "builtAt": "2026-08-05T07:03:57.127Z"
}

== start gateway (healthy; creates + registers the session store) ==
2026-08-05T15:27:57.865+08:00 [gateway] ready
== seed managed media record + original file ==
$ node /tmp/seed-managed-media.cjs /tmp/openclaw-proof-media7 cccccccc-3333-4333-8333-cccccccccccc
seeded attachment=cccccccc-3333-4333-8333-cccccccccccc file=/tmp/openclaw-proof-media7/media/outgoing/originals/cccccccc-3333-4333-8333-cccccccccccc-cat-full.png

== CONTROL: healthy store, chat.history sweep deletes the unreferenced media ==
$ node dist/index.js gateway call chat.history --params {"sessionKey":"agent:main:main"} ...
{
  "sessionKey": "agent:main:main",
  "messages": [],
  "hasMore": false,
  "totalMessages": 0,
(chat.history succeeded on attempt 3; response body trimmed)

-- after sweep (healthy store): file + record DELETED --
$ ls -la /tmp/openclaw-proof-media7/media/outgoing/originals/
总用量 0
drwxrwxr-x 2 0668000666 0668000666  6 8月   5 15:29 .
drwxrwxr-x 3 0668000666 0668000666 23 8月   5 15:28 ..

$ node -e const{DatabaseSync}=require('node:sqlite');const db=new DatabaseSync('/tmp/openclaw-proof-media7/state/openclaw.sqlite',{readOnly:true});console.log('records:',db.prepare('SELECT attachment_id FROM managed_outgoing_image_records').all());db.close();
records: []

== TABLE-MISSING STORE: re-seed, start gateway, drop session_nodes live ==
$ node /tmp/seed-managed-media.cjs /tmp/openclaw-proof-media7 dddddddd-4444-4444-8444-dddddddddddd
seeded attachment=dddddddd-4444-4444-8444-dddddddddddd file=/tmp/openclaw-proof-media7/media/outgoing/originals/dddddddd-4444-4444-8444-dddddddddddd-cat-full.png

$ node -e const{DatabaseSync}=require('node:sqlite');const db=new DatabaseSync('/tmp/openclaw-proof-media7/store/openclaw-agent.sqlite');db.exec('DROP TABLE session_nodes');console.log('session_nodes dropped from the live store; tables left:',db.prepare("SELECT name FROM sqlite_schema WHERE type='table' AND name LIKE 'session%'").all().map(r=>r.name));db.close();
session_nodes dropped from the live store; tables left: [
  'session_key_contract',
  'session_windows',
  'session_conversations',
  'session_members',
  'session_suggestions',
  'session_transcript_index_state',
  'session_transcript_active_events',
  'session_transcript_fts',
  'session_transcript_fts_data',
  'session_transcript_fts_idx',
  'session_transcript_fts_content',
  'session_transcript_fts_docsize',
  'session_transcript_fts_config'
]

-- probe: store opens but session_nodes is gone (non-throwing table-missing outcome) --
$ node -e const{DatabaseSync}=require('node:sqlite');const db=new DatabaseSync('/tmp/openclaw-proof-media7/store/openclaw-agent.sqlite',{readOnly:true});try{db.prepare('SELECT count(*) FROM session_nodes').all();}catch(e){console.log('session_nodes read:',e.message);}db.close();
session_nodes read: no such table: session_nodes

$ node dist/index.js gateway call chat.history --params {"sessionKey":"agent:main:main"} ...
{
  "sessionKey": "agent:main:main",
  "messages": [],
  "hasMore": false,
  "totalMessages": 0,
(chat.history succeeded on attempt 2; response body trimmed)

-- after sweep (table-missing store): file + record RETAINED --
$ ls -la /tmp/openclaw-proof-media7/media/outgoing/originals/
总用量 4
drwxrwxr-x 2 0668000666 0668000666 63 8月   5 15:29 .
drwxrwxr-x 3 0668000666 0668000666 23 8月   5 15:28 ..
-rw-rw-r-- 1 0668000666 0668000666 14 8月   5 15:29 dddddddd-4444-4444-8444-dddddddddddd-cat-full.png

$ node -e const{DatabaseSync}=require('node:sqlite');const db=new DatabaseSync('/tmp/openclaw-proof-media7/state/openclaw.sqlite',{readOnly:true});console.log('records:',db.prepare('SELECT attachment_id FROM managed_outgoing_image_records').all());db.close();
records: [
  [Object: null prototype] {
    attachment_id: 'dddddddd-4444-4444-8444-dddddddddddd'
  }
]

== transcript done ==

Healthy store → the same chat.history sweep deletes the unreferenced media (control). Store with session_nodes dropped → chat.history still answers (200, empty history) and the sweep retains the file and record. Both outcomes at the exact reviewed head.

@clawsweeper re-review

@clawsweeper clawsweeper Bot added rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. and removed rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. labels Aug 5, 2026
@wangmiao0668000666

Copy link
Copy Markdown
Contributor Author

Closing as superseded by #119127.

The P0 data-loss bug (#119090) is still real on current main, but #119127 now carries the correct owner-boundary repair: typed session-store availability (SessionStoreTargetsReadResult) survives src/config/sessions/targets.ts discovery, and the managed-media reaper retains records and originals whenever a store — configured or retired/unconfigured fixed/shared — is unreadable. That covers exactly the gap ClawSweeper's P0 finding identified in this PR's strictStore approach, which only protected configured-agent stores.

Landing both would also conflict over managed-image-attachments.ts / targets.ts / session-accessor.sqlite-entry.ts while this PR would still leave the retired-store deletion path open.

Issue #119090 stays open and is tracked by #119127. If #119127 stalls or drops the availability work, this branch can be reopened and reworked to carry typed availability through discovery instead of the downstream strict loader.

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

Labels

gateway Gateway runtime merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. P0 Emergency: data loss, security bypass, crash loop, or unusable core runtime. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. size: M status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: managed media cleanup fails open on an unreadable session store and permanently deletes a session's generated media

2 participants