[GH-ISSUE #3047] [Issue]: /conversation/schedule/generate saves schedules via unqueued full-overwrite updateMetadata, clobbering concurrent metadata patches (lost update) #1614

Closed
opened 2026-10-21 05:40:48 +07:00 by bsakaguchi · 2 comments
Owner

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

Originally assigned to: @SpicyMarinara on GitHub.

What's wrong
After generating character schedules, the route saves them with chats.updateMetadata(), which does a FULL JSON overwrite of the chat's metadata column and — unlike chats.patchMetadata() — does NOT run inside the per-chat metadata patch queue. Any metadata write performed by patchMetadata during the (LLM-latency-long) generation window is silently lost. Concretely, GET /status/:chatId and POST /autonomous/check both call inheritFreshConversationSchedules(), which uses patchMetadata() to persist inherited schedules / status overrides. A status or autonomous poll that lands while /schedule/generate is mid-flight has its patched keys overwritten when generate finishes, because the final write is built from metadata read BEFORE the generation work plus a stale-snapshot schedules object, and being unqueued it isn't serialized against the patch queue at all. The cross-chat sync loop repeats the same pattern on OTHER chats.

How to reproduce (try it yourself)

  1. Open a conversation chat whose character has no fresh schedule, so the client's ensureSchedules() POSTs /conversation/schedule/generate (seconds long due to the LLM call).
  2. While that request is in flight, let the chat view's status/autonomous polling hit GET /conversation/status/:chatId or POST /conversation/autonomous/check, which run inheritFreshConversationSchedules() -> patchMetadata().
  3. Let /schedule/generate finish.

You'll see: any metadata key written by the concurrent patchMetadata after generate's pre-LLM read (an inherited schedule for another character, a status override) is gone — overwritten by the blind full-document write.
Expected: the schedule save merges onto the latest committed metadata and preserves concurrently-patched keys.

Where it is

  • packages/server/src/routes/conversation.routes.ts:538-548 (self-chat save) and 570-577 (cross-chat sync loop) — both call chats.updateMetadata.
  • Contrast: packages/server/src/services/storage/chats.storage.ts:459-465 (updateMetadata, unqueued full overwrite) vs 467-489 (patchMetadata, queued via withChatMetadataPatchQueue).
  • Concurrent writer: chats.storage.ts:340-367 inheritFreshConversationSchedules -> patchMetadata at line 360, reached from conversation.routes.ts:595, 712, 863, 903.
  • Design-intent comment documenting this exact invariant: chats.routes.ts:907-911.

What's happening
updateMetadata is a blind stringify-and-write with no compare-and-set and no queue membership, so it is not mutually exclusive with patchMetadata. The route's "re-read fresh metadata" mitigation only narrows the window — it cannot protect against patchMetadata writes that interleave after the re-read, because there are await boundaries between the read and the write and the write isn't serialized against the queue.

Suggested fix
Replace both unqueued updateMetadata calls with queued patchMetadata updaters that merge ONLY the entries this run actually changed onto freshly-read committed metadata.

Self-chat (conversation.routes.ts:538-548) — patch only the characters this run generated or shared:

const changedCharIds = Object.entries(results)
  .filter(([, r]) => r.status === "generated" || r.status === "shared")
  .map(([id]) => id);
if (changedCharIds.length > 0) {
  await chats.patchMetadata(chatId, (current) => {
    const currentSchedules = hasSchedules(current.characterSchedules) ? (current.characterSchedules as CharacterSchedules) : {};
    const mergedSchedules: CharacterSchedules = { ...currentSchedules };
    for (const id of changedCharIds) mergedSchedules[id] = newSchedules[id]!;
    return { conversationSchedulesEnabled: true, characterSchedules: mergedSchedules, scheduleWeekStart: mondayStr };
  });
}

Cross-chat sync (conversation.routes.ts:570-577) — re-merge inside the queue against each chat's fresh metadata, layering only the overlapping entries:

if (changed) {
  await chats.patchMetadata(c.id, (currentC) => {
    const cur = hasSchedules(currentC.characterSchedules) ? (currentC.characterSchedules as CharacterSchedules) : {};
    const next: CharacterSchedules = { ...cur };
    for (const cid of overlap) next[cid] = preserveTimingSettings(newSchedules[cid]!, cur[cid] ?? cSchedules[cid]);
    return { conversationSchedulesEnabled: true, characterSchedules: next, scheduleWeekStart: mondayStr };
  });
}

Regression note (important): do NOT spread ...newSchedules wholesale into the merge as the naive fix would. newSchedules is seeded as a stale snapshot read at request start, and characters whose schedule was "fresh" and skipped keep that stale value — spreading it last would re-clobber any newer per-character schedule a concurrent writer committed during the LLM window, reintroducing a narrower form of the same lost update. Merge only the run's actually-produced/overlapping entries onto current. mergeMetadataPatch is a shallow top-level spread, so omitted top-level keys are preserved automatically. This mirrors the canonical pattern at chats.routes.ts:906-924 (/summaries route).


AI-investigated against v2.0.6; cited lines read and confirmed. Please verify before fixing.

Originally created by @kolacheee on GitHub (Jun 29, 2026). Original GitHub issue: https://github.com/Pasta-Devs/Marinara-Engine/issues/3047 Originally assigned to: @SpicyMarinara on GitHub. **What's wrong** After generating character schedules, the route saves them with `chats.updateMetadata()`, which does a FULL JSON overwrite of the chat's metadata column and — unlike `chats.patchMetadata()` — does NOT run inside the per-chat metadata patch queue. Any metadata write performed by `patchMetadata` during the (LLM-latency-long) generation window is silently lost. Concretely, GET /status/:chatId and POST /autonomous/check both call `inheritFreshConversationSchedules()`, which uses `patchMetadata()` to persist inherited schedules / status overrides. A status or autonomous poll that lands while /schedule/generate is mid-flight has its patched keys overwritten when generate finishes, because the final write is built from metadata read BEFORE the generation work plus a stale-snapshot schedules object, and being unqueued it isn't serialized against the patch queue at all. The cross-chat sync loop repeats the same pattern on OTHER chats. **How to reproduce (try it yourself)** 1. Open a conversation chat whose character has no fresh schedule, so the client's `ensureSchedules()` POSTs /conversation/schedule/generate (seconds long due to the LLM call). 2. While that request is in flight, let the chat view's status/autonomous polling hit GET /conversation/status/:chatId or POST /conversation/autonomous/check, which run `inheritFreshConversationSchedules()` -> `patchMetadata()`. 3. Let /schedule/generate finish. You'll see: any metadata key written by the concurrent `patchMetadata` after generate's pre-LLM read (an inherited schedule for another character, a status override) is gone — overwritten by the blind full-document write. Expected: the schedule save merges onto the latest committed metadata and preserves concurrently-patched keys. **Where it is** - `packages/server/src/routes/conversation.routes.ts:538-548` (self-chat save) and `570-577` (cross-chat sync loop) — both call `chats.updateMetadata`. - Contrast: `packages/server/src/services/storage/chats.storage.ts:459-465` (`updateMetadata`, unqueued full overwrite) vs `467-489` (`patchMetadata`, queued via `withChatMetadataPatchQueue`). - Concurrent writer: `chats.storage.ts:340-367` `inheritFreshConversationSchedules` -> `patchMetadata` at line 360, reached from conversation.routes.ts:595, 712, 863, 903. - Design-intent comment documenting this exact invariant: `chats.routes.ts:907-911`. **What's happening** `updateMetadata` is a blind stringify-and-write with no compare-and-set and no queue membership, so it is not mutually exclusive with `patchMetadata`. The route's "re-read fresh metadata" mitigation only narrows the window — it cannot protect against `patchMetadata` writes that interleave after the re-read, because there are await boundaries between the read and the write and the write isn't serialized against the queue. **Suggested fix** Replace both unqueued `updateMetadata` calls with queued `patchMetadata` updaters that merge ONLY the entries this run actually changed onto freshly-read committed metadata. Self-chat (conversation.routes.ts:538-548) — patch only the characters this run generated or shared: ```ts const changedCharIds = Object.entries(results) .filter(([, r]) => r.status === "generated" || r.status === "shared") .map(([id]) => id); if (changedCharIds.length > 0) { await chats.patchMetadata(chatId, (current) => { const currentSchedules = hasSchedules(current.characterSchedules) ? (current.characterSchedules as CharacterSchedules) : {}; const mergedSchedules: CharacterSchedules = { ...currentSchedules }; for (const id of changedCharIds) mergedSchedules[id] = newSchedules[id]!; return { conversationSchedulesEnabled: true, characterSchedules: mergedSchedules, scheduleWeekStart: mondayStr }; }); } ``` Cross-chat sync (conversation.routes.ts:570-577) — re-merge inside the queue against each chat's fresh metadata, layering only the overlapping entries: ```ts if (changed) { await chats.patchMetadata(c.id, (currentC) => { const cur = hasSchedules(currentC.characterSchedules) ? (currentC.characterSchedules as CharacterSchedules) : {}; const next: CharacterSchedules = { ...cur }; for (const cid of overlap) next[cid] = preserveTimingSettings(newSchedules[cid]!, cur[cid] ?? cSchedules[cid]); return { conversationSchedulesEnabled: true, characterSchedules: next, scheduleWeekStart: mondayStr }; }); } ``` Regression note (important): do NOT spread `...newSchedules` wholesale into the merge as the naive fix would. `newSchedules` is seeded as a stale snapshot read at request start, and characters whose schedule was "fresh" and skipped keep that stale value — spreading it last would re-clobber any newer per-character schedule a concurrent writer committed during the LLM window, reintroducing a narrower form of the same lost update. Merge only the run's actually-produced/overlapping entries onto `current`. `mergeMetadataPatch` is a shallow top-level spread, so omitted top-level keys are preserved automatically. This mirrors the canonical pattern at chats.routes.ts:906-924 (/summaries route). --- *AI-investigated against v2.0.6; cited lines read and confirmed. Please verify before fixing.*
Author
Owner

@SpicyMarinara commented on GitHub (Jun 29, 2026):

Claiming this for the current staging sweep in draft PR #3053 (branch codex/issue-sweep-3033-3052).

<!-- gh-comment-id:4834990108 --> @SpicyMarinara commented on GitHub (Jun 29, 2026): Claiming this for the current staging sweep in draft PR #3053 (branch `codex/issue-sweep-3033-3052`).
Author
Owner

@SpicyMarinara commented on GitHub (Jun 29, 2026):

Fixed in PR #3053 on branch codex/issue-sweep-3033-3052 (commit bfb1bc76). Closing this issue as addressed; the PR remains open for staging review/merge.

<!-- gh-comment-id:4835090150 --> @SpicyMarinara commented on GitHub (Jun 29, 2026): Fixed in PR #3053 on branch `codex/issue-sweep-3033-3052` (commit bfb1bc76). Closing this issue as addressed; the PR remains open for staging review/merge.
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#1614
No description provided.