diff --git a/PLUGIN.md b/PLUGIN.md index 91b328fb72..9549833bb2 100644 --- a/PLUGIN.md +++ b/PLUGIN.md @@ -180,7 +180,7 @@ Discover `capabilities.fork` from the manifest; do not infer support from the pa } ``` -`messages` is in exactly the same order as `orderedMessages`, describes the raw `pluginSnapshot` rather than a folded view, and includes optional `text`, `toolName`, and `toolCallId`. Compare original text and role to establish the longest matching prefix; tool identities/content type must match too. Copy the corresponding ordered identities verbatim; `identityHash` and revisions are opaque and clients do not need a content-hash algorithm. A message the kernel hard-excludes from compression (`compress.protectedTools`) carries `"ref": null` in both arrays — it participates in ordering and identity but has no addressable ref; copy it verbatim like any other prefix entry. Only `mNNNNN` strings or `null` are legal ref values. Multimodal/opaque content that cannot be verified by this text projection returns `409`, `status: unavailable`, `code: SNAPSHOT_UNAVAILABLE`, not a guessed text match. Missing raw snapshots or inconsistent raw/ref/CCR mappings likewise fail closed. Raw snapshot retention is capped (`BILI_PUBLIC_SNAPSHOT_CAP_BYTES`, default 16 MiB, `0` disables): a session whose serialized raw snapshot grows past the cap stops being forkable — snapshot/fork answer `409 SNAPSHOT_UNAVAILABLE` — instead of retaining an unbounded raw copy forever. +`messages` is in exactly the same order as `orderedMessages`, describes the raw source view (the retained `pluginSnapshot`, or the session's most recent raw request view when no retained copy exists — never a folded view), and includes optional `text`, `toolName`, and `toolCallId`. Compare original text and role to establish the longest matching prefix; tool identities/content type must match too. Copy the corresponding ordered identities verbatim; `identityHash` and revisions are opaque and clients do not need a content-hash algorithm. A message the kernel hard-excludes from compression (`compress.protectedTools`) carries `"ref": null` in both arrays — it participates in ordering and identity but has no addressable ref; copy it verbatim like any other prefix entry. Only `mNNNNN` strings or `null` are legal ref values. Multimodal/opaque content that cannot be verified by this text projection returns `409`, `status: unavailable`, `code: SNAPSHOT_UNAVAILABLE`, not a guessed text match. When neither a retained copy nor a recent raw view exists, or the raw/ref/CCR mappings are inconsistent, the endpoint likewise fails closed with `409 SNAPSHOT_UNAVAILABLE`. That code is RETRYABLE: the condition clears on the parent's next model request (and the recent-raw-view source makes it rare after any traffic at all), so clients must retry on later requests instead of giving up inheritance permanently (#3011). Raw snapshot retention is capped (`BILI_PUBLIC_SNAPSHOT_CAP_BYTES`, default 16 MiB, `0` disables): a session whose serialized raw snapshot grows past the cap stops being forkable — snapshot/fork answer `409 SNAPSHOT_UNAVAILABLE` — instead of retaining an unbounded raw copy forever. `POST /__bili/plugin/fork` body: diff --git a/src/agent/fork-adopt.ts b/src/agent/fork-adopt.ts index 6d3b65b70f..01b6a3609d 100644 --- a/src/agent/fork-adopt.ts +++ b/src/agent/fork-adopt.ts @@ -59,7 +59,11 @@ type SnapshotResponse = { type ForkAdoptionResult = | { outcome: "adopted"; branchPoint: number; replayed: boolean } - | { outcome: "degraded"; reason: string }; + // #3011: retryable carries the server's structured verdict (its error + // code / status class), NOT a re-parse of the reason string — the old + // regex /^(snapshot|fork) (error|http 5\d\d)/ missed the proxy's own + // documented-retryable 409 SNAPSHOT_UNAVAILABLE and gave up forever. + | { outcome: "degraded"; reason: string; retryable: boolean }; function forkStableJson(value: unknown): string { if (Array.isArray(value)) return `[${value.map(forkStableJson).join(",")}]`; @@ -401,7 +405,12 @@ async function readBoundedErrorBody(res: Response): Promise<{ code: string; erro * failure path returns { outcome: "degraded" } — the child then simply starts * a fresh conversation, exactly today's behavior; adoption is best effort. * A 409 PARENT_REVISION_CONFLICT (parent mutated between snapshot and fork) - * is retried once with a fresh snapshot before degrading. + * is retried once with a fresh snapshot before degrading. Degraded results + * carry `retryable` (#3011): whether a LATER attempt can succeed — network / + * 5xx / 409 SNAPSHOT_UNAVAILABLE are states the parent can outlive (a fresh + * parent request re-establishes its raw view); deterministic 4xx verdicts + * (unknown parent, diverged prefix, conflicting child) cannot change in this + * process. Consumers classify by the field, never by the reason text. */ export async function tryForkAdoption(opts: { base: string; @@ -418,10 +427,10 @@ export async function tryForkAdoption(opts: { // projected above with pinned parity (#2469 stage 2). const wire = detectWireFormat(opts.body); if (wire === "google") { - return { outcome: "degraded", reason: `wire unsupported (${wire})` }; + return { outcome: "degraded", reason: `wire unsupported (${wire})`, retryable: false }; } const core = chatBodyToCore(opts.body); - if (core === null || core.length === 0) return { outcome: "degraded", reason: "body unmappable" }; + if (core === null || core.length === 0) return { outcome: "degraded", reason: "body unmappable", retryable: true }; const snapshotUrl = `${opts.base}/__bili/plugin/snapshot?conversationId=${encodeURIComponent(opts.parentConversationId)}`; for (let attempt = 0; attempt < 2; attempt += 1) { let snapshot: Awaited>; @@ -432,15 +441,21 @@ export async function tryForkAdoption(opts: { // SNAPSHOT_UNAVAILABLE + why) instead of hiding them behind a // bare status code. const detail = await readBoundedErrorBody(res); - return { outcome: "degraded", reason: `snapshot http ${res.status}${detail.code ? ` ${detail.code}` : ""}${detail.error ? ` (${detail.error})` : ""}` }; + // #3011: classify by the proxy's structured verdict, not by + // re-parsing the reason string. 5xx and 409 + // SNAPSHOT_UNAVAILABLE are conditions the parent can outlive + // (a fresh parent request re-establishes its raw view); every + // other 4xx names a state this process cannot fix. + const retryable = res.status >= 500 || (res.status === 409 && detail.code === "SNAPSHOT_UNAVAILABLE"); + return { outcome: "degraded", reason: `snapshot http ${res.status}${detail.code ? ` ${detail.code}` : ""}${detail.error ? ` (${detail.error})` : ""}`, retryable }; } snapshot = snapshotOf(await res.json()); } catch (err) { - return { outcome: "degraded", reason: `snapshot error ${err instanceof Error ? err.message : String(err)}` }; + return { outcome: "degraded", reason: `snapshot error ${err instanceof Error ? err.message : String(err)}`, retryable: true }; } - if (snapshot === null) return { outcome: "degraded", reason: "snapshot malformed" }; + if (snapshot === null) return { outcome: "degraded", reason: "snapshot malformed", retryable: false }; const branchPoint = matchForkPrefix(core, snapshot.orderedMessages); - if (branchPoint === 0) return { outcome: "degraded", reason: "no prefix match" }; + if (branchPoint === 0) return { outcome: "degraded", reason: "no prefix match", retryable: false }; const prefix = snapshot.orderedMessages.slice(0, branchPoint); const orderHash = branchPoint === snapshot.orderedMessages.length ? snapshot.orderHash : forkOrderHashOf(prefix); const payload = { @@ -461,7 +476,7 @@ export async function tryForkAdoption(opts: { signal: AbortSignal.timeout(FORK_TIMEOUT_MS), }); } catch (err) { - return { outcome: "degraded", reason: `fork error ${err instanceof Error ? err.message : String(err)}` }; + return { outcome: "degraded", reason: `fork error ${err instanceof Error ? err.message : String(err)}`, retryable: true }; } if (res.status === 201 || res.status === 200) { let replayed = false; @@ -479,9 +494,12 @@ export async function tryForkAdoption(opts: { opts.log?.(`fork for ${opts.childConversationId} hit parent revision conflict, retrying once with a fresh snapshot (#2399)`); continue; } - return { outcome: "degraded", reason: `fork http ${res.status}${code ? ` ${code}` : ""}` }; + // CHILD_CONFLICT / PARENT_STATE_INCOMPLETE / BRANCH_POINT_CONFLICT and + // friends are deterministic verdicts about THIS child's state — only + // 5xx can still change under a later attempt (#3011). + return { outcome: "degraded", reason: `fork http ${res.status}${code ? ` ${code}` : ""}`, retryable: res.status >= 500 }; } - return { outcome: "degraded", reason: "parent revision conflict retry exhausted" }; + return { outcome: "degraded", reason: "parent revision conflict retry exhausted", retryable: false }; } const forkCapabilityCache = new Map(); @@ -576,15 +594,21 @@ export function createForkAdopter(log: (line: string) => void, opts?: { maxAttem done.add(input.child); return; } - log(`fork adoption for ${input.child} degraded (${result.reason}) — the session continues without inherited compression state (#2399/#2469)`); - // Only transient failures (network / 5xx / unmappable body) leave the - // window open so a later request retries up to maxAttempts; every other - // outcome is terminal. Once this child's stamped request has landed, a - // retry can only ever meet CHILD_CONFLICT (the server registers the - // child conversation before any later fork POST), which latches here as - // a non-transient outcome (#2403 review). - const transient = /^(snapshot|fork) (error|http 5\d\d)/.test(result.reason) || result.reason === "body unmappable"; - if (!transient || (attempts.get(input.child) ?? 0) >= maxAttempts) done.add(input.child); + // #3011: classify by the server's structured verdict on the result + // (retryable), never by re-parsing the reason string — the old regex + // missed 409 SNAPSHOT_UNAVAILABLE and gave up after one attempt. + // Transient outcomes leave the window open for later requests up to + // maxAttempts; every other outcome is terminal. Once this child's + // stamped request has landed, a retry can only ever meet + // CHILD_CONFLICT (the server registers the child conversation before + // any later fork POST), which latches here as non-retryable (#2403). + const exhausted = !result.retryable || (attempts.get(input.child) ?? 0) >= maxAttempts; + if (exhausted) { + log(`fork adoption for ${input.child} degraded (${result.reason}) — permanently disabled, no further retries in this process; the session continues without inherited compression state (#3011/#2399/#2469)`); + done.add(input.child); + } else { + log(`fork adoption for ${input.child} degraded (${result.reason}) — transient, will retry on a later request (attempt ${attempts.get(input.child)}/${maxAttempts}); the session continues without inherited compression state until adopted (#3011/#2399/#2469)`); + } }; return { async maybeAdopt(input): Promise { diff --git a/src/plugin.ts b/src/plugin.ts index f570106ab2..35829e5695 100644 --- a/src/plugin.ts +++ b/src/plugin.ts @@ -1214,6 +1214,36 @@ function sessionRevisionOf(session: Session): string { return revision; } +/** #3011: pick the raw view forkSnapshot serves. pluginSnapshot is the + * canonical guarded copy (#2077), but it is only PERSISTED after a fork + * receipt or explicit retention — any residency gap (LRU evict / host + * restart) loses it until the parent's next model request, which is exactly + * when a fork child needs it most (the child's adoption window precedes its + * first forwarded request). session.lastMessages — written by EVERY prepare* + * with the raw incoming view and persisted unconditionally — covers that + * gap. It also wins when its head diverges from a stale snapshot: after a + * full-cover native compaction the zero-overlap guard freezes pluginSnapshot + * pre-compaction while the state rebase re-issues the refs, so serving the + * stale copy fails closed on "raw/ref mapping inconsistent" forever; the + * head-divergent tail is the freshest raw view the client will replay next. + * A folded tail (lastMessagesFolded) is never a raw source. An EMPTY retained + * copy is still a valid source: a zero-branchpoint fork child legitimately + * holds pluginSnapshot === [] and its own forkSnapshot() (childRevision) must + * serve that emptiness, not report "unavailable". When neither in-memory + * view survived (shadow-mode cold restore, #5140), the verified storage + * reconstruction below is the last rung — same fail-closed contract. */ +function forkSourceMessages(session: Session): { messages: CoreMessage[]; fromTail: boolean } | null { + const primary = Array.isArray(session.pluginSnapshot) ? session.pluginSnapshot : undefined; + const tail = session.lastMessages && session.lastMessagesFolded !== true && session.lastMessages.length > 0 ? session.lastMessages : undefined; + if (!primary) { + if (tail) return { messages: tail, fromTail: true }; + const rebuilt = reconstructRawTailForFork(session); + return rebuilt ? { messages: rebuilt, fromTail: true } : null; + } + if (tail && primary.length > 0 && forkMessageIdentityHash(tail[0]!) !== forkMessageIdentityHash(primary[0]!)) return { messages: tail, fromTail: true }; + return { messages: primary, fromTail: false }; +} + /** #5140 item 4: a non-retained parent cold-restored in shadow mode loses its * resident pluginSnapshot (persist.ts retention gate) even though index.db * still holds the independently recorded unfolded raw tail. Rebuild that tail @@ -1294,15 +1324,21 @@ function reconstructRawTailForFork(session: Session): CoreMessage[] | null { } function forkSnapshot(session: Session, source?: CoreMessage[] | null) { - const messages = source ?? session.pluginSnapshot ?? reconstructRawTailForFork(session); - if (!messages) { - const capped = session.metadata.publicSnapshotCapped === true; - const base = capped ? "raw snapshot exceeded the retention cap (BILI_PUBLIC_SNAPSHOT_CAP_BYTES); fork is refused rather than retaining an unbounded raw copy" : "raw snapshot unavailable; send a fresh plugin model request"; - // the capped base names the refusal itself; a gate recorded under it is - // incidental (reconstruction may bail before reaching the cap check) - const why = capped ? undefined : reconMissReason(session.id); + // The retention cap stays a hard refusal even when a recent raw view is + // available: serving around it would make the cap unenforceable (#2433). + if (session.metadata.publicSnapshotCapped === true) throw new Error("raw snapshot exceeded the retention cap (BILI_PUBLIC_SNAPSHOT_CAP_BYTES); fork is refused rather than retaining an unbounded raw copy"); + // An explicitly passed view (the fork handler's pre-computed source) wins + // outright; otherwise the picker cascades retained copy -> recent raw view + // -> verified storage reconstruction. An explicit view IS the retained + // copy only by identity — any other served view is non-resident and skips + // the retained-copy bookkeeping below. + const picked = source ? { messages: source, fromTail: source !== session.pluginSnapshot } : forkSourceMessages(session); + if (!picked) { + const base = "raw snapshot unavailable; send a fresh plugin model request"; + const why = reconMissReason(session.id); throw new Error(why ? `${base} [reconstruction: ${why}]` : base); } + const messages = picked.messages; // #4266 mechanism 1: signed thinking is no longer an opaque refusal. Wire // thinking/redacted_thinking blocks project to a named reasoning message // (anthropicToCore), so they are comparable by view. The host-projected @@ -1316,7 +1352,10 @@ function forkSnapshot(session: Session, source?: CoreMessage[] | null) { if (session.metadata.publicSnapshotTextComparable === false) throw new Error("multimodal or opaque content cannot be compared by text"); const store = contentStoreOf(session); const expectedStoredRefs = session.metadata.publicSnapshotStoredRefs; - if (Array.isArray(expectedStoredRefs) && expectedStoredRefs.some((ref) => typeof ref !== "string" || !store.byRef[ref])) throw new Error("CCR original index unavailable"); + // The stored-ref list is bookkeeping for the RETAINED copy; on the tail + // path it describes a different (older or reset) view, so only the + // per-message CCR checks below apply to what is actually served (#3011). + if (!picked.fromTail && Array.isArray(expectedStoredRefs) && expectedStoredRefs.some((ref) => typeof ref !== "string" || !store.byRef[ref])) throw new Error("CCR original index unavailable"); const indexedHashes = new Set(Object.values(store.byRef).map((entry) => entry.hash)); if (Object.entries(store.byHash).some(([hash, text]) => !indexedHashes.has(hash) || typeof text !== "string" || createHash("sha256").update(text, "utf8").digest("hex") !== hash)) throw new Error("CCR original payload/index inconsistent"); if (Object.entries(store.byRef).some(([ref, entry]) => typeof store.byHash[entry.hash] !== "string" || (session.state.messageRefs.byRaw[entry.rawId] !== undefined && (session.state.messageRefs.byRaw[entry.rawId] !== ref || session.state.messageRefs.byRef[ref] !== entry.rawId)))) throw new Error("CCR original alias inconsistent"); @@ -1580,11 +1619,17 @@ export async function handlePluginFork(payload: string, res: ServerResponse): Pr await withSessionLock(parent, async () => { if (await replay()) return; if (conversations.has(request.childConversationId) || pendingRegisters.some((r) => r.conversationId === request.childConversationId) || (registeredIds.has(request.childConversationId) && !forkChildHeldBySameParent(request.childConversationId, request.parentConversationId))) return forkReply(res, 409, { ok: false, code: "CHILD_CONFLICT", error: "child conversation already registered" }); - // #5140 item 4: a cold non-retained parent has no resident snapshot; - // stand in with the verified unified raw tail (no fresh model call). - const source = parent.pluginSnapshot ?? reconstructRawTailForFork(parent); + // #3011/#5140: the child's raw baseline must come from the SAME source + // view the snapshot is served from — retained copy, recent raw view, + // or verified storage reconstruction (residency gaps lose the first; + // shadow-mode cold restores can leave none until the next model call). + const source = forkSourceMessages(parent); + if (!source) { + const why = reconMissReason(parent.id); + return forkReply(res, 409, { ok: false, status: "unavailable", code: "SNAPSHOT_UNAVAILABLE", error: why ? `raw snapshot unavailable; send a fresh plugin model request [reconstruction: ${why}]` : "raw snapshot unavailable; send a fresh plugin model request" }); + } let snapshot: ReturnType; - try { snapshot = forkSnapshot(parent, source); } + try { snapshot = forkSnapshot(parent, source.messages); } catch (err) { return forkReply(res, 409, { ok: false, status: "unavailable", code: "SNAPSHOT_UNAVAILABLE", error: String(err) }); } if (snapshot.parentRevision !== request.parentRevision) { // #2671 Phase 2b: accept a stale v1 revision (whole-store hash) from @@ -1654,7 +1699,7 @@ export async function handlePluginFork(payload: string, res: ServerResponse): Pr child.state.stats.tokensCompressed = child.state.blocks.filter((b) => b.active).reduce((sum, b) => sum + b.compressedTokens, 0); child.state.stats.compressionCount = blocks.length; if (prefix.length === snapshot.orderedMessages.length) child.state.nudge = structuredClone(parent.state.nudge); - child.pluginSnapshot = structuredClone(source!.slice(0, request.branchPoint.messageCount)); + child.pluginSnapshot = structuredClone(source.messages.slice(0, request.branchPoint.messageCount)); const forkView = prune(child.pluginSnapshot, child.state); // Hiding the original pair is safe only if its summary survives the fork. child.state.absorbed = structuredClone(parent.state.absorbed?.filter((a) => @@ -1721,10 +1766,11 @@ export async function handlePluginFork(payload: string, res: ServerResponse): Pr // lazily-persisted parent would drop its snapshot on disk and the next // restart would 409. Flush eagerly (publishForkSession precedent) so // the flag and the snapshot land in one write. - // #5140 item 4: only a SUCCESSFUL fork retains the verified source — - // materialize the reconstructed tail on the parent so the flushSync + // #5140 item 4 / #3011: only a SUCCESSFUL fork retains the served source — + // when it came from a non-resident view (recent raw tail or verified + // storage reconstruction), materialize it on the parent so the flushSync // below persists the real raw copy for continuity (GET never does). - if (source && source !== parent.pluginSnapshot) parent.pluginSnapshot = structuredClone(source); + if (source.fromTail) parent.pluginSnapshot = structuredClone(source.messages); parent.metadata.publicSnapshotRetained = true; if (!getStore().flushSync(parent)) loggerLog("warn", `fork ${request.childConversationId}: parent snapshot flush failed (${parent.id}); the debounced save will retry`); forkReply(res, 201, response); diff --git a/src/session.ts b/src/session.ts index b3a2723627..68026a292f 100644 --- a/src/session.ts +++ b/src/session.ts @@ -1667,6 +1667,14 @@ export function resetSessionCompression(session: Session): void { // deletes the on-disk envelope on the next save. session.contentStore = undefined; session.contentStoreDirty = true; + // #3011: the rebase re-issues refs and wipes the CCR store — the retained + // snapshot's bookkeeping (stored-ref list, wire comparability verdict, + // tracked byte count) describes content whose mapping no longer exists; + // each field re-evaluates on the parent's next request. + delete session.metadata.publicSnapshotStoredRefs; + delete session.metadata.publicSnapshotWireHash; + delete session.metadata.publicSnapshotBytes; + delete session.metadata.publicSnapshotTextComparable; // #1343: rebase wipes both the queued injections and their acks (context // rebuilt), so clear the durable ledger too — otherwise a later // reconcileReloadedRetrievals would misattribute this expected loss as a diff --git a/tests/dsh-fork-adopt.test.ts b/tests/dsh-fork-adopt.test.ts index 57b4baaaa6..16533dd9b0 100644 --- a/tests/dsh-fork-adopt.test.ts +++ b/tests/dsh-fork-adopt.test.ts @@ -211,16 +211,16 @@ test("tryForkAdoption never posts a fork when the prefix does not match", async const calls: Recorded[] = []; const fetchImpl = routerFetch({ snapshot: () => jsonRes(snapshotFixture(seedCore)) }, calls); const result = await tryForkAdoption({ base: "http://proxy", parentConversationId: "parent", childConversationId: "child", body: bodyFor([{ role: "user", content: "unrelated history" }]), fetchImpl }); - assert.deepEqual(result, { outcome: "degraded", reason: "no prefix match" }); + assert.deepEqual(result, { outcome: "degraded", reason: "no prefix match", retryable: false }); assert.equal(calls.some((c) => c.url.includes("/__bili/plugin/fork")), false); }); test("tryForkAdoption degrades on snapshot failures without posting", async () => { const calls: Recorded[] = []; const notFound = routerFetch({ snapshot: () => new Response("{}", { status: 404 }) }, calls); - assert.deepEqual(await tryForkAdoption({ base: "http://proxy", parentConversationId: "parent", childConversationId: "child", body: parentBody, fetchImpl: notFound }), { outcome: "degraded", reason: "snapshot http 404" }); + assert.deepEqual(await tryForkAdoption({ base: "http://proxy", parentConversationId: "parent", childConversationId: "child", body: parentBody, fetchImpl: notFound }), { outcome: "degraded", reason: "snapshot http 404", retryable: false }); const malformed = routerFetch({ snapshot: () => jsonRes({ ok: true, orderedMessages: "nope" }) }, calls); - assert.deepEqual(await tryForkAdoption({ base: "http://proxy", parentConversationId: "parent", childConversationId: "child", body: parentBody, fetchImpl: malformed }), { outcome: "degraded", reason: "snapshot malformed" }); + assert.deepEqual(await tryForkAdoption({ base: "http://proxy", parentConversationId: "parent", childConversationId: "child", body: parentBody, fetchImpl: malformed }), { outcome: "degraded", reason: "snapshot malformed", retryable: false }); const throwing = (async () => { throw new Error("boom"); }) as unknown as typeof fetch; const degraded = await tryForkAdoption({ base: "http://proxy", parentConversationId: "parent", childConversationId: "child", body: parentBody, fetchImpl: throwing }); assert.equal(degraded.outcome, "degraded"); @@ -232,7 +232,11 @@ test("tryForkAdoption surfaces bounded snapshot diagnostics instead of a bare st const calls: Recorded[] = []; const unavailable = routerFetch({ snapshot: () => new Response(JSON.stringify({ ok: false, status: "unavailable", code: "SNAPSHOT_UNAVAILABLE", error: "Error: multimodal or opaque content cannot be compared by text" }), { status: 409, headers: { "content-type": "application/json" } }) }, calls); const result = await tryForkAdoption({ base: "http://proxy", parentConversationId: "parent", childConversationId: "child", body: parentBody, fetchImpl: unavailable }); - assert.deepEqual(result, { outcome: "degraded", reason: "snapshot http 409 SNAPSHOT_UNAVAILABLE (Error: multimodal or opaque content cannot be compared by text)" }); + // Field-based classification (#3011): the client cannot tell a residency-gap + // 409 from a multimodal 409 by code alone — over-retrying burns at most + // maxAttempts cheap GETs before the explicit permanent-disable log, while + // under-retrying resurrects the original bug. + assert.deepEqual(result, { outcome: "degraded", reason: "snapshot http 409 SNAPSHOT_UNAVAILABLE (Error: multimodal or opaque content cannot be compared by text)", retryable: true }); assert.equal(calls.length, 1, "one snapshot attempt, no fork POST"); assert.equal(calls.every((c) => !c.url.includes("/__bili/plugin/fork")), true); }); @@ -252,11 +256,11 @@ test("tryForkAdoption sanitizes control characters out of snapshot diagnostics ( test("tryForkAdoption degrades safely on non-JSON or oversized snapshot error bodies (#2469)", async () => { const nonJson = routerFetch({ snapshot: () => new Response("gateway exploded", { status: 409 }) }, []); - assert.deepEqual(await tryForkAdoption({ base: "http://proxy", parentConversationId: "parent", childConversationId: "child", body: parentBody, fetchImpl: nonJson }), { outcome: "degraded", reason: "snapshot http 409" }); + assert.deepEqual(await tryForkAdoption({ base: "http://proxy", parentConversationId: "parent", childConversationId: "child", body: parentBody, fetchImpl: nonJson }), { outcome: "degraded", reason: "snapshot http 409", retryable: false }); // A body past the 1KB read cap is truncated mid-JSON: parsing must fail // closed to the status-only reason, never hang or buffer unboundedly. const oversized = routerFetch({ snapshot: () => new Response(JSON.stringify({ ok: false, code: "BIG", error: "x".repeat(5000) }), { status: 409 }) }, []); - assert.deepEqual(await tryForkAdoption({ base: "http://proxy", parentConversationId: "parent", childConversationId: "child", body: parentBody, fetchImpl: oversized }), { outcome: "degraded", reason: "snapshot http 409" }); + assert.deepEqual(await tryForkAdoption({ base: "http://proxy", parentConversationId: "parent", childConversationId: "child", body: parentBody, fetchImpl: oversized }), { outcome: "degraded", reason: "snapshot http 409", retryable: false }); }); test("tryForkAdoption ends google children before any network request; responses go through the protocol (#2469)", async () => { @@ -265,20 +269,20 @@ test("tryForkAdoption ends google children before any network request; responses const responsesCalls: Recorded[] = []; const responsesFetch = routerFetch({ snapshot: () => jsonRes(snapshotFixture(seedCore)), fork: () => jsonRes({ ok: true }, 201) }, responsesCalls); const responses = await tryForkAdoption({ base: "http://proxy", parentConversationId: "parent", childConversationId: "child", body: { model: "gpt", input: [{ type: "message", role: "user", content: "hi" }] }, fetchImpl: responsesFetch }); - assert.deepEqual(responses, { outcome: "degraded", reason: "no prefix match" }); + assert.deepEqual(responses, { outcome: "degraded", reason: "no prefix match", retryable: false }); assert.equal(responsesCalls.filter((c) => c.url.includes("snapshot")).length, 1, "the responses child reaches the snapshot"); assert.equal(responsesCalls.filter((c) => c.url.endsWith("/__bili/plugin/fork")).length, 0, "...but posts no fork receipt for a mismatch"); const googleCalls: Recorded[] = []; const googleFetch = routerFetch({ snapshot: () => jsonRes(snapshotFixture(seedCore)) }, googleCalls); const google = await tryForkAdoption({ base: "http://proxy", parentConversationId: "parent", childConversationId: "child", body: { contents: [{ role: "user", parts: [{ text: "hi" }] }] }, fetchImpl: googleFetch }); - assert.deepEqual(google, { outcome: "degraded", reason: "wire unsupported (google)" }); + assert.deepEqual(google, { outcome: "degraded", reason: "wire unsupported (google)", retryable: false }); assert.equal(googleCalls.length, 0); }); test("tryForkAdoption surfaces fork rejections and replays", async () => { const conflict = routerFetch({ snapshot: () => jsonRes(snapshotFixture(seedCore)), fork: () => jsonRes({ ok: false, code: "CHILD_CONFLICT" }, 409) }, []); const rejected = await tryForkAdoption({ base: "http://proxy", parentConversationId: "parent", childConversationId: "child", body: parentBody, fetchImpl: conflict }); - assert.deepEqual(rejected, { outcome: "degraded", reason: "fork http 409 CHILD_CONFLICT" }); + assert.deepEqual(rejected, { outcome: "degraded", reason: "fork http 409 CHILD_CONFLICT", retryable: false }); const replay = routerFetch({ snapshot: () => jsonRes(snapshotFixture(seedCore)), fork: () => jsonRes({ ok: true, replayed: true }, 200) }, []); const replayed = await tryForkAdoption({ base: "http://proxy", parentConversationId: "parent", childConversationId: "child", body: parentBody, fetchImpl: replay }); assert.deepEqual(replayed, { outcome: "adopted", branchPoint: 3, replayed: true }); diff --git a/tests/pi-omp-fork-adopt.test.ts b/tests/pi-omp-fork-adopt.test.ts index b11e107099..2fb31e6f8c 100644 --- a/tests/pi-omp-fork-adopt.test.ts +++ b/tests/pi-omp-fork-adopt.test.ts @@ -256,6 +256,68 @@ test("createForkAdopter retries transient failures until the cap, then closes (# assert.equal(calls.filter((c) => c.url.endsWith("/__bili/plugin/fork")).length, 3, "past the cap the window is closed"); }); +test("tryForkAdoption classifies snapshot failures by the server's structured verdict (#3011)", async () => { + const input = adoptInput(); + const run = (respond: () => Response | Promise) => tryForkAdoption({ base: input.base, parentConversationId: input.parent, childConversationId: input.child, body: input.body, fetchImpl: fakeFetchRouting([manifestRoute, { match: snapshotRoute.match, respond }]).fetchImpl }); + const unavailable = (code: string, status = 409) => new Response(JSON.stringify({ ok: false, status: "unavailable", code, error: "raw snapshot unavailable; send a fresh plugin model request" }), { status }); + // The incident: the proxy's own documented-retryable 409 was classified + // terminal by the old regex and gave up after one attempt. + const asDegraded = async (p: Promise>>) => { const r = await p; if (r.outcome !== "degraded") throw new Error(`expected degraded, got ${JSON.stringify(r)}`); return r; }; + assert.deepEqual(await run(() => unavailable("SNAPSHOT_UNAVAILABLE")), { outcome: "degraded", reason: "snapshot http 409 SNAPSHOT_UNAVAILABLE (raw snapshot unavailable; send a fresh plugin model request)", retryable: true }); + assert.equal((await asDegraded(run(() => unavailable("PARENT_NOT_FOUND", 404)))).retryable, false, "an unknown parent cannot appear mid-process"); + assert.equal((await asDegraded(run(() => unavailable("BRANCH_POINT_CONFLICT")))).retryable, false, "other 409 codes are deterministic verdicts"); + const s503 = await asDegraded(run(() => new Response("upstream melted", { status: 503 }))); + assert.equal(s503.retryable, true, "5xx stays retryable"); + const boom = await asDegraded(run(async () => { throw new Error("network exploded"); })); + assert.equal(boom.retryable, true, "network errors stay retryable"); +}); + +test("tryForkAdoption classifies fork POST failures by status class (#3011)", async () => { + const input = adoptInput(); + const core = openaiBodyToCore(input.body as Record)!; + const matchSnapshot = { match: snapshotRoute.match, respond: () => Response.json({ ok: true, protocolVersion: 1, status: "exact", parentRevision: hash("rev1"), orderHash: hash("full"), orderedMessages: [{ rawId: "a", ref: "m00001", identityHash: forkIdentityHashOf(core[0]!) }] }) }; + const run = (respond: () => Response) => tryForkAdoption({ base: input.base, parentConversationId: input.parent, childConversationId: input.child, body: input.body, fetchImpl: fakeFetchRouting([manifestRoute, matchSnapshot, { match: (c: Recorded) => c.url.endsWith("/__bili/plugin/fork"), respond }]).fetchImpl }); + const conflict = await run(() => new Response(JSON.stringify({ ok: false, code: "CHILD_CONFLICT", error: "child conversation already registered" }), { status: 409 })); + if (conflict.outcome !== "degraded") throw new Error(`expected degraded, got ${JSON.stringify(conflict)}`); + assert.equal(conflict.retryable, false, "CHILD_CONFLICT latches — this child keeps its id, so the verdict cannot change"); + assert.match(conflict.reason, /fork http 409 CHILD_CONFLICT/); + const fork503 = await run(() => new Response("boom", { status: 503 })); + if (fork503.outcome !== "degraded") throw new Error(`expected degraded, got ${JSON.stringify(fork503)}`); + assert.equal(fork503.retryable, true, "fork 5xx stays retryable"); +}); + +test("createForkAdopter retries 409 SNAPSHOT_UNAVAILABLE until the parent recovers (#3011)", async () => { + resetForkCapabilityCacheForTest(); + const core = openaiBodyToCore(adoptInput().body as Record)!; + const recovered = { match: snapshotRoute.match, respond: () => Response.json({ ok: true, protocolVersion: 1, status: "exact", parentRevision: hash("rev1"), orderHash: hash("full"), orderedMessages: [{ rawId: "a", ref: "m00001", identityHash: forkIdentityHashOf(core[0]!) }] }) }; + let snapshots = 0; + const flaky = { match: snapshotRoute.match, respond: () => { snapshots += 1; return snapshots <= 2 ? new Response(JSON.stringify({ ok: false, status: "unavailable", code: "SNAPSHOT_UNAVAILABLE", error: "raw snapshot unavailable; send a fresh plugin model request" }), { status: 409 }) : recovered.respond(); } }; + const { fetchImpl, calls } = fakeFetchRouting([manifestRoute, flaky, forkRoute]); + const lines: string[] = []; + const adopter = createForkAdopter((l) => lines.push(l), { fetchImpl }); + await adopter.maybeAdopt(adoptInput()); + await adopter.maybeAdopt(adoptInput()); + assert.equal(lines.filter((l) => l.includes("transient, will retry")).length, 2, "each residency-gap 409 leaves the window open"); + await adopter.maybeAdopt(adoptInput()); + assert.equal(calls.filter((c) => c.url.endsWith("/__bili/plugin/fork")).length, 1, "the recovered parent adopts on the third request"); + assert.ok(!lines.some((l) => l.includes("permanently disabled"))); +}); + +test("createForkAdopter closes permanently after the cap and says so explicitly (#3011)", async () => { + resetForkCapabilityCacheForTest(); + const unavailable = () => new Response(JSON.stringify({ ok: false, status: "unavailable", code: "SNAPSHOT_UNAVAILABLE", error: "raw snapshot unavailable; send a fresh plugin model request" }), { status: 409 }); + const { fetchImpl, calls } = fakeFetchRouting([manifestRoute, { match: snapshotRoute.match, respond: unavailable }, forkRoute]); + const lines: string[] = []; + const adopter = createForkAdopter((l) => lines.push(l), { fetchImpl }); + for (let i = 0; i < 4; i += 1) await adopter.maybeAdopt(adoptInput()); + assert.equal(calls.filter((c) => c.url.includes("snapshot")).length, 3, "maxAttempts=3 bounds the retries"); + assert.equal(calls.filter((c) => c.url.endsWith("/__bili/plugin/fork")).length, 0); + assert.ok(lines.some((l) => l.includes("permanently disabled")), "the give-up is explicit, not silent"); + const after = lines.length; + await adopter.maybeAdopt(adoptInput()); + assert.equal(lines.length, after, "no further attempts or log lines after the latch"); +}); + test("createForkAdopter skips side-shaped bodies without consuming the attempt budget (#2399 gate ④)", async () => { resetForkCapabilityCacheForTest(); const core = openaiBodyToCore(adoptInput().body as Record)!; @@ -569,7 +631,7 @@ test("pi lane: an exploding getBranch fails toward capability and still adopts ( test("tryForkAdoption rejects a responses child whose prefix matches nothing (#2469 stage 2)", { timeout: 60_000 }, async () => { const { fetchImpl, calls } = fakeFetchRouting([snapshotRoute]); const result = await tryForkAdoption({ base: "http://px", parentConversationId: "p1", childConversationId: "c1", body: { model: "gpt", input: [{ type: "message", role: "user", content: "completely unrelated" }] }, fetchImpl }); - assert.deepEqual(result, { outcome: "degraded", reason: "no prefix match" }); + assert.deepEqual(result, { outcome: "degraded", reason: "no prefix match", retryable: false }); assert.equal(calls.filter((c) => c.url.endsWith("/__bili/plugin/fork")).length, 0, "no fork receipt is posted for a mismatch"); }); @@ -649,14 +711,14 @@ test("fork endpoint: identity-registered child yields only for the same parent ( { role: "system", content: "system prompt" }, { role: "user", content: "first original ".repeat(250) }, ] } }); - assert.deepEqual(conflicted, { outcome: "degraded", reason: "fork http 409 CHILD_CONFLICT" }, "different-parent claim stays a conflict"); + assert.deepEqual(conflicted, { outcome: "degraded", reason: "fork http 409 CHILD_CONFLICT", retryable: false }, "different-parent claim stays a conflict"); assert.equal((await register("child-bare")).status, 200); const bare = await tryForkAdoption({ base: h.origin, parentConversationId: "parent-sid", childConversationId: "child-bare", body: { model: "claude-test", max_tokens: 1024, stream: false, messages: [ { role: "system", content: "system prompt" }, { role: "user", content: "first original ".repeat(250) }, ] } }); - assert.deepEqual(bare, { outcome: "degraded", reason: "fork http 409 CHILD_CONFLICT" }, "parentless claim stays a conflict"); + assert.deepEqual(bare, { outcome: "degraded", reason: "fork http 409 CHILD_CONFLICT", retryable: false }, "parentless claim stays a conflict"); } finally { await h.close(); } diff --git a/tests/plugin-fork.test.ts b/tests/plugin-fork.test.ts index 089d74ea16..ab75a451f1 100644 --- a/tests/plugin-fork.test.ts +++ b/tests/plugin-fork.test.ts @@ -1620,3 +1620,74 @@ test("fork protocol v2: revision is stable across state churn that does not move assert.notEqual(moved.body.parentRevision, before.body.parentRevision, "a snapshot change must flip the v2 revision"); } finally { await h.close(); } }); + +test("HTTP snapshot serves the recent raw view when no retained copy exists (#3011)", async () => { + const h = await harness(); + try { + const session = getSession("parent"); + assert.ok(session.pluginSnapshot, "the seeded parent retains a raw snapshot"); + // Simulate the residency gap: LRU evict / host restart loses the + // retained copy (persisted only after a fork receipt or explicit + // retention) while lastMessages — written by every request and + // persisted unconditionally — survives. Stale stored-ref bookkeeping + // from the lost view must not veto the tail path. + session.pluginSnapshot = undefined; + session.metadata.publicSnapshotStoredRefs = ["m99998"]; + const snapshot = await h.request("/__bili/plugin/snapshot?conversationId=parent"); + assert.equal(snapshot.status, 200, JSON.stringify(snapshot.body)); + assert.equal(snapshot.body.orderedMessages.length, 3); + assert.deepEqual(snapshot.body.messages.map((m) => m.text), h.messages.map((m) => m.content)); + // A full-prefix fork materializes from the same source view (the old + // code crashed here on parent.pluginSnapshot!.slice). + const fork = await h.request("/__bili/plugin/fork", forkRequest(snapshot.body, "child", 3)); + assert.equal(fork.status, 201, JSON.stringify(fork.body)); + const childSnap = (await h.request("/__bili/plugin/snapshot?conversationId=child")).body; + assert.deepEqual(childSnap.orderedMessages, snapshot.body.orderedMessages); + } finally { await h.close(); } +}); + +test("HTTP snapshot stays unavailable with neither retained copy nor recent raw view (#3011)", async () => { + const h = await harness(); + try { + const session = getSession("parent"); + session.pluginSnapshot = undefined; + session.lastMessages = undefined; + const snapshot = await h.request("/__bili/plugin/snapshot?conversationId=parent"); + assert.equal(snapshot.status, 409); + assert.equal(snapshot.body.code, "SNAPSHOT_UNAVAILABLE"); + } finally { await h.close(); } +}); + +test("HTTP snapshot never serves a folded tail view (#3011)", async () => { + const h = await harness(); + try { + const session = getSession("parent"); + session.pluginSnapshot = undefined; + session.lastMessagesFolded = true; + const snapshot = await h.request("/__bili/plugin/snapshot?conversationId=parent"); + assert.equal(snapshot.status, 409); + assert.equal(snapshot.body.code, "SNAPSHOT_UNAVAILABLE"); + } finally { await h.close(); } +}); + +test("HTTP snapshot prefers the fresh raw view over a stale frozen snapshot (#3011)", async () => { + const h = await harness(); + try { + const session = getSession("parent"); + assert.ok(session.lastMessages && session.lastMessages.length > 0); + // A full-cover native compaction froze pluginSnapshot pre-compaction + // (zero-overlap guard refuses to shrink it) while the rebase re-issued + // the ref space; the next raw request rewrote lastMessages. Serving + // the stale head would fail closed on its dead mapping forever — the + // head-divergent tail is the freshest raw view the client replays next. + const freshHead = { id: hash("fresh-head"), role: "user" as const, contentType: "text" as const, text: "post-compaction opener" }; + session.state.messageRefs.byRaw[freshHead.id] = "m00099"; + session.state.messageRefs.byRef["m00099"] = freshHead.id; + session.lastMessages = [freshHead, ...session.lastMessages.slice(1)]; + session.lastMessagesFolded = false; + const snapshot = await h.request("/__bili/plugin/snapshot?conversationId=parent"); + assert.equal(snapshot.status, 200, JSON.stringify(snapshot.body)); + assert.equal(snapshot.body.messages[0].text, freshHead.text); + assert.equal(snapshot.body.orderedMessages[0].ref, "m00099"); + } finally { await h.close(); } +});