[PR #5879] [MERGED] feat(server): let capability packages register their own file tables #6977

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

📋 Pull Request Information

Original PR: https://github.com/Pasta-Devs/Marinara-Engine/pull/5879
Author: @Gunterlie
Created: 9/5/2026
Status: ✅ Merged
Merged: 9/5/2026
Merged by: @Gunterlie

Base: staging ← Head: feat/capability-package-file-tables


📝 Commits (3)

  • 5a3155a feat(server): let capability packages register their own file tables
  • 6a274ca fix(server): harden package table registration against bad definitions
  • 898f5c2 test(server): assert registration continues past a malformed package table

📊 Changes

5 files changed (+699 additions, -33 deletions)

View changed files

📝 CHANGELOG.md (+1 -0)
📝 packages/server/src/db/file-backed-store.ts (+315 -31)
📝 packages/server/src/routes/backup.routes.ts (+14 -1)
📝 scripts/regressions/launcher/format-guard.regression.mjs (+4 -1)
➕ scripts/regressions/package-table-registration.regression.ts (+365 -0)

📄 Description

Important

Contributions target staging.

Linked issue

Closes #5878

Why this change

The Slurp capability package needs package-owned storage. Slurp declares its own file tables and cannot persist them.

The file-backed store builds every table's metadata once at module load, from a hardcoded allowlist of the Engine's own tables. Any name outside that list has no metadata, so getMeta() throws [file-storage] Unsupported table: <name>. A downloaded capability package therefore has no supported way to persist its own data; it can only borrow an Engine table that was designed for something else.

This PR closes the Engine-side gap: it adds the storage API that accepts package-declared tables into a live store.

What changed

registerTables on the store controller. Packages activate after initialize(), so registration runs against an already-running store rather than at boot. A registered table gets everything a boot-loaded table gets, because the alternative is a table that accepts writes and silently loses them: validated metadata, a row container, its existing on-disk rows, membership in the flush loop, and an entry in the snapshot manifest. Registration is idempotent, so a package reload re-registering the same table does not reset it. It cannot shadow a table that already exists — the first definition of a name, always the Engine's own since those are built at module load, keeps the name. Failures are per table and logged rather than thrown, so one malformed package table definition cannot abort host startup.

Table-name validation. Table names become filesystem paths (tables/<name>.json, tables/<name>/) with no escaping anywhere in the store. That was safe only while every name came from the Engine's own hardcoded list; an unvalidated package-supplied name would be an arbitrary-write primitive outside the data directory. fileBackedTableNameRejection now gates every registered name and accepts only what the Engine's own names already look like: non-empty, at most 64 characters, matching /^[a-z][a-z0-9_]*$/, and not a Windows reserved basename (Windows blocks those with any extension). The length bound keeps <name>.json plus a shard filename inside path limits. A rejected name is refused before it reaches any path join or any registry.

The regression asserts this against the real store: it registers a set of hostile names — ../../escaped, .., nested/table, back\slash, Uppercase, trailing., with space, _leading, 9leading, con, and a 65-character name — and then walks the entire sandbox tree, which is one level above the storage directory so an escape would land somewhere the test can see. It asserts that no rejected name joins the file-backed table list and that not one file or directory was created, inside or outside the data directory.

Sharding. Registered tables are sharded, like every Engine table. SHARDED_TABLES aliases FILE_BACKED_TABLES, so a name pushed onto the list becomes sharded by array identity whether or not that was intended; making registered tables flat would opt a brand-new table into the store's least-exercised path and would still leave the alias lying about them. That aliasing was also a trap worth closing: SHARDED_TABLE_SET used to be a module-load snapshot of the list, so after registration the array said "sharded" and the set said "not sharded", and the load, flush and delete paths would each have classified the same table differently. The set is now mutable and registration writes the list and the set together, or neither.

No primary key is refused at registration. Registered tables have no SHARD_KEY_COLUMNS entry, so they shard by primary key. A keyless table would register cleanly and then throw "no stable shard key" on its first insert, long after a package author could connect the failure to the definition. It is now refused up front, before the name enters any registry.

Profile export/import. Registered tables persist exactly like Engine tables and are captured by a full data-directory backup, but they are deliberately excluded from profile export. profileTableObjects in backup.routes.ts is built from the schema barrel, so a runtime-registered table has no entry and every loop skips it. That exclusion is intentional, not an oversight to fix by consulting the live registry: a profile snapshot is portable user data that may be restored into a different install where the owning package does not exist, so importing those rows would be a restore-time failure or a silent orphan with no schema to validate against. A comment at that site records the reasoning.

Known constraint — the registries are process-global. tableMetasByName, FILE_BACKED_TABLE_SET and SHARDED_TABLE_SET are module-level, as the Engine's own table metadata already is. A registered name therefore outlives the store that registered it: a store constructed later in the same process, against a different storage directory, already knows the name, boot-loads it from its own directory, and finds nothing. That degrades to an empty table, never to corruption or a cross-directory read. It is accepted because production runs one store per process, and because the alternative — instance-scoped registries — means threading a store through getMeta() and the entire module-level lookup surface. Per-instance registration is the correct fix if the Engine ever runs more than one store at a time. Until then there is a concrete consequence for tests: a test that constructs several stores must give each scenario a distinct table name, or its second store silently exercises the boot loader instead of registerTables. The regression follows that rule explicitly, with a comment at each case that needs a fresh name.

No caller is wired yet. Nothing in the Engine currently loads package-supplied table objects. This PR is the storage-side API only; connecting a package loader to it is separate work.

Also included:

  • FILE_BACKED_TABLES is now a widened runtime list built from BUILT_IN_FILE_BACKED_TABLES, so every consumer that walks "all file-backed tables" sees registered names. The Engine's own tuple keeps its literal-union type so CASCADES and other table-name constants stay compile-checked. The list itself is module-private; the only sanctioned way to grow it is registerTables, which validates the name and updates every companion registry in the same breath.
  • scripts/regressions/launcher/format-guard.regression.mjs now compares the launcher's SHARDED_TABLES copy against BUILT_IN_FILE_BACKED_TABLES rather than the widened list. An offline downgrade script can never know a runtime-registered name.
  • loadRegisteredTableRows reads a newly registered table's existing shards. It is deliberately thinner than the boot loader: the re-home detection, duplicate arbitration and format-migration repair there exist for histories a table the Engine has never written cannot have. Corrupt-file recovery still applies, because that comes from parseJsonFile and applies to any file on disk.
  • buildFileTableMetadata is extracted so schema-declared and package-registered tables share the same shape and unique-constraint validation.
  • New regression scripts/regressions/package-table-registration.regression.ts (auto-discovered by the runner).

Validation

  • pnpm check passes locally
  • Container (Docker / Podman) built and ran without issue
  • Ran the app, clicked through the changes manually
  • Checked edge cases (light + dark mode, mobile viewport, empty states, error paths)
  • Above manual verification completed (describe below)
  • Read and followed CONTRIBUTING.md

Manual verification notes

The checkboxes above are left unticked for a human to confirm. This change has no UI surface and no wired caller, so the meaningful verification is the new regression, which drives the real store end to end rather than a mock. It is written to be run as node ./scripts/run-regressions.mjs --filter package-table-registration after pnpm build:shared, and each case builds a real store over a fresh temporary storage directory:

  1. Hostile names. Flush twice to a clean baseline (the second flush is what creates the manifest's .bak, so normal store bookkeeping stays out of the comparison), snapshot the whole sandbox, register each hostile name plus a keyless table, flush again, and assert the sandbox tree is byte-for-byte unchanged and no rejected name entered FILE_BACKED_TABLES.
  2. Register and persist. Register a valid table, insert a row, re-register the same table and confirm the row survives, flush, and check on disk that a shard directory exists and that no flat <name>.json monolith was also created. Then close the store, open a new one over the same directory, register again, and confirm the row is read back with its values intact. Delete the row, flush, and confirm the emptied shard is removed rather than left as litter.
  3. Shadowing. Insert a real chats row, register an impostor table also named chats with different columns, and confirm the Engine's rows and column metadata are untouched and the name is not duplicated in the table list.
  4. Recovery on registration. Plant a corrupt shard primary with a good .bak. Registration must recover the rows and mark the shard dirty; the test then flushes and reads the file back to confirm it was rewritten canonically, so the next boot does not recover from backup all over again.
  5. Recovery to zero rows. Plant a corrupt primary with a valid-but-empty .bak. There is no shard key to dirty, so the file is marked stale instead; the test confirms the flush removes the primary and its backup rather than leaving a corrupt pair that is re-recovered and re-logged on every boot.
  6. Unrecoverable pair. Plant a primary and a .bak that both fail to parse, and confirm both are quarantined for manual inspection, reported through getQuarantinedTables() against the registered table, and left undisturbed by the following flush.

The regression sets LOG_LEVEL=silent before importing the store, because these cases deliberately provoke error-level rejections and quarantine reports, and the pretty-print transport worker can otherwise outlive the test and hang the runner.

Docs and release impact

  • No docs changes needed
  • Updated docs (README / CONTRIBUTING / android/README / CHANGELOG) as needed
  • Translated docs on the docs-i18n branch updated to match, or a [docs-i18n] follow-up issue opened
  • Version/release files updated (only if this PR includes a version bump)

A CHANGELOG.md entry is added under [Unreleased]. No user-facing docs change, because there is no user-facing surface yet. No version bump.

UI evidence (if applicable)

Not applicable; no UI surface.

Summary by CodeRabbit

  • New Features

    • Capability packages can register persistent file tables at runtime.
    • Registered tables support sharding, querying, persistence across restarts, and safe backup recovery.
    • Table names are strictly validated to prevent unsafe or conflicting registrations.
    • Re-registering an existing table is handled safely and consistently.
  • Bug Fixes

    • Improved recovery of damaged or unreadable table data, including quarantining unusable files and rewriting recovered shards canonically.

🔄 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/5879 **Author:** [@Gunterlie](https://github.com/Gunterlie) **Created:** 9/5/2026 **Status:** ✅ Merged **Merged:** 9/5/2026 **Merged by:** [@Gunterlie](https://github.com/Gunterlie) **Base:** `staging` ← **Head:** `feat/capability-package-file-tables` --- ### 📝 Commits (3) - [`5a3155a`](https://github.com/Pasta-Devs/Marinara-Engine/commit/5a3155ac5cbb2be3ad31178f168b9fd73a56662b) feat(server): let capability packages register their own file tables - [`6a274ca`](https://github.com/Pasta-Devs/Marinara-Engine/commit/6a274caf7bb2fde951f3c1188d11ff2acd9fd7a2) fix(server): harden package table registration against bad definitions - [`898f5c2`](https://github.com/Pasta-Devs/Marinara-Engine/commit/898f5c2ea6f7bdf4958c4450e7965cbb600b6461) test(server): assert registration continues past a malformed package table ### 📊 Changes **5 files changed** (+699 additions, -33 deletions) <details> <summary>View changed files</summary> 📝 `CHANGELOG.md` (+1 -0) 📝 `packages/server/src/db/file-backed-store.ts` (+315 -31) 📝 `packages/server/src/routes/backup.routes.ts` (+14 -1) 📝 `scripts/regressions/launcher/format-guard.regression.mjs` (+4 -1) ➕ `scripts/regressions/package-table-registration.regression.ts` (+365 -0) </details> ### 📄 Description > [!IMPORTANT] > Contributions target `staging`. ## Linked issue Closes #5878 ## Why this change The Slurp capability package needs package-owned storage. Slurp declares its own file tables and cannot persist them. The file-backed store builds every table's metadata once at module load, from a hardcoded allowlist of the Engine's own tables. Any name outside that list has no metadata, so `getMeta()` throws `[file-storage] Unsupported table: <name>`. A downloaded capability package therefore has no supported way to persist its own data; it can only borrow an Engine table that was designed for something else. This PR closes the Engine-side gap: it adds the storage API that accepts package-declared tables into a live store. ## What changed **`registerTables` on the store controller.** Packages activate after `initialize()`, so registration runs against an already-running store rather than at boot. A registered table gets everything a boot-loaded table gets, because the alternative is a table that accepts writes and silently loses them: validated metadata, a row container, its existing on-disk rows, membership in the flush loop, and an entry in the snapshot manifest. Registration is idempotent, so a package reload re-registering the same table does not reset it. It cannot shadow a table that already exists — the first definition of a name, always the Engine's own since those are built at module load, keeps the name. Failures are per table and logged rather than thrown, so one malformed package table definition cannot abort host startup. **Table-name validation.** Table names become filesystem paths (`tables/<name>.json`, `tables/<name>/`) with no escaping anywhere in the store. That was safe only while every name came from the Engine's own hardcoded list; an unvalidated package-supplied name would be an arbitrary-write primitive outside the data directory. `fileBackedTableNameRejection` now gates every registered name and accepts only what the Engine's own names already look like: non-empty, at most 64 characters, matching `/^[a-z][a-z0-9_]*$/`, and not a Windows reserved basename (Windows blocks those with any extension). The length bound keeps `<name>.json` plus a shard filename inside path limits. A rejected name is refused before it reaches any path join or any registry. The regression asserts this against the real store: it registers a set of hostile names — `../../escaped`, `..`, `nested/table`, `back\slash`, `Uppercase`, `trailing.`, `with space`, `_leading`, `9leading`, `con`, and a 65-character name — and then walks the entire sandbox tree, which is one level above the storage directory so an escape would land somewhere the test can see. It asserts that no rejected name joins the file-backed table list and that not one file or directory was created, inside or outside the data directory. **Sharding.** Registered tables are sharded, like every Engine table. `SHARDED_TABLES` aliases `FILE_BACKED_TABLES`, so a name pushed onto the list becomes sharded by array identity whether or not that was intended; making registered tables flat would opt a brand-new table into the store's least-exercised path and would still leave the alias lying about them. That aliasing was also a trap worth closing: `SHARDED_TABLE_SET` used to be a module-load snapshot of the list, so after registration the array said "sharded" and the set said "not sharded", and the load, flush and delete paths would each have classified the same table differently. The set is now mutable and registration writes the list and the set together, or neither. **No primary key is refused at registration.** Registered tables have no `SHARD_KEY_COLUMNS` entry, so they shard by primary key. A keyless table would register cleanly and then throw "no stable shard key" on its first insert, long after a package author could connect the failure to the definition. It is now refused up front, before the name enters any registry. **Profile export/import.** Registered tables persist exactly like Engine tables and are captured by a full data-directory backup, but they are deliberately excluded from profile export. `profileTableObjects` in `backup.routes.ts` is built from the schema barrel, so a runtime-registered table has no entry and every loop skips it. That exclusion is intentional, not an oversight to fix by consulting the live registry: a profile snapshot is portable user data that may be restored into a different install where the owning package does not exist, so importing those rows would be a restore-time failure or a silent orphan with no schema to validate against. A comment at that site records the reasoning. **Known constraint — the registries are process-global.** `tableMetasByName`, `FILE_BACKED_TABLE_SET` and `SHARDED_TABLE_SET` are module-level, as the Engine's own table metadata already is. A registered name therefore outlives the store that registered it: a store constructed later in the same process, against a different storage directory, already knows the name, boot-loads it from its own directory, and finds nothing. That degrades to an empty table, never to corruption or a cross-directory read. It is accepted because production runs one store per process, and because the alternative — instance-scoped registries — means threading a store through `getMeta()` and the entire module-level lookup surface. Per-instance registration is the correct fix if the Engine ever runs more than one store at a time. Until then there is a concrete consequence for tests: a test that constructs several stores **must** give each scenario a distinct table name, or its second store silently exercises the boot loader instead of `registerTables`. The regression follows that rule explicitly, with a comment at each case that needs a fresh name. **No caller is wired yet.** Nothing in the Engine currently loads package-supplied table objects. This PR is the storage-side API only; connecting a package loader to it is separate work. Also included: - `FILE_BACKED_TABLES` is now a widened runtime list built from `BUILT_IN_FILE_BACKED_TABLES`, so every consumer that walks "all file-backed tables" sees registered names. The Engine's own tuple keeps its literal-union type so `CASCADES` and other table-name constants stay compile-checked. The list itself is module-private; the only sanctioned way to grow it is `registerTables`, which validates the name and updates every companion registry in the same breath. - `scripts/regressions/launcher/format-guard.regression.mjs` now compares the launcher's `SHARDED_TABLES` copy against `BUILT_IN_FILE_BACKED_TABLES` rather than the widened list. An offline downgrade script can never know a runtime-registered name. - `loadRegisteredTableRows` reads a newly registered table's existing shards. It is deliberately thinner than the boot loader: the re-home detection, duplicate arbitration and format-migration repair there exist for histories a table the Engine has never written cannot have. Corrupt-file recovery still applies, because that comes from `parseJsonFile` and applies to any file on disk. - `buildFileTableMetadata` is extracted so schema-declared and package-registered tables share the same shape and unique-constraint validation. - New regression `scripts/regressions/package-table-registration.regression.ts` (auto-discovered by the runner). ## Validation - [ ] `pnpm check` passes locally - [ ] Container (Docker / Podman) built and ran without issue - [ ] Ran the app, clicked through the changes manually - [ ] Checked edge cases (light + dark mode, mobile viewport, empty states, error paths) - [ ] Above manual verification completed (describe below) - [ ] Read and followed `CONTRIBUTING.md` ### Manual verification notes The checkboxes above are left unticked for a human to confirm. This change has no UI surface and no wired caller, so the meaningful verification is the new regression, which drives the real store end to end rather than a mock. It is written to be run as `node ./scripts/run-regressions.mjs --filter package-table-registration` after `pnpm build:shared`, and each case builds a real store over a fresh temporary storage directory: 1. **Hostile names.** Flush twice to a clean baseline (the second flush is what creates the manifest's `.bak`, so normal store bookkeeping stays out of the comparison), snapshot the whole sandbox, register each hostile name plus a keyless table, flush again, and assert the sandbox tree is byte-for-byte unchanged and no rejected name entered `FILE_BACKED_TABLES`. 2. **Register and persist.** Register a valid table, insert a row, re-register the same table and confirm the row survives, flush, and check on disk that a shard directory exists and that no flat `<name>.json` monolith was also created. Then close the store, open a new one over the same directory, register again, and confirm the row is read back with its values intact. Delete the row, flush, and confirm the emptied shard is removed rather than left as litter. 3. **Shadowing.** Insert a real `chats` row, register an impostor table also named `chats` with different columns, and confirm the Engine's rows and column metadata are untouched and the name is not duplicated in the table list. 4. **Recovery on registration.** Plant a corrupt shard primary with a good `.bak`. Registration must recover the rows *and* mark the shard dirty; the test then flushes and reads the file back to confirm it was rewritten canonically, so the next boot does not recover from backup all over again. 5. **Recovery to zero rows.** Plant a corrupt primary with a valid-but-empty `.bak`. There is no shard key to dirty, so the file is marked stale instead; the test confirms the flush removes the primary and its backup rather than leaving a corrupt pair that is re-recovered and re-logged on every boot. 6. **Unrecoverable pair.** Plant a primary and a `.bak` that both fail to parse, and confirm both are quarantined for manual inspection, reported through `getQuarantinedTables()` against the registered table, and left undisturbed by the following flush. The regression sets `LOG_LEVEL=silent` before importing the store, because these cases deliberately provoke error-level rejections and quarantine reports, and the pretty-print transport worker can otherwise outlive the test and hang the runner. ## Docs and release impact - [ ] No docs changes needed - [ ] Updated docs (README / CONTRIBUTING / android/README / CHANGELOG) as needed - [ ] Translated docs on the `docs-i18n` branch updated to match, or a `[docs-i18n]` follow-up issue opened - [ ] Version/release files updated (only if this PR includes a version bump) A `CHANGELOG.md` entry is added under `[Unreleased]`. No user-facing docs change, because there is no user-facing surface yet. No version bump. ## UI evidence (if applicable) Not applicable; no UI surface. <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **New Features** * Capability packages can register persistent file tables at runtime. * Registered tables support sharding, querying, persistence across restarts, and safe backup recovery. * Table names are strictly validated to prevent unsafe or conflicting registrations. * Re-registering an existing table is handled safely and consistently. * **Bug Fixes** * Improved recovery of damaged or unreadable table data, including quarantining unusable files and rewriting recovered shards canonically. <!-- 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:15:25 +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#6977
No description provided.