diff --git a/src/persist.ts b/src/persist.ts index 872c0cf0bc..7104e44d60 100644 --- a/src/persist.ts +++ b/src/persist.ts @@ -118,6 +118,10 @@ interface PersistedSession { }; /** Free-form escape hatch (v2+). */ metadata?: Record; + /** [#1343] Undelivered retrieve injections: the ack already promised + * delivery, so a restart restores the queue (bounded by the in-memory + * cap) instead of silently dropping it. Absent on pre-#1343 files. */ + pendingRetrievals?: CoreMessage[]; createdAt: number; // Legacy flat fields (v1). Kept optional only so buildSession can read // older files; v2 records emit grouped meta/stats instead. @@ -672,6 +676,7 @@ function buildRecord(session: Session): PersistedSession { metadata: { ...session.metadata }, state: session.state, blockContents: Object.fromEntries(session.blockContents), + pendingRetrievals: (session.pendingRetrievals?.length ?? 0) > 0 ? session.pendingRetrievals : undefined, createdAt: session.createdAt, }; } @@ -753,10 +758,18 @@ function buildSession(parsed: PersistedSession): Session { lastMessagesFolded: parsed.messagesFolded === true, inFlight: 0, persisted: true, - pendingRetrievals: [], + pendingRetrievals: Array.isArray(parsed.pendingRetrievals) + ? parsed.pendingRetrievals.filter((m): m is CoreMessage => !!m && typeof m === "object" && typeof (m as CoreMessage).text === "string") + : [], }; } +/** Test-only exposure of the persistence record builder (#1343 round-trip + * tests). */ +export function _buildRecordForTest(session: Session): PersistedSession { + return buildRecord(session); +} + function isValidRecord(parsed: unknown): parsed is PersistedSession { if (!parsed || typeof parsed !== "object") return false; const r = parsed as Partial; diff --git a/src/server.ts b/src/server.ts index 39d3befd74..45fecfbb7a 100644 --- a/src/server.ts +++ b/src/server.ts @@ -62,7 +62,7 @@ import { } from "acp-kernel/wire"; import { ABSORB_TOOL, ABSORB_TOOL_GOOGLE, ABSORB_TOOL_OPENAI, ABSORB_TOOL_RESPONSES, COMPRESS_TOOL, BILI_ACP_TOOLS_ANTHROPIC, BILI_ACP_TOOLS_GOOGLE, BILI_ACP_TOOLS_OPENAI, BILI_ACP_TOOLS_RESPONSES, BILI_ACP_READONLY_TOOLS_RESPONSES, COMPRESS_TOOL_NAME, IMAGE_FULL_TOOL, IMAGE_FULL_TOOL_GOOGLE, IMAGE_FULL_TOOL_OPENAI, IMAGE_FULL_TOOL_RESPONSES, RULE_TOOL, RULE_TOOL_GOOGLE, RULE_TOOL_OPENAI, RULE_TOOL_RESPONSES, retrieveToolsFor, buildAbsorbSystemPrompt, buildCompressSystemPrompt, buildCompressHybridSystemPrompt, withConversationIdNote, withMarkerIntegrityNote, withStagedCompressGuidance, withSummaryBudgetNote } from "./compress-tool.js"; import { applyAbsorbView, absorbEnabled, absorbToolName, storeEffectiveAbsorb } from "./absorb.js"; -import { adoptContentStore, ccrEnabled, ccrPluginWireOk, contentStoreOf, drainPendingRetrievals, executeRetrieve, retrieveToolName, storeEffectiveCcr, type CcrSettings } from "./store.js"; +import { adoptContentStore, ccrEnabled, ccrPluginWireOk, contentStoreOf, drainPendingRetrievals, executeRetrieve, requeueRetrievalsOnFailure, retrieveToolName, storeEffectiveCcr, trackRetrievalDrain, type CcrSettings } from "./store.js"; import { applyImageCompressionPass, imageCompressionEnabled, imageFullTrailingNote, storeEffectiveImageCompression, type ImageCompressionSettings } from "./image-compress.js"; import { rulesEnabled, storeEffectiveRules } from "./rules-feature.js"; import { rewriteJsonResponse, type RewriteCtx } from "./stream.js"; @@ -2668,9 +2668,13 @@ async function prepareAnthropic( await applyImageCompressionPass(session, processedMessages as BiliMessage[], { config, billing: imageBillingFor(opts, upstreamOrigin), log }); // [#1271] plugin mode: acp_retrieve ran via the tool API; ride the full original // back on this forward as a request-only trailing message (ephemeral, never persisted). + // [#1343] track the drained batch so a failed forward requeues it. if (pluginMode && ccrEnabled(session)) { const retrInj = drainPendingRetrievals(session); - if (retrInj.length > 0) processedMessages = [...processedMessages, ...retrInj]; + if (retrInj.length > 0) { + processedMessages = [...processedMessages, ...retrInj]; + trackRetrievalDrain(session, retrInj); + } } rebuiltMessages = coreToAnthropic(processedMessages as BiliMessage[], cacheControls); if (sysNotes.length > 0) { @@ -2851,9 +2855,13 @@ async function prepareOpenai( await applyImageCompressionPass(session, processedMessages as BiliMessage[], { config, billing: imageBillingFor(opts, billingUpstream ?? upstreamOrigin), log }); // [#1271] plugin mode: acp_retrieve ran via the tool API; ride the full original // back on this forward as a request-only trailing message (ephemeral, never persisted). + // [#1343] track the drained batch so a failed forward requeues it. if (pluginMode && ccrEnabled(session)) { const retrInj = drainPendingRetrievals(session); - if (retrInj.length > 0) processedMessages = [...processedMessages, ...retrInj]; + if (retrInj.length > 0) { + processedMessages = [...processedMessages, ...retrInj]; + trackRetrievalDrain(session, retrInj); + } } rebuiltMessages = systemToUser(hardenOpenaiAssistantContent(coreToOpenai(processedMessages as BiliMessage[]))); @@ -4471,6 +4479,9 @@ async function forward( // #604: a network-level failure (socket reset, timeout abort) also never // reports usage — arm the emergency shrink like the 5xx branch below. if (prepared && req.method !== "GET" && req.method !== "HEAD") armFailureShrink(prepared, log, "network failure"); + // [#1343] the drained retrieval batch never reached upstream — give it + // back to the queue so the next forward delivers the promised text. + requeueRetrievalsOnFailure(prepared?.session, "upstream network failure"); throw new Error(`upstream request failed: ${formatUpstreamError(error, upstreamUrl, proxyUrl)}`, { cause: error }); } // #552 learn-on-failure: a converting upstream that rejects a role (codex @@ -4774,6 +4785,9 @@ async function forward( // overflow path above could not have handled this response. if (prepared?.session && upstream.status >= 500) { armFailureShrink(prepared, log, `upstream ${upstream.status}`); + // [#1343] upstream rejected the request — the batch was never + // delivered; requeue for the client's retry. + requeueRetrievalsOnFailure(prepared.session, `upstream ${upstream.status}`); } // #174: always log a non-2xx upstream response (status + request-id + // body snippet) — a 4xx/5xx with zero log trace is a diagnostic diff --git a/src/session.ts b/src/session.ts index 2a92eaf12f..7cce416eeb 100644 --- a/src/session.ts +++ b/src/session.ts @@ -197,8 +197,15 @@ export type Session = { contentStoreDirty?: boolean; /** In-memory only (NOT persisted): full-text retrieval injections queued by * executeRetrieve, drained into the next re-request after the tool-result - * pair (request-only, same channel as nudges). */ + * pair (request-only, same channel as nudges). [#1343] The queue itself + * now rides the persisted session file; only the delivery ticket below + * stays transient. */ pendingRetrievals: CoreMessage[]; + /** [#1343] In-memory only (NOT persisted): the most recent drained + * retrieval batch, held between drain and forward outcome so a failed + * forward can requeue it. Any new drain clears it — a delivered batch + * must never be resurrected. */ + lastRetrievalDrain?: CoreMessage[]; /** #1095 in-memory only (NOT persisted): deterministic encode cache keyed * by sha256 of the ORIGINAL base64 → encoded payload. Identical inputs * must yield identical wire bytes across turns/restarts (prefix-cache diff --git a/src/store.ts b/src/store.ts index 6464e21175..c5512a324c 100644 --- a/src/store.ts +++ b/src/store.ts @@ -10,6 +10,7 @@ import { } from "acp-kernel"; import { log as loggerLog } from "./logger.js"; import { getStore } from "./persist.js"; +import { markDirty } from "./session.js"; import type { CompressSettings } from "./config.js"; import type { Session } from "./session.js"; @@ -27,7 +28,18 @@ export function storeEffectiveCcr(session: Session, ccr: CcrSettings | undefined // flush as a stale trailing full-text message whenever the lane re-arms at // an unrelated conversation point. Not persisted either way (#persist resets // on load) — this only tightens the in-memory window. - if (!ccr) session.pendingRetrievals.length = 0; + if (!ccr) { + // [#1343] A disarmed lane cannot deliver queued full-text injections: + // the retrieve ack already promised the text, so log the loss loudly + // instead of clearing silently. + if (session.pendingRetrievals.length > 0) { + loggerLog("warn", `[ccr] lane disarmed with ${session.pendingRetrievals.length} undelivered retrieval injection(s) (ack'd, never delivered) — dropping queue (#1343)`); + session.pendingRetrievals.length = 0; + } + // Invariant: a delivered batch must never be resurrected by an + // unrelated later forward failure once the lane re-arms (#1343). + session.lastRetrievalDrain = undefined; + } } /** Read back the CCR policy stamped by {@link storeEffectiveCcr}. */ @@ -98,6 +110,8 @@ export function adoptContentStore(session: Session, store: MessageContentStore): session.contentStoreDirty = true; } +const RETRIEVAL_QUEUE_MAX = 4; + /** Execute a retrieve-tool call against the kernel store: resolve the ref, * count hit/miss, and queue the full-text injection for the re-request path * (request-only, same channel as nudges — never persisted, structurally @@ -119,13 +133,49 @@ export function executeRetrieve(args: Record, session: Session) } session.stats.retrieveHits = (session.stats.retrieveHits ?? 0) + 1; session.state = noteRetrieval(session.state); + // [#1343] Bound the queue: a lane that never drains (non-CCR wire after a + // mode switch, or a client that stops re-requesting) must not accumulate + // full-text injections indefinitely. Oldest is dropped with a log line — + // same honest-loss shape as the disarm clear above. + if (session.pendingRetrievals.length >= RETRIEVAL_QUEUE_MAX) { + const dropped = session.pendingRetrievals.shift(); + loggerLog("warn", `[ccr] retrieval queue full (max ${RETRIEVAL_QUEUE_MAX}); dropping oldest undelivered injection ${dropped?.id ?? ""} (#1343)`); + } session.pendingRetrievals.push(result.injection); + markDirty(session); loggerLog("info", `[ccr] retrieve ${ref} (${result.entry.tokens} tok, ${result.entry.chars} chars)`); return result.ackText; } /** Drain queued retrieval injections: callers append them to the re-request - * message list AFTER the tool-result pair (ack first, full text second). */ + * message list AFTER the tool-result pair (ack first, full text second). + * [#1343] A fresh drain invalidates the previous drain's requeue ticket: + * only the most recent in-flight batch may be restored on forward failure — + * a delivered batch must never be resurrected by a later request's error. */ export function drainPendingRetrievals(session: Session): CoreMessage[] { - return session.pendingRetrievals?.length ? session.pendingRetrievals.splice(0) : []; + session.lastRetrievalDrain = undefined; + if (!session.pendingRetrievals?.length) return []; + const drained = session.pendingRetrievals.splice(0); + markDirty(session); + return drained; +} + +/** Record a drained batch as in-flight so a failed forward can requeue it + * (#1343, window 2: post-drain, pre-success). Call after appending the + * drained messages to the outgoing list. */ +export function trackRetrievalDrain(session: Session, drained: CoreMessage[]): void { + if (drained.length > 0) session.lastRetrievalDrain = drained; +} + +/** [#1343] A forward that failed before upstream accepted the request + * requeues the tracked batch: the retrieve ack already told the model the + * full text follows, so silent loss would strand the delivery contract. + * The requeued injections ride the next successful forward. */ +export function requeueRetrievalsOnFailure(session: Session | undefined, reason: string): void { + const drained = session?.lastRetrievalDrain; + if (!drained || drained.length === 0) return; + session.pendingRetrievals.unshift(...drained); + session.lastRetrievalDrain = undefined; + markDirty(session); + loggerLog("warn", `[ccr] ${reason}: requeued ${drained.length} undelivered retrieval injection(s) — they ride the next successful forward (#1343)`); } diff --git a/tests/ccr-retrieval-delivery.test.ts b/tests/ccr-retrieval-delivery.test.ts new file mode 100644 index 0000000000..6dccbfddc9 --- /dev/null +++ b/tests/ccr-retrieval-delivery.test.ts @@ -0,0 +1,147 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import { mkdtempSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import * as path from "node:path"; +import { createContentStore, storeOriginal, type CoreMessage } from "acp-kernel"; +import { SessionStore, _buildRecordForTest, _setStoreForTest } from "../src/persist.ts"; +import { + drainPendingRetrievals, + executeRetrieve, + requeueRetrievalsOnFailure, + storeEffectiveCcr, + trackRetrievalDrain, +} from "../src/store.ts"; +import { createInitialState } from "acp-kernel"; +import type { Session } from "../src/session.ts"; + +/** + * #1343: the retrieve ack promises "the full text rides the next request", + * but delivery rode volatile state with four loss windows. The fixes: + * - W1: the queue persists with the session file (restart survives); + * - W2: a failed forward requeues the drained batch (drain ticket); + * - W3: disarm drops the queue LOUDLY; + * - W4: the queue is bounded; oldest is dropped with a log line. + */ + +function freshSession(id: string): Session { + return { + id, + meta: {}, + stats: { requests: 0, tokensSaved: 0, inputTokens: 0, cachedTokens: 0, outputTokens: 0, cacheSamples: 0, lastInputTokens: 0, compressCreditTokens: 0, contextTokens: 0, retrieveCalls: 0, retrieveHits: 0, retrieveMisses: 0, storedBytes: 0, storeBytesSaved: 0, rangeRestores: 0 }, + metadata: {}, + state: createInitialState(), + createdAt: Date.now(), + lastSeen: Date.now(), + blockContents: new Map(), + inFlight: 0, + persisted: false, + pendingRetrievals: [], + }; +} + +function injection(id: string, text: string): CoreMessage { + return { id, role: "user", contentType: "text", text }; +} + +test("W2: a failed forward requeues the drained batch, in order, exactly once", () => { + _setStoreForTest(new SessionStore({ enabled: false })); + const session = freshSession("w2"); + session.pendingRetrievals.push(injection("i1", "full text one"), injection("i2", "full text two")); + + const drained = drainPendingRetrievals(session); + trackRetrievalDrain(session, drained); + assert.equal(session.pendingRetrievals.length, 0, "drained"); + + requeueRetrievalsOnFailure(session, "upstream network failure"); + assert.equal(session.pendingRetrievals.length, 2, "batch back on the queue"); + assert.equal(session.pendingRetrievals[0]!.text, "full text one", "order preserved"); + assert.equal(session.lastRetrievalDrain, undefined, "ticket consumed"); + + requeueRetrievalsOnFailure(session, "upstream 502"); + assert.equal(session.pendingRetrievals.length, 2, "second failure must not duplicate"); +}); + +test("W2 guard: a delivered batch is never resurrected by a later failure", () => { + _setStoreForTest(new SessionStore({ enabled: false })); + const session = freshSession("w2-guard"); + session.pendingRetrievals.push(injection("i1", "delivered text")); + + const delivered = drainPendingRetrievals(session); + trackRetrievalDrain(session, delivered); + // forward succeeded; next request drains again (empty) — the new drain + // must invalidate the stale ticket. + drainPendingRetrievals(session); + requeueRetrievalsOnFailure(session, "upstream 500"); + assert.equal(session.pendingRetrievals.length, 0, "delivered batch stays delivered"); +}); + +test("W2 guard: disarming invalidates the in-flight ticket (no resurrection across a lane switch)", () => { + _setStoreForTest(new SessionStore({ enabled: false })); + const session = freshSession("w2-disarm"); + session.pendingRetrievals.push(injection("i1", "delivered text")); + + const delivered = drainPendingRetrievals(session); + trackRetrievalDrain(session, delivered); + // forward succeeded; then the lane switches to a non-CCR wire and an + // unrelated later request fails before upstream accepts. + storeEffectiveCcr(session, undefined); + requeueRetrievalsOnFailure(session, "unrelated later network failure"); + assert.equal(session.pendingRetrievals.length, 0, "delivered batch stays delivered across disarm"); + assert.equal(session.lastRetrievalDrain, undefined, "ticket cleared on disarm"); +}); + +test("W3: disarming a lane with a queued batch drops it loudly (observable behavior)", () => { + _setStoreForTest(new SessionStore({ enabled: false })); + const session = freshSession("w3"); + session.pendingRetrievals.push(injection("i1", "stray text")); + storeEffectiveCcr(session, undefined); + assert.equal(session.pendingRetrievals.length, 0, "queue cleared on disarm"); + // Re-arming keeps working (no crash on empty queue). + storeEffectiveCcr(session, { enabled: true }); + assert.equal(session.pendingRetrievals.length, 0); +}); + +test("W4: the retrieval queue is bounded; oldest is dropped on overflow", () => { + _setStoreForTest(new SessionStore({ enabled: false })); + const session = freshSession("w4"); + let store = createContentStore(); + for (let i = 1; i <= 6; i++) { + store = storeOriginal(store, { ref: `m0000${i}`, rawId: `u${i}`, text: `CONTENT-${i}`, kind: "file read", tokens: 2, head: `CONTENT-${i}` }); + } + session.contentStore = store; + for (let i = 1; i <= 6; i++) { + executeRetrieve({ ref: `m0000${i}` }, session); + } + assert.equal(session.pendingRetrievals.length, 4, "queue capped at 4"); + assert.ok( + session.pendingRetrievals.every((m) => !m.text.includes("CONTENT-1") && !m.text.includes("CONTENT-2")), + "oldest dropped, newest kept", + ); +}); + +test("W1: the queue persists with the session file and survives reload", async () => { + const dir = mkdtempSync(path.join(tmpdir(), "bili-1343-")); + try { + const persist = new SessionStore({ dir, enabled: true, debounceMs: 0 }); + _setStoreForTest(persist); + const session = freshSession("w1"); + session.pendingRetrievals.push(injection("i1", "undelivered full text")); + + const record = _buildRecordForTest(session); + assert.equal(record.pendingRetrievals?.length, 1, "record carries the queue"); + assert.deepEqual(record.pendingRetrievals!.map((m) => m.text), ["undelivered full text"]); + // Empty queue writes nothing (old files stay byte-compatible). + const empty = _buildRecordForTest(freshSession("w1b")); + assert.equal(empty.pendingRetrievals, undefined); + + // Full disk round-trip: writeNow → loadSync restores the queue. + await persist.writeNow(session); + const restored = new SessionStore({ dir, enabled: true, debounceMs: 0 }).loadSync("w1"); + assert.ok(restored, "session reloaded from disk"); + assert.equal(restored!.pendingRetrievals.length, 1, "queue survives restart (#1343 W1)"); + assert.equal(restored!.pendingRetrievals[0]!.text, "undelivered full text"); + } finally { + rmSync(dir, { recursive: true, force: true }); + } +});