[GH-ISSUE #2991] [Issue]: A throwing lorebook-keeper retry discards all already-computed tracker/CYOA/rewrite results (missing error isolation) #1563

Closed
opened 2026-10-21 05:39:14 +07:00 by bsakaguchi · 1 comment
Owner

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

Originally assigned to: @SpicyMarinara on GitHub.

What's wrong
On the retry path, the non-lorebook agents run first and produce results, but those results are only applied to the chat much later. In between, the lorebook-keeper stage runs with no error isolation. If the keeper's DB work throws (a lorebook write error, disk error, etc.), the rejection propagates to the route's single outer catch, which only emits an error event. As a result the apply step is never reached, and every non-lorebook agent that already SUCCEEDED (rewrites, world-state/character/persona/quest/custom trackers, CYOA, illustrator, sprites) is silently dropped — never applied, never saved as run history, never even streamed.

How to reproduce (try it yourself)

  1. Configure a chat with a lorebook-keeper agent plus at least one tracker/CYOA/rewrite agent.
  2. Trigger a retry of those agent types (POST /retry-agents with both agentTypes).
  3. Have the lorebook persistence layer throw during the keeper run (e.g. a lorebook store write/disk error inside persistLorebookKeeperUpdates).

You'll see: the SSE stream ends with type:"error"; the tracker/CYOA/rewrite effects already computed are never applied.
Expected: a keeper persistence failure should not discard unrelated, already-successful agent results.

Where it is
packages/server/src/routes/generate/retry-agents-route.ts:3174-3188 (unguarded executeLorebookKeeperRetries call) before :3301 (persistRetryResults) and :3314 (applyRetryResultEffects); throw sources at :2131 and :2162. The other stages (executeRetryBatches per-group catch, persistRetryResults per-result catch, applyRetryResultEffects per-result catch) are isolated; only the keeper stage is not.

What's happening
executeLorebookKeeperRetries (which includes DB persistence) is sequenced before applyRetryResultEffects inside one shared try block and is not isolated. Its failure aborts application of unrelated, already-successful results.

Suggested fix
Wrap the keeper stage in its own try/catch so a keeper DB failure cannot abort applying the non-lorebook results, AND emit an agent_error SSE inside the catch (matching the existing illustrator failure pattern) so a real keeper failure stays visible — important for the keeper-only retry case. Replace the unguarded call at lines 3174-3188:

let rawLorebookKeeperRunEntries: Array<{ messageId: string; result: AgentResult }> = [];
if (lorebookKeeperAgent) {
  try {
    rawLorebookKeeperRunEntries = await executeLorebookKeeperRetries({
      lorebookKeeperAgent,
      baseContext: agentContext,
      messages: recentMessages,
      readBehindMessages: getLorebookKeeperSettings(chatMeta).readBehindMessages,
      lastProcessedMessageId:
        (await agentsStore.getLastSuccessfulRunByType("lorebook-keeper", chatId))?.messageId ?? null,
      backfillUnprocessed: lorebookKeeperBackfill,
      lorebooksStore,
      chatId,
      chatName: (chat as any).name,
      requireApproval: requireAgentWriteApproval,
    });
  } catch (err) {
    logger.error(err, "[retry-agents] Lorebook Keeper retry failed; applying other agent results");
    sendSseEvent(reply, {
      type: "agent_error",
      data: {
        agentType: "lorebook-keeper",
        agentName: lorebookKeeperAgent.cfg?.name ?? "Lorebook Keeper",
        error: err instanceof Error ? err.message : "Lorebook Keeper failed",
      },
    });
  }
}

Regression avoided: the literal suggested fix ("continue with an empty entries array", i.e. logger.error-only swallow) would make a genuine keeper failure invisible — in the keeper-only retry case the route would stream a misleading done. Adding the agent_error SSE keeps the failure visible. The keeper's return value is consumed only in keeper-only spots that safely no-op on [], and the keeper mutates only per-target context clones, so swallowing leaves no corrupt state.


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/2991 Originally assigned to: @SpicyMarinara on GitHub. **What's wrong** On the retry path, the non-lorebook agents run first and produce results, but those results are only applied to the chat much later. In between, the lorebook-keeper stage runs with no error isolation. If the keeper's DB work throws (a lorebook write error, disk error, etc.), the rejection propagates to the route's single outer catch, which only emits an error event. As a result the apply step is never reached, and every non-lorebook agent that already SUCCEEDED (rewrites, world-state/character/persona/quest/custom trackers, CYOA, illustrator, sprites) is silently dropped — never applied, never saved as run history, never even streamed. **How to reproduce (try it yourself)** 1. Configure a chat with a lorebook-keeper agent plus at least one tracker/CYOA/rewrite agent. 2. Trigger a retry of those agent types (POST /retry-agents with both agentTypes). 3. Have the lorebook persistence layer throw during the keeper run (e.g. a lorebook store write/disk error inside persistLorebookKeeperUpdates). You'll see: the SSE stream ends with `type:"error"`; the tracker/CYOA/rewrite effects already computed are never applied. Expected: a keeper persistence failure should not discard unrelated, already-successful agent results. **Where it is** `packages/server/src/routes/generate/retry-agents-route.ts:3174-3188` (unguarded `executeLorebookKeeperRetries` call) before `:3301` (persistRetryResults) and `:3314` (applyRetryResultEffects); throw sources at `:2131` and `:2162`. The other stages (executeRetryBatches per-group catch, persistRetryResults per-result catch, applyRetryResultEffects per-result catch) are isolated; only the keeper stage is not. **What's happening** `executeLorebookKeeperRetries` (which includes DB persistence) is sequenced before `applyRetryResultEffects` inside one shared try block and is not isolated. Its failure aborts application of unrelated, already-successful results. **Suggested fix** Wrap the keeper stage in its own try/catch so a keeper DB failure cannot abort applying the non-lorebook results, AND emit an `agent_error` SSE inside the catch (matching the existing illustrator failure pattern) so a real keeper failure stays visible — important for the keeper-only retry case. Replace the unguarded call at lines 3174-3188: ```ts let rawLorebookKeeperRunEntries: Array<{ messageId: string; result: AgentResult }> = []; if (lorebookKeeperAgent) { try { rawLorebookKeeperRunEntries = await executeLorebookKeeperRetries({ lorebookKeeperAgent, baseContext: agentContext, messages: recentMessages, readBehindMessages: getLorebookKeeperSettings(chatMeta).readBehindMessages, lastProcessedMessageId: (await agentsStore.getLastSuccessfulRunByType("lorebook-keeper", chatId))?.messageId ?? null, backfillUnprocessed: lorebookKeeperBackfill, lorebooksStore, chatId, chatName: (chat as any).name, requireApproval: requireAgentWriteApproval, }); } catch (err) { logger.error(err, "[retry-agents] Lorebook Keeper retry failed; applying other agent results"); sendSseEvent(reply, { type: "agent_error", data: { agentType: "lorebook-keeper", agentName: lorebookKeeperAgent.cfg?.name ?? "Lorebook Keeper", error: err instanceof Error ? err.message : "Lorebook Keeper failed", }, }); } } ``` Regression avoided: the literal suggested fix ("continue with an empty entries array", i.e. logger.error-only swallow) would make a genuine keeper failure invisible — in the keeper-only retry case the route would stream a misleading `done`. Adding the `agent_error` SSE keeps the failure visible. The keeper's return value is consumed only in keeper-only spots that safely no-op on `[]`, and the keeper mutates only per-target context clones, so swallowing leaves no corrupt state. --- *AI-investigated against v2.0.6; cited lines read and confirmed. Please verify before fixing.*
Author
Owner

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

Fixed in merged staging PR #3004.

<!-- gh-comment-id:4832280692 --> @SpicyMarinara commented on GitHub (Jun 29, 2026): Fixed in merged staging PR #3004.
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#1563
No description provided.