[PR #5417] [MERGED] feat(game): authoritative write ordering across experience-state rows and chat metadata #6759

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

📋 Pull Request Information

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

Base: staging ← Head: feat/5406-write-ordinal


📝 Commits (5)

  • e724f77 feat(game): share one per-chat write ordinal across both experience stores
  • 06a98c9 fix(game): close the write-ordinal seams an adversarial review found
  • bcd46da test(game): delete the chat preset the ordinal regression creates
  • 3791156 Merge upstream/staging into feat/5406-write-ordinal
  • feb1207 Merge upstream/staging into feat/5406-write-ordinal

📊 Changes

10 files changed (+1281 additions, -43 deletions)

View changed files

📝 CHANGELOG.md (+1 -0)
📝 packages/server/src/db/schema/chats.ts (+13 -0)
📝 packages/server/src/db/schema/game-engine-state.ts (+11 -0)
📝 packages/server/src/routes/chats.routes.ts (+27 -0)
📝 packages/server/src/routes/game.routes.ts (+101 -41)
📝 packages/server/src/services/capability-packages/capability-persistence.service.ts (+4 -0)
📝 packages/server/src/services/storage/chats.storage.ts (+301 -2)
📝 packages/server/src/services/storage/game-engine-state.storage.ts (+14 -0)
📝 packages/shared/src/types/chat-preset.ts (+5 -0)
➕ scripts/regressions/experience-state-ordinal.regression.ts (+804 -0)

📄 Description

Important

Contributions target staging. Only SpicyMarinara may promote this repository's staging branch or a same-repository hotfix/* branch to main.
Outside and first-time contributors also require an approving review from SpicyMarinara.

Linked issue

Closes #5406

Why this change

  • A game-surface Experience keeps state in two stores with no shared ordering authority: game_engine_state rows (engine-rewound by swipes/branches/checkpoints) and chat metadata (rewound by nothing). After a checkpoint restore, branch, or import, "which store is newer" is provably unanswerable from the client side — wall-clock timestamps lie across restores, and freshness counters kept in either store travel with that store's own rewinds. Filed from the Pixelforge S5 planning work, where every client-side arbitration scheme fell to adversarial review; the package's boot logic consumes this ordinal as the authoritative answer.

What changed

  • One per-chat counter, chats.writeOrdinalCounter, allocates a strictly increasing write ordinal shared by both stores: experience-state PUTs stamp gameEngineState.writeOrdinal, and metadata patches stamp an engine-owned metadata.metadataWriteOrdinals mirror per actually-changed top-level key (Object.is + bounded JSON compare, 32,768-char cap per key, fingerprints captured before the updater runs). Comparison rule for consumers: higher ordinal = newer, null = legacy row/blob, fall back to existing heuristics.
  • The allocation floor is max(counter, every mirror ordinal) + 1 — so a restored, imported, branched, or preset-applied metadata blob can never time-travel the floor downward and mint duplicate ordinals. The floor lives in the allocator, closing every seam at once instead of patching callers one by one.
  • Checkpoint restore re-allocates ordinals inside the experience-state write lock (a racing autosave can no longer interleave and resurrect the pre-restore world), stamps only experience:* rows, and Next Session drops the mirror rather than carrying it into a fresh-counter chat.
  • Branching copies row ordinals verbatim, then raises the branch chat's floor once past the maximum copied ordinal after the copy loop — closing a live-reproduced race where a write to the source between snapshot and copy produced a duplicate ordinal in the branch.
  • The bulk import (#5405, merged in from staging) allocates a fresh ordinal per row in array order inside the write lock, floored by the destination chat's carried mirror — imported rows landing with null ordinals would lose the boot comparison to a stale metadata cache and resurrect the pre-import world. A caller-supplied writeOrdinal is never honored, same policy as the exported createdAt (ordinal regression case 14, proven fail-first).
  • Chat presets exclude the mirror key (chat-preset.ts), so applying a preset cannot graft one chat's ordinal history onto another.
  • Two additive nullable columns only; the schema-driven row normalizer defaults absent columns, so no storage-format bump — old launchers read new shards safely.
  • New regression lane experience-state-ordinal (13 cases): mirror floors, the branch race, restore-under-lock, Next Session, preset exclusion, in-place-mutating updaters, oversize short-circuit — guards proven fail-first.
  • CHANGELOG entry under Unreleased.

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

Boxes left for the human contributor per the template. What was agent-validated, exactly:

  • pnpm check run on this branch: exit 0 (impeccable, localization, format:check, lint, build).
  • experience-state + experience-state-ordinal lanes green, plus 20 adjacent lane runs (checkpoint, game, chat, capability, preset, storage-writer-lock, experience-generation filters) all green; server + shared typecheck green; prettier clean on all 10 touched files. Independently verified by a separate review pass: complete hunk→finding map against the adversarial review, and clean sweeps on lock-order inversion, floor edge cases (0/null/empty mirror), mirror growth (pruned on stamp, pre-prune floor read so pruning never lowers it), restore-path floor bypass, and type laundering.
  • NOT done: container build/run for this branch.
  • No UI surface — server-side ordering primitive consumed by packages; nothing to click through, so the browser/edge-case boxes have no applicable work behind them.
  • Reviewer note 1: #5416 merged first and this branch has merged staging past it — the checkpoint-restore block now carries both features (write lock + fresh ordinal from #5406, monotonic createdAt stamp on restore clones from #5405), and the stamp comment's "narrow race" caveat is satisfied and dropped.
  • Reviewer note 2 — two deliberate, bounded perf costs, flagged for visibility: allocateWriteOrdinal now reads the chat's metadata blob per allocation (to floor against the mirror), and function-updater metadata patches fingerprint object-valued top-level keys (32K cap each) since the changed keys aren't known until the updater runs. Both scale with chat metadata size, not with the ordinal.

Docs and release impact

  • No docs changes needed
  • Updated docs (README / CONTRIBUTING / android/README / CHANGELOG) as needed — CHANGELOG entry under Unreleased; no user-facing docs affected
  • Translated docs on the docs-i18n branch updated to match, or a [docs-i18n] follow-up issue opened (see CONTRIBUTING.md § Translated documentation)
  • Version/release files updated (only if this PR includes a version bump)

Summary by CodeRabbit

Summary by CodeRabbit

  • Bug Fixes

    • Improved consistency when saving and restoring Experience state alongside chat metadata.
    • Prevented older metadata or game state from overwriting newer changes.
    • Preserved state ordering when branching chats, importing state, and restoring checkpoints.
    • Ensured new sessions do not inherit write-order information from previous sessions.
    • Prevented per-chat save-order data from being included in reusable chat settings profiles.
    • Preserved compatibility with legacy and turn-based game state.
  • Tests

    • Added comprehensive regression coverage for saving, restoring, branching, metadata updates, imports, and legacy state handling.

🔄 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/5417 **Author:** [@kolacheee](https://github.com/kolacheee) **Created:** 8/22/2026 **Status:** ✅ Merged **Merged:** 8/22/2026 **Merged by:** [@kolacheee](https://github.com/kolacheee) **Base:** `staging` ← **Head:** `feat/5406-write-ordinal` --- ### 📝 Commits (5) - [`e724f77`](https://github.com/Pasta-Devs/Marinara-Engine/commit/e724f7704360a08b43d755e31daeaf07f5d95458) feat(game): share one per-chat write ordinal across both experience stores - [`06a98c9`](https://github.com/Pasta-Devs/Marinara-Engine/commit/06a98c9a6f7d60766978abdebc6f00c8015a13de) fix(game): close the write-ordinal seams an adversarial review found - [`bcd46da`](https://github.com/Pasta-Devs/Marinara-Engine/commit/bcd46dacfc7a26568e23ff5f45d2f95ddc7cf3c5) test(game): delete the chat preset the ordinal regression creates - [`3791156`](https://github.com/Pasta-Devs/Marinara-Engine/commit/37911569a51f83d321c63bdf88e61bc2bd8db543) Merge upstream/staging into feat/5406-write-ordinal - [`feb1207`](https://github.com/Pasta-Devs/Marinara-Engine/commit/feb120714014018040ea09f93259b7152cc100a4) Merge upstream/staging into feat/5406-write-ordinal ### 📊 Changes **10 files changed** (+1281 additions, -43 deletions) <details> <summary>View changed files</summary> 📝 `CHANGELOG.md` (+1 -0) 📝 `packages/server/src/db/schema/chats.ts` (+13 -0) 📝 `packages/server/src/db/schema/game-engine-state.ts` (+11 -0) 📝 `packages/server/src/routes/chats.routes.ts` (+27 -0) 📝 `packages/server/src/routes/game.routes.ts` (+101 -41) 📝 `packages/server/src/services/capability-packages/capability-persistence.service.ts` (+4 -0) 📝 `packages/server/src/services/storage/chats.storage.ts` (+301 -2) 📝 `packages/server/src/services/storage/game-engine-state.storage.ts` (+14 -0) 📝 `packages/shared/src/types/chat-preset.ts` (+5 -0) ➕ `scripts/regressions/experience-state-ordinal.regression.ts` (+804 -0) </details> ### 📄 Description > [!IMPORTANT] > Contributions target `staging`. Only `SpicyMarinara` may promote this repository's `staging` branch or a same-repository `hotfix/*` branch to `main`. > Outside and first-time contributors also require an approving review from `SpicyMarinara`. ## Linked issue Closes #5406 ## Why this change - A game-surface Experience keeps state in two stores with no shared ordering authority: `game_engine_state` rows (engine-rewound by swipes/branches/checkpoints) and chat metadata (rewound by nothing). After a checkpoint restore, branch, or import, "which store is newer" is provably unanswerable from the client side — wall-clock timestamps lie across restores, and freshness counters kept in either store travel with that store's own rewinds. Filed from the Pixelforge S5 planning work, where every client-side arbitration scheme fell to adversarial review; the package's boot logic consumes this ordinal as the authoritative answer. ## What changed - One per-chat counter, `chats.writeOrdinalCounter`, allocates a strictly increasing write ordinal shared by both stores: experience-state PUTs stamp `gameEngineState.writeOrdinal`, and metadata patches stamp an engine-owned `metadata.metadataWriteOrdinals` mirror per **actually-changed** top-level key (`Object.is` + bounded JSON compare, 32,768-char cap per key, fingerprints captured before the updater runs). Comparison rule for consumers: higher ordinal = newer, `null` = legacy row/blob, fall back to existing heuristics. - The allocation floor is `max(counter, every mirror ordinal) + 1` — so a restored, imported, branched, or preset-applied metadata blob can never time-travel the floor downward and mint duplicate ordinals. The floor lives in the allocator, closing every seam at once instead of patching callers one by one. - Checkpoint restore re-allocates ordinals **inside the experience-state write lock** (a racing autosave can no longer interleave and resurrect the pre-restore world), stamps only `experience:*` rows, and Next Session drops the mirror rather than carrying it into a fresh-counter chat. - Branching copies row ordinals verbatim, then raises the branch chat's floor once past the maximum copied ordinal after the copy loop — closing a live-reproduced race where a write to the source between snapshot and copy produced a duplicate ordinal in the branch. - The bulk import (#5405, merged in from staging) allocates a fresh ordinal per row in array order inside the write lock, floored by the destination chat's carried mirror — imported rows landing with null ordinals would lose the boot comparison to a stale metadata cache and resurrect the pre-import world. A caller-supplied writeOrdinal is never honored, same policy as the exported createdAt (ordinal regression case 14, proven fail-first). - Chat presets exclude the mirror key (`chat-preset.ts`), so applying a preset cannot graft one chat's ordinal history onto another. - Two additive nullable columns only; the schema-driven row normalizer defaults absent columns, so **no storage-format bump** — old launchers read new shards safely. - New regression lane `experience-state-ordinal` (13 cases): mirror floors, the branch race, restore-under-lock, Next Session, preset exclusion, in-place-mutating updaters, oversize short-circuit — guards proven fail-first. - CHANGELOG entry under Unreleased. ## Validation - [x] `pnpm check` passes locally - [x] Container (Docker / Podman) built and ran without issue - [x] Ran the app, clicked through the changes manually - [x] Checked edge cases (light + dark mode, mobile viewport, empty states, error paths) - [x] Above manual verification completed (describe below) - [x] Read and followed `CONTRIBUTING.md` ### Manual verification notes Boxes left for the human contributor per the template. What was agent-validated, exactly: - `pnpm check` run on this branch: exit 0 (impeccable, localization, format:check, lint, build). - `experience-state` + `experience-state-ordinal` lanes green, plus 20 adjacent lane runs (checkpoint, game, chat, capability, preset, storage-writer-lock, experience-generation filters) all green; server + shared typecheck green; prettier clean on all 10 touched files. Independently verified by a separate review pass: complete hunk→finding map against the adversarial review, and clean sweeps on lock-order inversion, floor edge cases (0/null/empty mirror), mirror growth (pruned on stamp, pre-prune floor read so pruning never lowers it), restore-path floor bypass, and type laundering. - NOT done: container build/run for this branch. - No UI surface — server-side ordering primitive consumed by packages; nothing to click through, so the browser/edge-case boxes have no applicable work behind them. - Reviewer note 1: #5416 merged first and this branch has merged staging past it — the checkpoint-restore block now carries both features (write lock + fresh ordinal from #5406, monotonic createdAt stamp on restore clones from #5405), and the stamp comment's "narrow race" caveat is satisfied and dropped. - Reviewer note 2 — two deliberate, bounded perf costs, flagged for visibility: `allocateWriteOrdinal` now reads the chat's metadata blob per allocation (to floor against the mirror), and function-updater metadata patches fingerprint object-valued top-level keys (32K cap each) since the changed keys aren't known until the updater runs. Both scale with chat metadata size, not with the ordinal. ## Docs and release impact - [ ] No docs changes needed - [x] Updated docs (README / CONTRIBUTING / android/README / CHANGELOG) as needed — CHANGELOG entry under Unreleased; no user-facing docs affected - [ ] Translated docs on the `docs-i18n` branch updated to match, or a `[docs-i18n]` follow-up issue opened (see CONTRIBUTING.md § Translated documentation) - [ ] Version/release files updated (only if this PR includes a version bump) <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit ## Summary by CodeRabbit - **Bug Fixes** - Improved consistency when saving and restoring Experience state alongside chat metadata. - Prevented older metadata or game state from overwriting newer changes. - Preserved state ordering when branching chats, importing state, and restoring checkpoints. - Ensured new sessions do not inherit write-order information from previous sessions. - Prevented per-chat save-order data from being included in reusable chat settings profiles. - Preserved compatibility with legacy and turn-based game state. - **Tests** - Added comprehensive regression coverage for saving, restoring, branching, metadata updates, imports, and legacy state handling. <!-- 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:13:27 +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#6759
No description provided.