[PR #5620] [MERGED] fix(storage): answer the gallery reference check without leasing chat_images #6853

Closed
opened 2026-10-23 04:14:19 +07:00 by bsakaguchi · 0 comments
Owner

📋 Pull Request Information

Original PR: https://github.com/Pasta-Devs/Marinara-Engine/pull/5620
Author: @kolacheee
Created: 8/29/2026
Status: ✅ Merged
Merged: 8/29/2026
Merged by: @kolacheee

Base: staging ← Head: fix/5613-reference-check-without-lease


📝 Commits (6)

  • c1f11f5 fix(storage): answer the gallery reference check without leasing chat_images
  • 2a934cd style: format the gallery-file-lifecycle regression
  • 1afac0c docs: add changelog entries for the residual-lease fixes (#5611/#5612/#5613)
  • 7488bd7 fix(storage): close the reference-check gaps found by adversarial review
  • 2c452c9 refactor(storage): delete the now-dead unscoped listByFilePath
  • 5524fc7 fix(storage): gate negative reference answers on stable residency

📊 Changes

5 files changed (+580 additions, -14 deletions)

View changed files

📝 CHANGELOG.md (+3 -0)
📝 packages/server/src/db/file-backed-store.ts (+53 -2)
📝 packages/server/src/services/image/gallery-file-lifecycle.ts (+237 -8)
📝 packages/server/src/services/storage/gallery.storage.ts (+0 -4)
➕ scripts/regressions/gallery-file-lifecycle.regression.ts (+287 -0)

📄 Description

Closes #5613. The last of the three residual-lease findings from the #5592 close-out audit (#5611 → #5614, #5612 → #5616).

Why

galleryFileHasReferences asks a question that is cross-chat by design — "does any chat still reference this physical file before we unlink it?" — so its chat_images query could not carry a chatId and permanently converted the whole table to fully resident on the first image deletion anywhere in the app (chat gallery, character/persona images, global gallery, cascade deletion). On any install where the user had ever deleted an image, MARINARA_MAX_RESIDENT_CHATS silently stopped bounding chat_images for the rest of the process. A conjunct can't fix this one — scoping the query to one chat would delete files other chats still show.

What changed

The chat_images half of the check (the other three tables are eager and unchanged) now answers in layers, guided by the failure asymmetry — a false "referenced" merely keeps an orphan file on disk, while a false "unreferenced" would delete a file another chat still displays:

  1. Every non-resident unit's shard file is read directly off disk — sound because a non-resident unit can hold no unflushed state (#5616's invariant: writes force residency first, eviction only runs after a successful flush). Any row whose filePath (or dbName-form file_path) matches is a reference, regardless of which chat owns it — so cross-chat references, stray rows included, are found without loading anyone. Peek results are memoized across calls keyed on the table's write generation plus the resident set (same generation + same residency ⇒ no shard file can have changed), because the deletion flows call this once or twice per image and would otherwise pay a full synchronous shard-directory read each time.
  2. A shard the peek cannot interpret (unreadable, non-array root, malformed row, lone .bak from an interrupted flush) is handed to the real loader by key — decoded from the filename when the decode round-trips through the encoder, or attributed by matching the encoding over the eager chats table when the filename is the undecodable %h hash form — loading exactly that unit through the full recovery ladder and short-circuiting on a hit. decodeShardKey is the new best-effort inverse of the filename encoding (the store itself never decodes — rows carry their own keys).
  3. Everything resident is answered last by one scan over the store's in-memory rows via a new getResidentLazyRows() accessor — not per-unit queries. This is what makes memory authoritative in both directions (an unflushed new row counts; an unflushed delete does not resurrect through its stale shard file — load-bearing, since the delete flow checks within the flush debounce), covers rows no per-key query can express (null/absent/non-string chatId rows living in the pinned orphan unit), and, running last, makes mid-call interleavings safe: anything a concurrent request writes during this function's awaits lands in memory and is seen.
  4. Only a shard that is unreadable AND unattributable to any unit is assumed referenced — with a warning, and only after the rest of the sweep found nothing — the safe direction.

Eager mode and an already-leased table keep the original plain query, which is complete there and leases nothing new. The scan is sorted for cross-filesystem determinism and classifies directory entries with the store's own isShardDataFileName, so artifact files the store ignores can't disable cleanup.

Housekeeping: #5614 merged under this branch during review, so gallery.storage.ts's now-dead unscoped listByFilePath is deleted here too — the final unscoped chat_images query in the storage layer.

Regression

New suite gallery-file-lifecycle.regression.ts: a cross-chat reference found by peek with zero unit loads and zero lease (the headline — A/B-verified red pre-fix on exactly the lease assert), dbName-form rows, corrupt-shard and lone-.bak loader handoffs (each loading only its own unit), a malformed-row shard answering correctly while its repair handoff runs, a full-sweep miss loading nothing new, both memory-authority directions (unflushed insert counts / unflushed delete doesn't resurrect), the real unlinkGalleryFileIfUnreferenced flow deleting an unreferenced file and keeping a referenced one, and a control block proving the check still answers correctly when the table was leased by some other path. Self-skips under MARINARA_EAGER_STORAGE.

An adversarial verification pass (three independent reviewers: false-negative construction, decode/scan mechanics, caller integration + suite validity) ran before opening this PR and caught six real problems in the first draft — including a reproduced false negative in the catastrophic direction (orphan-unit rows with null/absent/non-string chatId were invisible to the per-unit query loop, and their files were physically unlinked while live rows referenced them). All six are fixed and pinned by the suite; the getResidentLazyRows memory scan is the structural fix for the worst one. The reviewers also fuzz-tested decodeShardKey round-trip fidelity (10,047 keys: exact for every well-formed id; the only lossy classes are encoder-side and pre-existing) and verified the load-bearing store invariants by execution. Full findings summarized in a comment below.

Validation done

  • tsc --noEmit all packages ✅
  • Prettier on all changed files ✅ (plain — the tree is LF now, thanks #5617)
  • Regression lanes: gallery-file-lifecycle (lazy + eager-skip) ✅, gallery-recovery ✅, lazy-chat-units ✅, message-sharding ✅

Manual verification

  • Delete a chat gallery image on an install with MARINARA_MAX_RESIDENT_CHATS set and confirm the log never prints Lazy table chat_images is now fully resident
  • Delete an image whose file is shared with a branched chat and confirm the file survives; delete the last reference and confirm the file is removed from data/gallery/
  • Delete a character image and a persona image (the same check runs on those paths)

Summary by CodeRabbit

  • Bug Fixes

    • Improved gallery image deletion and recovery of orphaned files.
    • Gallery references are checked reliably without loading entire chat histories into memory.
    • Startup scanning now detects gallery images directly from stored data, improving recovery after interrupted operations.
    • Corrected chat ownership handling for Game mode, swipes, checkpoints, and gallery storage.
    • Prevented unrelated chats from affecting gallery image retention or deletion.
  • Tests

    • Added regression coverage for shared images, malformed records, recovery scenarios, and safe file retention or deletion.

🔄 This issue represents a GitHub Pull Request. It cannot be merged through Gitea due to API limitations.

## 📋 Pull Request Information **Original PR:** https://github.com/Pasta-Devs/Marinara-Engine/pull/5620 **Author:** [@kolacheee](https://github.com/kolacheee) **Created:** 8/29/2026 **Status:** ✅ Merged **Merged:** 8/29/2026 **Merged by:** [@kolacheee](https://github.com/kolacheee) **Base:** `staging` ← **Head:** `fix/5613-reference-check-without-lease` --- ### 📝 Commits (6) - [`c1f11f5`](https://github.com/Pasta-Devs/Marinara-Engine/commit/c1f11f5283a130fbfa7c3f185b70a9cb5491523f) fix(storage): answer the gallery reference check without leasing chat_images - [`2a934cd`](https://github.com/Pasta-Devs/Marinara-Engine/commit/2a934cd8f114bcb78817bb1bbde630c783cacacb) style: format the gallery-file-lifecycle regression - [`1afac0c`](https://github.com/Pasta-Devs/Marinara-Engine/commit/1afac0cdd64abe1f7835f49b47aa22722a41993c) docs: add changelog entries for the residual-lease fixes (#5611/#5612/#5613) - [`7488bd7`](https://github.com/Pasta-Devs/Marinara-Engine/commit/7488bd7714b12efbe6f9abb1197df9c20bf46df2) fix(storage): close the reference-check gaps found by adversarial review - [`2c452c9`](https://github.com/Pasta-Devs/Marinara-Engine/commit/2c452c95c612de949c9f4c57fa260feb46f50e7d) refactor(storage): delete the now-dead unscoped listByFilePath - [`5524fc7`](https://github.com/Pasta-Devs/Marinara-Engine/commit/5524fc75c98056e7c5097778c9313d76880bf560) fix(storage): gate negative reference answers on stable residency ### 📊 Changes **5 files changed** (+580 additions, -14 deletions) <details> <summary>View changed files</summary> 📝 `CHANGELOG.md` (+3 -0) 📝 `packages/server/src/db/file-backed-store.ts` (+53 -2) 📝 `packages/server/src/services/image/gallery-file-lifecycle.ts` (+237 -8) 📝 `packages/server/src/services/storage/gallery.storage.ts` (+0 -4) ➕ `scripts/regressions/gallery-file-lifecycle.regression.ts` (+287 -0) </details> ### 📄 Description Closes #5613. The last of the three residual-lease findings from the #5592 close-out audit (#5611 → #5614, #5612 → #5616). ## Why `galleryFileHasReferences` asks a question that is cross-chat *by design* — "does **any** chat still reference this physical file before we unlink it?" — so its `chat_images` query could not carry a chatId and permanently converted the whole table to fully resident on the **first image deletion anywhere in the app** (chat gallery, character/persona images, global gallery, cascade deletion). On any install where the user had ever deleted an image, `MARINARA_MAX_RESIDENT_CHATS` silently stopped bounding `chat_images` for the rest of the process. A conjunct can't fix this one — scoping the query to one chat would delete files other chats still show. ## What changed The `chat_images` half of the check (the other three tables are eager and unchanged) now answers in layers, guided by the failure asymmetry — a false "referenced" merely keeps an orphan file on disk, while a false "unreferenced" would delete a file another chat still displays: 1. **Every non-resident unit's shard file is read directly off disk** — sound because a non-resident unit can hold no unflushed state (#5616's invariant: writes force residency first, eviction only runs after a successful flush). Any row whose `filePath` (or dbName-form `file_path`) matches is a reference, regardless of which chat owns it — so cross-chat references, stray rows included, are found without loading anyone. Peek results are **memoized across calls** keyed on the table's write generation plus the resident set (same generation + same residency ⇒ no shard file can have changed), because the deletion flows call this once or twice per image and would otherwise pay a full synchronous shard-directory read each time. 2. **A shard the peek cannot interpret** (unreadable, non-array root, malformed row, lone `.bak` from an interrupted flush) is handed to the real loader by key — decoded from the filename when the decode **round-trips through the encoder**, or attributed by matching the encoding over the eager `chats` table when the filename is the undecodable `%h` hash form — loading exactly that unit through the full recovery ladder and short-circuiting on a hit. `decodeShardKey` is the new best-effort inverse of the filename encoding (the store itself never decodes — rows carry their own keys). 3. **Everything resident is answered last by one scan over the store's in-memory rows** via a new `getResidentLazyRows()` accessor — not per-unit queries. This is what makes memory authoritative in *both* directions (an unflushed new row counts; an unflushed delete does not resurrect through its stale shard file — load-bearing, since the delete flow checks within the flush debounce), covers rows **no per-key query can express** (null/absent/non-string `chatId` rows living in the pinned orphan unit), and, running last, makes mid-call interleavings safe: anything a concurrent request writes during this function's awaits lands in memory and is seen. 4. **Only a shard that is unreadable AND unattributable to any unit** is assumed referenced — with a warning, and only after the rest of the sweep found nothing — the safe direction. Eager mode and an already-leased table keep the original plain query, which is complete there and leases nothing new. The scan is sorted for cross-filesystem determinism and classifies directory entries with the store's own `isShardDataFileName`, so artifact files the store ignores can't disable cleanup. Housekeeping: #5614 merged under this branch during review, so `gallery.storage.ts`'s now-dead unscoped `listByFilePath` is deleted here too — the final unscoped `chat_images` query in the storage layer. ## Regression New suite `gallery-file-lifecycle.regression.ts`: a cross-chat reference found by peek with **zero unit loads and zero lease** (the headline — A/B-verified red pre-fix on exactly the lease assert), dbName-form rows, corrupt-shard and lone-`.bak` loader handoffs (each loading only its own unit), a malformed-row shard answering correctly while its repair handoff runs, a full-sweep miss loading nothing new, both memory-authority directions (unflushed insert counts / unflushed delete doesn't resurrect), the real `unlinkGalleryFileIfUnreferenced` flow deleting an unreferenced file and keeping a referenced one, and a control block proving the check still answers correctly when the table was leased by some other path. Self-skips under `MARINARA_EAGER_STORAGE`. An adversarial verification pass (three independent reviewers: false-negative construction, decode/scan mechanics, caller integration + suite validity) ran before opening this PR and caught six real problems in the first draft — including a **reproduced false negative in the catastrophic direction** (orphan-unit rows with null/absent/non-string `chatId` were invisible to the per-unit query loop, and their files were physically unlinked while live rows referenced them). All six are fixed and pinned by the suite; the `getResidentLazyRows` memory scan is the structural fix for the worst one. The reviewers also fuzz-tested `decodeShardKey` round-trip fidelity (10,047 keys: exact for every well-formed id; the only lossy classes are encoder-side and pre-existing) and verified the load-bearing store invariants by execution. Full findings summarized in a comment below. ## Validation done - `tsc --noEmit` all packages ✅ - Prettier on all changed files ✅ (plain — the tree is LF now, thanks #5617) - Regression lanes: `gallery-file-lifecycle` (lazy + eager-skip) ✅, `gallery-recovery` ✅, `lazy-chat-units` ✅, `message-sharding` ✅ ## Manual verification - [ ] Delete a chat gallery image on an install with `MARINARA_MAX_RESIDENT_CHATS` set and confirm the log never prints `Lazy table chat_images is now fully resident` - [ ] Delete an image whose file is shared with a branched chat and confirm the file survives; delete the last reference and confirm the file is removed from `data/gallery/` - [ ] Delete a character image and a persona image (the same check runs on those paths) <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **Bug Fixes** * Improved gallery image deletion and recovery of orphaned files. * Gallery references are checked reliably without loading entire chat histories into memory. * Startup scanning now detects gallery images directly from stored data, improving recovery after interrupted operations. * Corrected chat ownership handling for Game mode, swipes, checkpoints, and gallery storage. * Prevented unrelated chats from affecting gallery image retention or deletion. * **Tests** * Added regression coverage for shared images, malformed records, recovery scenarios, and safe file retention or deletion. <!-- end of auto-generated comment: release notes by coderabbit.ai --> --- <sub>🔄 This issue represents a GitHub Pull Request. It cannot be merged through Gitea due to API limitations.</sub>
bsakaguchi 2026-10-23 04:14:19 +07:00
Sign in to join this conversation.
No milestone
No project
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set.

Reference
Pasta-Devs/Marinara-Engine#6853
No description provided.