[PR #320] [MERGED] fix(game): preserve concurrent metadata writes during /generate stream #4560

Closed
opened 2026-10-22 04:08:43 +07:00 by bsakaguchi · 0 comments
Owner

📋 Pull Request Information

Original PR: https://github.com/Pasta-Devs/Marinara-Engine/pull/320
Author: @Romuromylus
Created: 4/30/2026
Status: ✅ Merged
Merged: 5/3/2026
Merged by: @SpicyMarinara

Base: main ← Head: fix/game-start-stale-metadata-write


📝 Commits (3)

  • b7db371 fix(game): preserve concurrent metadata writes during /generate stream
  • 9a6ddfd Merge branch 'main' into fix/game-start-stale-metadata-write
  • c67c01f Merge branch 'main' into fix/game-start-stale-metadata-write

📊 Changes

1 file changed (+47 additions, -9 deletions)

View changed files

📝 packages/server/src/routes/generate.routes.ts (+47 -9)

📄 Description

Linked issue

Closes #321

Why this change

In Game Mode 1.5.6, clicking Start Game on a freshly-set-up game shows the intro typewriter, then snaps back to the Start Game screen mid-stream. The user clicks again and the chat ends up with two [Start the game] user messages and starts at scene 2. Repros across all GM models (Opus / GPT / DeepSeek), so it is not a model issue.

Root cause: several persistence sites in packages/server/src/routes/generate.routes.ts capture chat.metadata once at request start (line 397) and pass the parsed copy back to chats.updateMetadata later in the stream. updateMetadata replaces the metadata column wholesale, so any of those late writes clobbers concurrent updates from other endpoints — in particular /game/start, which flips gameSessionStatus from "ready" → "active" while the [Start the game] generation is in flight.

When the stale write lands first, the client's chatMeta refetches "ready" again. GameSurface's clearing effect at packages/client/src/components/game/GameSurface.tsx:5159-5164 had already fired (it ran while status was briefly "active") and cleared startGameRequested. With sessionStatus === "ready" and introPresented === false, the surface drops back to the idle Start Game phase. The user clicks Start a second time, which fires another [Start the game] and walks the GM into a "session continuation" framing — the visible "scene 2" start.

The combat agent at generate.routes.ts:6361-6365 already handles this correctly with a re-fetch-then-merge pattern. The other persistence sites do not.

A previous attempt at this bug (3e13514, reverted by 518dc92 on the contributor's fork) tried to fix this client-side via query invalidation. That couldn't have worked because the actual race is server-side metadata clobbering.

What changed

Convert the at-risk persistence sites in generate.routes.ts to match the freshChat pattern used by the combat agent — re-fetch metadata immediately before the merge, write only the specific fields being updated:

  • Preset entryStateOverrides persistence (~line 887)
  • Lorebook keeper entryStateOverrides persistence (3 occurrences around lines 2049, 2090, 2980)
  • lastMapPosition persistence (~line 2856)
  • Game-state-patch gameMap sync (~line 5942)
  • chat_summary rolling-summary persistence (~line 6402)
  • mariContext data-fetched persistence (~line 7590)

Each site now does:

const freshChat = await chats.getById(input.chatId);
const freshMeta = freshChat ? (parseExtra(freshChat.metadata) as Record<string, unknown>) : chatMeta;
await chats.updateMetadata(input.chatId, { ...freshMeta, /* only the field being updated */ });

No behavior change for any single-write request. Concurrent writes from /game/start (and any other endpoint that updates chat metadata while a generation is streaming) are no longer lost.

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

Tested on a fork build deployed to a private VPS instance running the same Dockerfile from main. Steps run by the contributor:

  1. Open a fresh Game Mode chat (Fantasy/Adventure/Smut/Harem setup, Heroic tone) where the Start Game button is visible.
  2. Click Start Game.
  3. Observe: intro typewriter shows, GM streams the opening scene, screen stays in the intro phase through the stream.

Before the fix, the screen snapped back to idle mid-stream, requiring a second Start click and producing a duplicate [Start the game] user message. After the fix, that no longer happens on the same setup. Reproducer was previously consistent across Opus, GPT, and DeepSeek.

To-verify by upstream maintainers:

  • Manually verify Game Mode Start Game on Linux/Windows builds — particularly confirming the chat history contains exactly one [Start the game] user message after a successful start.
  • Verify other paths that write to chat metadata mid-stream (lorebook entry overrides, map sync, summary) still work end-to-end on a normal turn.

Docs and release impact

  • No docs changes needed

UI evidence (if applicable)

n/a — fix is server-side; user-visible effect is "Start Game no longer requires a second click."

Summary by CodeRabbit

  • Bug Fixes
    • Fixed race conditions in metadata persistence to prevent lost or conflicting updates.
    • Improved reliability of saved game state (map positions, active maps) during gameplay.
    • Ensured chat summaries, entry settings, and context data are consistently persisted after updates.

🔄 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/320 **Author:** [@Romuromylus](https://github.com/Romuromylus) **Created:** 4/30/2026 **Status:** ✅ Merged **Merged:** 5/3/2026 **Merged by:** [@SpicyMarinara](https://github.com/SpicyMarinara) **Base:** `main` ← **Head:** `fix/game-start-stale-metadata-write` --- ### 📝 Commits (3) - [`b7db371`](https://github.com/Pasta-Devs/Marinara-Engine/commit/b7db37111d28bf5df33a3e8e0ce4076d3b110aad) fix(game): preserve concurrent metadata writes during /generate stream - [`9a6ddfd`](https://github.com/Pasta-Devs/Marinara-Engine/commit/9a6ddfd8891335d906f844a7ac3260deb214568b) Merge branch 'main' into fix/game-start-stale-metadata-write - [`c67c01f`](https://github.com/Pasta-Devs/Marinara-Engine/commit/c67c01fc4664373afc26dbba57c5887ab1d627da) Merge branch 'main' into fix/game-start-stale-metadata-write ### 📊 Changes **1 file changed** (+47 additions, -9 deletions) <details> <summary>View changed files</summary> 📝 `packages/server/src/routes/generate.routes.ts` (+47 -9) </details> ### 📄 Description ## Linked issue Closes #321 ## Why this change In Game Mode 1.5.6, clicking **Start Game** on a freshly-set-up game shows the intro typewriter, then snaps back to the Start Game screen mid-stream. The user clicks again and the chat ends up with two `[Start the game]` user messages and starts at scene 2. Repros across all GM models (Opus / GPT / DeepSeek), so it is not a model issue. Root cause: several persistence sites in `packages/server/src/routes/generate.routes.ts` capture `chat.metadata` once at request start (line 397) and pass the parsed copy back to `chats.updateMetadata` later in the stream. `updateMetadata` replaces the metadata column wholesale, so any of those late writes clobbers concurrent updates from other endpoints — in particular `/game/start`, which flips `gameSessionStatus` from `"ready"` → `"active"` while the `[Start the game]` generation is in flight. When the stale write lands first, the client's `chatMeta` refetches `"ready"` again. `GameSurface`'s clearing effect at `packages/client/src/components/game/GameSurface.tsx:5159-5164` had already fired (it ran while status was briefly `"active"`) and cleared `startGameRequested`. With `sessionStatus === "ready"` and `introPresented === false`, the surface drops back to the idle Start Game phase. The user clicks Start a second time, which fires another `[Start the game]` and walks the GM into a "session continuation" framing — the visible "scene 2" start. The combat agent at `generate.routes.ts:6361-6365` already handles this correctly with a re-fetch-then-merge pattern. The other persistence sites do not. A previous attempt at this bug ([3e13514](https://github.com/Pasta-Devs/Marinara-Engine/commit/3e13514), reverted by [518dc92](https://github.com/Pasta-Devs/Marinara-Engine/commit/518dc92) on the contributor's fork) tried to fix this client-side via query invalidation. That couldn't have worked because the actual race is server-side metadata clobbering. ## What changed Convert the at-risk persistence sites in `generate.routes.ts` to match the `freshChat` pattern used by the combat agent — re-fetch metadata immediately before the merge, write only the specific fields being updated: - Preset `entryStateOverrides` persistence (~line 887) - Lorebook keeper `entryStateOverrides` persistence (3 occurrences around lines 2049, 2090, 2980) - `lastMapPosition` persistence (~line 2856) - Game-state-patch `gameMap` sync (~line 5942) - `chat_summary` rolling-summary persistence (~line 6402) - `mariContext` data-fetched persistence (~line 7590) Each site now does: ```ts const freshChat = await chats.getById(input.chatId); const freshMeta = freshChat ? (parseExtra(freshChat.metadata) as Record<string, unknown>) : chatMeta; await chats.updateMetadata(input.chatId, { ...freshMeta, /* only the field being updated */ }); ``` No behavior change for any single-write request. Concurrent writes from `/game/start` (and any other endpoint that updates chat metadata while a generation is streaming) are no longer lost. ## 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 Tested on a fork build deployed to a private VPS instance running the same Dockerfile from `main`. Steps run by the contributor: 1. Open a fresh Game Mode chat (Fantasy/Adventure/Smut/Harem setup, Heroic tone) where the Start Game button is visible. 2. Click **Start Game**. 3. Observe: intro typewriter shows, GM streams the opening scene, screen stays in the intro phase through the stream. Before the fix, the screen snapped back to idle mid-stream, requiring a second Start click and producing a duplicate `[Start the game]` user message. After the fix, that no longer happens on the same setup. Reproducer was previously consistent across Opus, GPT, and DeepSeek. To-verify by upstream maintainers: - Manually verify Game Mode Start Game on Linux/Windows builds — particularly confirming the chat history contains exactly one `[Start the game]` user message after a successful start. - Verify other paths that write to chat metadata mid-stream (lorebook entry overrides, map sync, summary) still work end-to-end on a normal turn. ## Docs and release impact - [x] No docs changes needed ## UI evidence (if applicable) n/a — fix is server-side; user-visible effect is "Start Game no longer requires a second click." <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **Bug Fixes** * Fixed race conditions in metadata persistence to prevent lost or conflicting updates. * Improved reliability of saved game state (map positions, active maps) during gameplay. * Ensured chat summaries, entry settings, and context data are consistently persisted after updates. <!-- 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-22 04:08:43 +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#4560
No description provided.