[GH-ISSUE #6144] A lorebook entry you switch off for one chat flips back on if you do it while a reply is being prepared #3417

Closed
opened 2026-10-21 06:02:53 +07:00 by bsakaguchi · 1 comment
Owner

Originally created by @kolacheee on GitHub (Sep 13, 2026).
Original GitHub issue: https://github.com/Pasta-Devs/Marinara-Engine/issues/6144

Originally assigned to: @SpicyMarinara on GitHub.

If you turn a lorebook entry off (or back on) for a single chat while the app is still preparing a reply, the change is thrown away. The switch moves, the server accepts it, and then it silently flips back once the turn finishes, with no error and no toast. The entry is live again for that chat and its text shows up in the next prompt. The same window also brings back per-chat entry switches that a lorebook deletion just cleaned up, leaving switches pointing at entries that no longer exist.

The window is the prompt assembly phase, not the streaming phase. Once reply text starts appearing in the bubble the change is safe.

How to reproduce (try it yourself)

  1. Open any chat that has a lorebook attached with at least one entry. The entry does not need to have fired before, and the chat does not need any existing per-chat switches.
  2. Widen the window so a human can hit it: open Chat Settings, Agents, and enable a character activity agent. That agent's call runs before the lorebook state is written back in every chat mode, so it buys you a real multi-second window. The widest window of all is a Conversation chat with more than one character, group mode set to Individual, no target character picked, not impersonating, plus a pre-generation agent enabled.
  3. Send a message.
  4. While the progress line still reads Agents, Lorebooks, Embedding or Assembling, and before any reply text appears, open Chat Settings, Lorebooks, click the pencil on the attached book, and flip one entry's switch OFF.
  5. Let the reply finish, then reopen the lorebook entry editor or reload the page.
  6. Send another message containing that entry's keyword and open Peek Prompt.

What you'll see: In step 4 the switch turns off and stays off, and the server answers 200. After the turn finishes it is back ON by itself, and in Peek Prompt the entry's text is back in the lore block. The same thing happens in the other direction: start from an entry already switched off for the chat, switch it ON inside the same window, and it reverts to off.

What should happen: The switch you set during the turn should stick, in both directions, exactly as it does when no generation is running.

Two extra checks that pin down what is going on:

  • Negative control: change some other chat setting inside the same window, for example the lorebook token budget. That one survives, so this is not a general metadata race, it is specific to the per-chat entry switches.
  • Deletion cleanup: send a message, and while the progress line still reads Agents or Lorebooks, go to Library, Lorebooks, and delete the book that chat has attached. Let the turn finish, then look at the chat with curl -s http://127.0.0.1:7860/api/chats/<chatId> | python3 -m json.tool | grep -A4 entryStateOverrides. The switches the deletion cleared are back, keyed to entries of a book that no longer exists.

Where it is

At staging ac14dd704:

  • packages/server/src/services/generation/lorebook-generation-runtime.ts:64-79, persistLorebookRuntimeState. It re-reads fresh chat metadata at :71-72 and then discards that fresh read for exactly two keys: await args.chats.updateMetadata(args.chatId, { ...freshMeta, entryStateOverrides: args.entryStateOverrides, entryTimingStates: args.entryTimingStates }) at :73-77.
  • packages/server/src/services/storage/chats.storage.ts:1440-1462, updateMetadata, documented as "Whole-blob metadata replace, outside the patch queue and NOT write-ordinal stamped (#5406)", with the rule at :1449-1450: "a key that becomes package-ordered must never be written here. Move the write to patchMetadata rather than adding a caller on this path."
  • packages/server/src/routes/chats.routes.ts:1367-1412, PATCH /:id/lorebook-entries/:entryId, the user-facing writer. This one is correct: it goes through storage.patchMetadata at :1397-1409.
  • packages/server/src/routes/generate.routes.ts:1261, the request-start snapshot let chatMeta = parseExtra(chat.metadata), and the four write-back sites at :2632, :2897, :3398 and :3879. All four run before sendProgress("generating") at :8720 and :8871, which is why the window ends at prompt assembly.
  • packages/server/src/services/lorebook/index.ts:1295 and :1308: the returned map is a copy of the request-start snapshot, or an empty object when the chat had none, never a merge against current storage.
  • scripts/regressions/chat-lorebook-entry-scope.regression.ts:88-92: the lane's scan() helper persists with chats.patchMetadata, not with persistLorebookRuntimeState.

What's happening

There are two writers for the chat's per-chat lorebook entry state and they do not serialize against each other. The switch in the UI writes through the per-chat metadata patch queue, which is the safe path. The generation writes its lorebook state back through the unqueued whole-blob path, and the map it writes is a copy of the metadata it read at the very start of the request. So any switch you change between request start and the end of prompt assembly is overwritten by the older snapshot. It is not conditional on an ephemeral counter being present: when the chat has no per-chat switches at all, the scan returns an empty map and the key is replaced with that empty map, which erases your fresh switch just the same.

The same unqueued write is what undoes the lorebook deletion cleanup that shipped in #6137. That cleanup takes the chat metadata patch queues to clear leftover switches when a book is deleted. A generation already in flight walks straight past the queue and writes the pre-delete snapshot back.

The shipped regression lane cannot see any of this, because it simulates the generation write-back with patchMetadata, which is the safe writer production does not use. The lane passes while the defect is live.

Suggested fix

Make persistLorebookRuntimeState write through chats.patchMetadata with an updater function, so it runs inside the same per-chat queue the toggle route uses. The updater should merge only the fields the scan actually computed, the ephemeral countdown and the enabled: false derived from it, into whatever is in storage at write time, per entry id, and leave every other entry's enabled exactly as storage has it. That is what chats.storage.ts:1449-1450 already tells callers to do. Nothing else calls this function, and fallbackMeta becomes unnecessary for these two keys.

While doing it, keep the two writers agreed on which key they use. The toggle route now resolves current.entryStateOverrides ?? current.lorebookEntryStateOverrides at chats.routes.ts:1400, but the write-back only ever writes entryStateOverrides, so on a chat still carrying the legacy key the generation quietly creates the modern key and changes which one the route reads from.

The fix also needs the regression lane to bite: change the scan() helper in scripts/regressions/chat-lorebook-entry-scope.regression.ts to drive the real persistLorebookRuntimeState instead of patchMetadata, and add a case that toggles an entry between the snapshot and the persist.

A second possible shape is to split the player's switch into its own metadata key so the two writers never share a blob, but that is a migration and it does not fix the resurrection of entryTimingStates.

Context

The per-chat entry switch shipped in PR #5981, which closed issue #5954. The unqueued write-back predates it, so the collision appeared when #5981 gave the key a user-facing writer. PR #6137 is involved: it touched chats.routes.ts and generate.routes.ts and it rewrote this regression lane, but it did not move the write-back off updateMetadata, and lorebook-generation-runtime.ts is not in its diff at all. #6137 also shipped the deletion cleanup for issue #6132, which this same write can undo. Related but not covering: #6126 and #6132 (both closed by #6137, both read-side or lifecycle, neither about concurrency), #2613 and #3047 (the ancestor unqueued-write issues, both closed, neither naming this function or key), and #5406 (the write-ordinal framework whose rule the code quotes). Unreleased on staging: the latest release tag is v2.4.4 and the switch landed after it, so no shipped user is hitting this yet.

Found by an AI-assisted sweep and re-verified against staging ac14dd704 on 2026-09-13. Please verify before fixing.

Originally created by @kolacheee on GitHub (Sep 13, 2026). Original GitHub issue: https://github.com/Pasta-Devs/Marinara-Engine/issues/6144 Originally assigned to: @SpicyMarinara on GitHub. If you turn a lorebook entry off (or back on) for a single chat while the app is still preparing a reply, the change is thrown away. The switch moves, the server accepts it, and then it silently flips back once the turn finishes, with no error and no toast. The entry is live again for that chat and its text shows up in the next prompt. The same window also brings back per-chat entry switches that a lorebook deletion just cleaned up, leaving switches pointing at entries that no longer exist. The window is the prompt assembly phase, not the streaming phase. Once reply text starts appearing in the bubble the change is safe. ## How to reproduce (try it yourself) 1. Open any chat that has a lorebook attached with at least one entry. The entry does not need to have fired before, and the chat does not need any existing per-chat switches. 2. Widen the window so a human can hit it: open Chat Settings, Agents, and enable a character activity agent. That agent's call runs before the lorebook state is written back in every chat mode, so it buys you a real multi-second window. The widest window of all is a Conversation chat with more than one character, group mode set to Individual, no target character picked, not impersonating, plus a pre-generation agent enabled. 3. Send a message. 4. While the progress line still reads Agents, Lorebooks, Embedding or Assembling, and before any reply text appears, open Chat Settings, Lorebooks, click the pencil on the attached book, and flip one entry's switch OFF. 5. Let the reply finish, then reopen the lorebook entry editor or reload the page. 6. Send another message containing that entry's keyword and open Peek Prompt. **What you'll see:** In step 4 the switch turns off and stays off, and the server answers 200. After the turn finishes it is back ON by itself, and in Peek Prompt the entry's text is back in the lore block. The same thing happens in the other direction: start from an entry already switched off for the chat, switch it ON inside the same window, and it reverts to off. **What should happen:** The switch you set during the turn should stick, in both directions, exactly as it does when no generation is running. Two extra checks that pin down what is going on: - Negative control: change some other chat setting inside the same window, for example the lorebook token budget. That one survives, so this is not a general metadata race, it is specific to the per-chat entry switches. - Deletion cleanup: send a message, and while the progress line still reads Agents or Lorebooks, go to Library, Lorebooks, and delete the book that chat has attached. Let the turn finish, then look at the chat with `curl -s http://127.0.0.1:7860/api/chats/<chatId> | python3 -m json.tool | grep -A4 entryStateOverrides`. The switches the deletion cleared are back, keyed to entries of a book that no longer exists. ## Where it is At staging ac14dd704: - `packages/server/src/services/generation/lorebook-generation-runtime.ts:64-79`, `persistLorebookRuntimeState`. It re-reads fresh chat metadata at :71-72 and then discards that fresh read for exactly two keys: `await args.chats.updateMetadata(args.chatId, { ...freshMeta, entryStateOverrides: args.entryStateOverrides, entryTimingStates: args.entryTimingStates })` at :73-77. - `packages/server/src/services/storage/chats.storage.ts:1440-1462`, `updateMetadata`, documented as "Whole-blob metadata replace, outside the patch queue and NOT write-ordinal stamped (#5406)", with the rule at :1449-1450: "a key that becomes package-ordered must never be written here. Move the write to `patchMetadata` rather than adding a caller on this path." - `packages/server/src/routes/chats.routes.ts:1367-1412`, `PATCH /:id/lorebook-entries/:entryId`, the user-facing writer. This one is correct: it goes through `storage.patchMetadata` at :1397-1409. - `packages/server/src/routes/generate.routes.ts:1261`, the request-start snapshot `let chatMeta = parseExtra(chat.metadata)`, and the four write-back sites at :2632, :2897, :3398 and :3879. All four run before `sendProgress("generating")` at :8720 and :8871, which is why the window ends at prompt assembly. - `packages/server/src/services/lorebook/index.ts:1295` and :1308: the returned map is a copy of the request-start snapshot, or an empty object when the chat had none, never a merge against current storage. - `scripts/regressions/chat-lorebook-entry-scope.regression.ts:88-92`: the lane's `scan()` helper persists with `chats.patchMetadata`, not with `persistLorebookRuntimeState`. ## What's happening There are two writers for the chat's per-chat lorebook entry state and they do not serialize against each other. The switch in the UI writes through the per-chat metadata patch queue, which is the safe path. The generation writes its lorebook state back through the unqueued whole-blob path, and the map it writes is a copy of the metadata it read at the very start of the request. So any switch you change between request start and the end of prompt assembly is overwritten by the older snapshot. It is not conditional on an ephemeral counter being present: when the chat has no per-chat switches at all, the scan returns an empty map and the key is replaced with that empty map, which erases your fresh switch just the same. The same unqueued write is what undoes the lorebook deletion cleanup that shipped in #6137. That cleanup takes the chat metadata patch queues to clear leftover switches when a book is deleted. A generation already in flight walks straight past the queue and writes the pre-delete snapshot back. The shipped regression lane cannot see any of this, because it simulates the generation write-back with `patchMetadata`, which is the safe writer production does not use. The lane passes while the defect is live. ## Suggested fix Make `persistLorebookRuntimeState` write through `chats.patchMetadata` with an updater function, so it runs inside the same per-chat queue the toggle route uses. The updater should merge only the fields the scan actually computed, the `ephemeral` countdown and the `enabled: false` derived from it, into whatever is in storage at write time, per entry id, and leave every other entry's `enabled` exactly as storage has it. That is what `chats.storage.ts:1449-1450` already tells callers to do. Nothing else calls this function, and `fallbackMeta` becomes unnecessary for these two keys. While doing it, keep the two writers agreed on which key they use. The toggle route now resolves `current.entryStateOverrides ?? current.lorebookEntryStateOverrides` at `chats.routes.ts:1400`, but the write-back only ever writes `entryStateOverrides`, so on a chat still carrying the legacy key the generation quietly creates the modern key and changes which one the route reads from. The fix also needs the regression lane to bite: change the `scan()` helper in `scripts/regressions/chat-lorebook-entry-scope.regression.ts` to drive the real `persistLorebookRuntimeState` instead of `patchMetadata`, and add a case that toggles an entry between the snapshot and the persist. A second possible shape is to split the player's switch into its own metadata key so the two writers never share a blob, but that is a migration and it does not fix the resurrection of `entryTimingStates`. ## Context The per-chat entry switch shipped in PR #5981, which closed issue #5954. The unqueued write-back predates it, so the collision appeared when #5981 gave the key a user-facing writer. PR #6137 is involved: it touched `chats.routes.ts` and `generate.routes.ts` and it rewrote this regression lane, but it did not move the write-back off `updateMetadata`, and `lorebook-generation-runtime.ts` is not in its diff at all. #6137 also shipped the deletion cleanup for issue #6132, which this same write can undo. Related but not covering: #6126 and #6132 (both closed by #6137, both read-side or lifecycle, neither about concurrency), #2613 and #3047 (the ancestor unqueued-write issues, both closed, neither naming this function or key), and #5406 (the write-ordinal framework whose rule the code quotes). Unreleased on staging: the latest release tag is v2.4.4 and the switch landed after it, so no shipped user is hitting this yet. Found by an AI-assisted sweep and re-verified against staging ac14dd704 on 2026-09-13. Please verify before fixing.
bsakaguchi 2026-10-21 06:02:53 +07:00
Author
Owner

@SpicyMarinara commented on GitHub (Sep 13, 2026):

Codex is addressing this report on behalf of @SpicyMarinara in draft PR #6168 as part of the requested issue sweep. I will verify the reported path against staging and preserve existing behavior outside the narrow fix.

<!-- gh-comment-id:5654637454 --> @SpicyMarinara commented on GitHub (Sep 13, 2026): Codex is addressing this report on behalf of @SpicyMarinara in draft PR #6168 as part of the requested issue sweep. I will verify the reported path against staging and preserve existing behavior outside the narrow fix.
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#3417
No description provided.