[PR #5616] [MERGED] fix(storage): stop boot gallery recovery from loading every chat with images #6850

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

📋 Pull Request Information

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

Base: staging ← Head: fix/5612-gallery-recovery-boot-walk


📝 Commits (4)

  • f7267e7 fix(storage): stop boot gallery recovery from loading every chat with images
  • e129e0a fix(storage): harden the gallery-recovery peek per adversarial review
  • a6ff745 style: format the gallery-recovery regression
  • 7ec2c14 fix(storage): hand malformed shard rows to the loader so repair can run

📊 Changes

3 files changed (+391 additions, -16 deletions)

View changed files

📝 packages/server/src/db/file-backed-store.ts (+30 -0)
📝 packages/server/src/services/storage/gallery-recovery.ts (+111 -16)
➕ scripts/regressions/gallery-recovery.regression.ts (+250 -0)

📄 Description

Closes #5612. Part of the #5592 close-out (follows #5597/#5603; sibling of #5614).

Why

The startup gallery-recovery scan (re-registering orphaned image files) queried chat_images once per data/gallery/<chatId> directory. Every query was correctly chatId-scoped — which is exactly why no query audit ever flagged it — but any row read pulls that chat's entire storage unit (all 17 lazy tables' shards) into memory. On an install where most chats have generated images, boot walked nearly every chat unit into memory before the server even started listening, quietly reproducing the eager-boot footprint #5592 removed, and leaving eviction to claw it back down afterward.

What changed

For a chat whose unit is not resident, the scan now reads the chat's chat_images shard file straight off disk instead of going through the store. This is sound because a non-resident unit can hold no unflushed state: writes force the unit resident first, and eviction only runs at the tail of a successful flush and skips units with pending state — so an evicted unit's shard file is always the current state.

The peek is deliberately conservative: anything it cannot fully trust (unreadable file, valid-JSON-but-non-array root, a lone .bak from an interrupted flush) falls back to the normal scoped query, so the store's full recovery ladder stays in charge of corruption — and only that one chat's unit loads. Same for a genuine orphan: the insert goes through the normal path, loading just that chat.

Net effect at boot:

Case Before After
Chat with images, all recorded (the overwhelming majority) whole unit loaded zero storage access beyond one eager chats lookup + one shard-file read
Empty gallery directory / deleted chat's leftover directory whole unit loaded / none zero storage access
Chat with an orphaned file whole unit loaded that one unit loads (insert path, heal ladder included)
Unreadable chat_images shard whole unit loaded that one unit loads (recovery ladder handoff)
MARINARA_EAGER_STORAGE whole-table query (already resident) unchanged — old path kept verbatim

Also exports isLazyUnitTable() and a getFullyResidentLazyTables() controller accessor from the store (the peek must not run against an eager, whole-table-leased, or otherwise fully-resident table, where memory — not disk — is the truth; the accessor is line-identical to the one #5614 adds, so whichever merges second rebases cleanly). GALLERY_DIR moved from a module-load constant to a call-time getDataDir() so the function honors the environment it runs in.

Regression

New suite gallery-recovery.regression.ts (auto-discovered by the runner): six chats covering fully-recorded (must load nothing — the headline assert), orphaned file (loads exactly that unit, preserves the recorded row), corrupt shard with valid .bak (loader handoff recovers the row, no duplicate insert), no shard at all (recovers, shard created on flush), empty directory and deleted-chat directory (no storage access), untouched shards byte-identical after flush, and an idempotent second run. A/B-verified: red against the pre-fix scan (fully-recorded chats' units load), green with the fix. Self-skips under MARINARA_EAGER_STORAGE like the sibling lazy suite.

An adversarial verification pass (three independent reviewers on the residency invariant, peek-vs-load semantics, and regression validity) ran before opening this PR and caught five real problems in the first draft, all fixed and now pinned by the suite:

  • dbName-form rows (chat_id/file_path) are a loader-accepted on-disk shape the peek read as "no rows" — every recorded image in such a shard would have been re-registered as a duplicate. The peek now hands any non-canonical row shape to the loader (chat-g fixture).
  • Duplicate primary keys in one shard: the loader dedupes, so the dropped row's file is a genuine orphan the peek would have wrongly counted as recorded. Duplicate ids now hand off to the loader (chat-h fixture).
  • Whole-table lease blind spot: if chat_images were ever fully leased, memory (with unflushed writes) is the truth, not the files — the peek now checks getFullyResidentLazyTables() first. Not reachable in today's boot (verified: nothing before the scan touches chat_images), fixed defensively.
  • The first A/B was red for the wrong reason: the pre-fix module froze DATA_DIR at import time, so it scanned a nonexistent default dir instead of the fixture. The suite now uses dynamic imports after the env assignments; the re-run fails pre-fix on exactly the headline "no unit loads" assert.
  • The suite never peeked a store-written shard: a second-boot block now reopens a fresh store over the first boot's flushed shards and asserts none of them load — pinning peek compatibility with the serializer's actual output shape.

One accepted limitation, documented in-code: a row misfiled into another chat's shard file is invisible to the peek until its host unit loads, so its image can be re-registered as a duplicate. This matches lazy scoped-query semantics generally — the pre-fix scan only avoided it by loading every unit, which is the exact behavior being removed. The reviewers also confirmed the load-bearing invariants clean by execution: eviction only at the successful-flush tail, no write path that leaves a non-resident unit dirty, transaction rollback re-pairing, and byte-identical path/key derivation between the peek and the store.

Validation done

  • tsc --noEmit all packages ✅
  • Prettier (--check --end-of-line auto) on the three changed files ✅ (repo-wide pnpm check prettier step fails on this Windows box for all files — #5598, pre-existing)
  • Regression lanes: gallery-recovery (lazy + eager-skip) ✅, lazy-chat-units ✅, message-sharding ✅

Manual verification

  • On an install with images in several chats, start the server and confirm the gallery still lists every image per chat
  • Drop a stray .png into data/gallery/<some-chat>/, restart, and confirm it appears in that chat's gallery ([gallery-recovery] Recovered 1 orphaned gallery image(s) in the log)
  • On Termux (or with MARINARA_MAX_RESIDENT_CHATS set), watch boot memory: it should no longer climb toward the old eager-boot level during startup on image-heavy installs

Summary by CodeRabbit

  • Bug Fixes

    • Improved gallery recovery when lazy storage is enabled.
    • Gallery data can now be recovered without unnecessarily loading all chat image data into memory.
    • Recovery better handles missing, deleted, corrupt, duplicate, orphaned, and alternate-format gallery files.
    • Empty storage directories are ignored, and valid gallery files remain stable across server restarts.
  • Diagnostics

    • Added visibility into lazy tables that have been fully loaded into memory.

🔄 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/5616 **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/5612-gallery-recovery-boot-walk` --- ### 📝 Commits (4) - [`f7267e7`](https://github.com/Pasta-Devs/Marinara-Engine/commit/f7267e714b77ad48c7c1f0d8c31e8a730feca8f8) fix(storage): stop boot gallery recovery from loading every chat with images - [`e129e0a`](https://github.com/Pasta-Devs/Marinara-Engine/commit/e129e0abfc838bdd5fcee4b13176939c53204e6c) fix(storage): harden the gallery-recovery peek per adversarial review - [`a6ff745`](https://github.com/Pasta-Devs/Marinara-Engine/commit/a6ff7452fe75ae02940d1f9d2614191819a827bc) style: format the gallery-recovery regression - [`7ec2c14`](https://github.com/Pasta-Devs/Marinara-Engine/commit/7ec2c146ee61c01204783c38b2ced9bd4adec774) fix(storage): hand malformed shard rows to the loader so repair can run ### 📊 Changes **3 files changed** (+391 additions, -16 deletions) <details> <summary>View changed files</summary> 📝 `packages/server/src/db/file-backed-store.ts` (+30 -0) 📝 `packages/server/src/services/storage/gallery-recovery.ts` (+111 -16) ➕ `scripts/regressions/gallery-recovery.regression.ts` (+250 -0) </details> ### 📄 Description Closes #5612. Part of the #5592 close-out (follows #5597/#5603; sibling of #5614). ## Why The startup gallery-recovery scan (re-registering orphaned image files) queried `chat_images` once per `data/gallery/<chatId>` directory. Every query was correctly chatId-scoped — which is exactly why no query audit ever flagged it — but any row read pulls that chat's **entire storage unit** (all 17 lazy tables' shards) into memory. On an install where most chats have generated images, boot walked nearly every chat unit into memory before the server even started listening, quietly reproducing the eager-boot footprint #5592 removed, and leaving eviction to claw it back down afterward. ## What changed For a chat whose unit is **not resident**, the scan now reads the chat's `chat_images` shard file straight off disk instead of going through the store. This is sound because a non-resident unit can hold no unflushed state: writes force the unit resident first, and eviction only runs at the tail of a successful flush and skips units with pending state — so an evicted unit's shard file is always the current state. The peek is deliberately conservative: anything it cannot fully trust (unreadable file, valid-JSON-but-non-array root, a lone `.bak` from an interrupted flush) falls back to the normal scoped query, so the store's full recovery ladder stays in charge of corruption — and only that one chat's unit loads. Same for a genuine orphan: the insert goes through the normal path, loading just that chat. Net effect at boot: | Case | Before | After | |---|---|---| | Chat with images, all recorded (the overwhelming majority) | whole unit loaded | **zero storage access** beyond one eager `chats` lookup + one shard-file read | | Empty gallery directory / deleted chat's leftover directory | whole unit loaded / none | zero storage access | | Chat with an orphaned file | whole unit loaded | that one unit loads (insert path, heal ladder included) | | Unreadable `chat_images` shard | whole unit loaded | that one unit loads (recovery ladder handoff) | | `MARINARA_EAGER_STORAGE` | whole-table query (already resident) | unchanged — old path kept verbatim | Also exports `isLazyUnitTable()` and a `getFullyResidentLazyTables()` controller accessor from the store (the peek must not run against an eager, whole-table-leased, or otherwise fully-resident table, where memory — not disk — is the truth; the accessor is line-identical to the one #5614 adds, so whichever merges second rebases cleanly). `GALLERY_DIR` moved from a module-load constant to a call-time `getDataDir()` so the function honors the environment it runs in. ## Regression New suite `gallery-recovery.regression.ts` (auto-discovered by the runner): six chats covering fully-recorded (must load **nothing** — the headline assert), orphaned file (loads exactly that unit, preserves the recorded row), corrupt shard with valid `.bak` (loader handoff recovers the row, no duplicate insert), no shard at all (recovers, shard created on flush), empty directory and deleted-chat directory (no storage access), untouched shards byte-identical after flush, and an idempotent second run. A/B-verified: red against the pre-fix scan (fully-recorded chats' units load), green with the fix. Self-skips under `MARINARA_EAGER_STORAGE` like the sibling lazy suite. An adversarial verification pass (three independent reviewers on the residency invariant, peek-vs-load semantics, and regression validity) ran before opening this PR and caught five real problems in the first draft, all fixed and now pinned by the suite: - **dbName-form rows** (`chat_id`/`file_path`) are a loader-accepted on-disk shape the peek read as "no rows" — every recorded image in such a shard would have been re-registered as a duplicate. The peek now hands any non-canonical row shape to the loader (chat-g fixture). - **Duplicate primary keys** in one shard: the loader dedupes, so the dropped row's file is a genuine orphan the peek would have wrongly counted as recorded. Duplicate ids now hand off to the loader (chat-h fixture). - **Whole-table lease blind spot**: if `chat_images` were ever fully leased, memory (with unflushed writes) is the truth, not the files — the peek now checks `getFullyResidentLazyTables()` first. Not reachable in today's boot (verified: nothing before the scan touches `chat_images`), fixed defensively. - **The first A/B was red for the wrong reason**: the pre-fix module froze `DATA_DIR` at import time, so it scanned a nonexistent default dir instead of the fixture. The suite now uses dynamic imports after the env assignments; the re-run fails pre-fix on exactly the headline "no unit loads" assert. - **The suite never peeked a store-written shard**: a second-boot block now reopens a fresh store over the first boot's flushed shards and asserts none of them load — pinning peek compatibility with the serializer's actual output shape. One accepted limitation, documented in-code: a row misfiled into *another* chat's shard file is invisible to the peek until its host unit loads, so its image can be re-registered as a duplicate. This matches lazy scoped-query semantics generally — the pre-fix scan only avoided it by loading every unit, which is the exact behavior being removed. The reviewers also confirmed the load-bearing invariants clean by execution: eviction only at the successful-flush tail, no write path that leaves a non-resident unit dirty, transaction rollback re-pairing, and byte-identical path/key derivation between the peek and the store. ## Validation done - `tsc --noEmit` all packages ✅ - Prettier (`--check --end-of-line auto`) on the three changed files ✅ (repo-wide `pnpm check` prettier step fails on this Windows box for all files — #5598, pre-existing) - Regression lanes: `gallery-recovery` (lazy + eager-skip) ✅, `lazy-chat-units` ✅, `message-sharding` ✅ ## Manual verification - [ ] On an install with images in several chats, start the server and confirm the gallery still lists every image per chat - [ ] Drop a stray `.png` into `data/gallery/<some-chat>/`, restart, and confirm it appears in that chat's gallery (`[gallery-recovery] Recovered 1 orphaned gallery image(s)` in the log) - [ ] On Termux (or with `MARINARA_MAX_RESIDENT_CHATS` set), watch boot memory: it should no longer climb toward the old eager-boot level during startup on image-heavy installs <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit - **Bug Fixes** - Improved gallery recovery when lazy storage is enabled. - Gallery data can now be recovered without unnecessarily loading all chat image data into memory. - Recovery better handles missing, deleted, corrupt, duplicate, orphaned, and alternate-format gallery files. - Empty storage directories are ignored, and valid gallery files remain stable across server restarts. - **Diagnostics** - Added visibility into lazy tables that have been fully loaded into memory. <!-- 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:17 +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#6850
No description provided.