From 3c50cd8bd4aff1e5a0071fb95637a0f800b13e0d Mon Sep 17 00:00:00 2001 From: awork Date: Wed, 21 Oct 2026 10:39:24 +0800 Subject: [PATCH 1/3] fix: recover fold coverage after short-request deactivation under id churn (#4050) A short request deactivates a retained fold (kernel syncBlocks, by design). When the main history then returns under canonical-equivalent id churn (client re-serialization), reconcileFoldCoverage never re-keyed the block: coveredRealHistoryIds skips inactive blocks, so covered.size===0 short-circuited the whole pass and the stale ids could never be found again - permanent coverage loss, summary off the wire, folded originals re-sent every turn. Feed retained view-deactivated lineage back into the claim ladder as recovery candidates (active coverage inserted first, so the anchor cap's survivor order is unchanged). The ladder decides per cell with multi-channel corroboration - nothing is restored blindly; non-corroborated cells stay honest mismatches and complete the existing lifecycle (z-streak reap #2695, truncation suppression, epoch verdict #3641). Host-side only; kernel untouched. --- src/fold-reconcile.ts | 41 +++++- tests/fold-reconcile.test.ts | 186 ++++++++++++++++++++++++++- tests/issue4050-short-replay.test.ts | 172 +++++++++++++++++++++++++ 3 files changed, 392 insertions(+), 7 deletions(-) create mode 100644 tests/issue4050-short-replay.test.ts diff --git a/src/fold-reconcile.ts b/src/fold-reconcile.ts index 0bfd631eae..a6194534b0 100644 --- a/src/fold-reconcile.ts +++ b/src/fold-reconcile.ts @@ -706,6 +706,8 @@ interface BlockLike { active?: boolean; effectiveMessageIds?: string[]; directMessageIds?: string[]; + /** Host-decompressed block — the kernel keeps it inactive by design. */ + expanded?: boolean; } /** #2297: only LIVE blocks count as covered. The kernel deactivates a block @@ -714,11 +716,44 @@ interface BlockLike { * those dead-lineage ids can never re-anchor and would sit in `missing` * permanently, inflating the drift warn ~2x (#2293). Delegates to * coveredRealHistoryIds so the single real-history caliber (#2627) is - * implemented exactly once. */ + * implemented exactly once. reconcileFoldCoverage additionally feeds the + * retained view-deactivated lineage back in via recoveryCandidateIds + * (#4050) — different question, same file; this caliber stays active-only. */ function coveredIdsOf(blocks: BlockLike[]): Set { return coveredRealHistoryIds(blocks); } +/** #4050: coverage of RETAINED folds that are inactive only because the last + * view skipped their span (kernel syncBlocks deactivation after a short + * request, #3844/#3845). That lineage is RECOVERABLE, not dead: the span's + * bytes may come back under churned ids (client re-serialization), and only + * the claim ladder can re-key them — but it never runs if they stay out of + * `covered` (coveredRealHistoryIds skips inactive blocks → covered.size===0 + * → noop → stale ids never re-anchor → syncBlocks can never find them again + * → permanent coverage loss, folded originals re-sent every turn). The claim + * ladder decides PER CELL with multi-channel corroboration, so nothing is + * restored blindly: corroborated cells get re-keyed (syncBlocks then + * re-activates the block on the next pipeline run), non-corroborated cells + * stay honestly unmatched and complete the existing lifecycle (z-streak reap + * for verified substrates #2695, truncation suppression, epoch verdict + * #3641). Excluded: `expanded` blocks — the host decompressed them ON PURPOSE + * (the originals ride the wire verbatim and a fresh compress creates a NEW + * block, kernel/src/sync.ts), so there is nothing to restore and including + * their ids would feed #2293-style missing inflation when the whole wire + * re-serializes. Consumed (merged-away) blocks need no exclusion: their ids + * duplicate the surviving parent's ids, which the Set dedupes, and they stay + * inactive regardless via the consumed guard in kernel/src/sync.ts. */ +function recoveryCandidateIds(blocks: ReadonlyArray): Set { + const ids = new Set(); + for (const block of blocks) { + if (block.active || block.expanded === true) continue; + for (const id of block.effectiveMessageIds ?? []) { + if (!isResponsesTurnSeparatorId(id)) ids.add(id); + } + } + return ids; +} + /** Pure core: plan the reconciliation between the previous pass order and the * incoming messages. Exposed for unit tests. `positions` (#2480) is the * stored positional fingerprint copy {ids, canon} (#2487's self-contained @@ -1502,7 +1537,11 @@ export function reconcileFoldCoverage(session: Session, msgs: CoreMessage[], opt return { kind: "off", missing: 0, claims: 0, byPos: 0, byTool: 0, byTwin: 0, bySim: 0, byOrder: 0, byNorm: 0, byTurn: 0, byImage: 0, byShape: 0, reaped: 0, unmatched: 0 }; } const blocks = (session.state?.blocks ?? []) as BlockLike[]; + // Active coverage first (the anchor cap's survivor order, #2334), then the + // retained view-deactivated lineage re-fed into the claim ladder (#4050); + // see recoveryCandidateIds for what is excluded and why. const covered = coveredIdsOf(blocks); + for (const id of recoveryCandidateIds(blocks)) covered.add(id); if (covered.size === 0) { resetFoldDriftState(session); return { kind: "noop", missing: 0, claims: 0, byPos: 0, byTool: 0, byTwin: 0, bySim: 0, byOrder: 0, byNorm: 0, byTurn: 0, byImage: 0, byShape: 0, reaped: 0, unmatched: 0 }; diff --git a/tests/fold-reconcile.test.ts b/tests/fold-reconcile.test.ts index ab8d3dcb7c..5881cbe7f1 100644 --- a/tests/fold-reconcile.test.ts +++ b/tests/fold-reconcile.test.ts @@ -760,11 +760,13 @@ describe("reconcileFoldCoverage owner-deletion drift (#2297)", () => { Array.from({ length: n }, (_, i) => msg(`${tag}${i}`, "assistant", `${tag} fresh tail turn ${i} padding words`)); test("missing counts only ACTIVE block coverage; dead-lineage ids drop out", () => { - // #2293 shape: the host truncated its own history; syncBlocks has - // already deactivated the old blocks (active=false) but their - // effectiveMessageIds persist in state — they can never re-anchor and + // #2293 shape: the host decompressed these blocks and they died — + // syncBlocks keeps them inactive (expanded=true) while their + // effectiveMessageIds persist in state; they can never re-anchor and // must not sit in `missing` forever. Pre-seeded anchors simulate the - // persisted state from when those blocks were still live. + // persisted state from when those blocks were still live. (#4050 + // refined the split: VIEW-deactivated inactive blocks are recovery + // candidates again — see the #4050 describe below.) const liveIds = Array.from({ length: 12 }, (_, i) => `live${i}`); const deadIds = Array.from({ length: 50 }, (_, i) => `dead${i}`); const seedAnchors: Record = {}; @@ -772,8 +774,8 @@ describe("reconcileFoldCoverage owner-deletion drift (#2297)", () => { const session = { state: { blocks: [ { active: true, effectiveMessageIds: liveIds }, - { active: false, effectiveMessageIds: deadIds.slice(0, 40) }, - { active: false, effectiveMessageIds: deadIds.slice(40) }, + { active: false, expanded: true, effectiveMessageIds: deadIds.slice(0, 40) }, + { active: false, expanded: true, effectiveMessageIds: deadIds.slice(40) }, ]}, metadata: { foldAnchors: seedAnchors, foldAnchorOrder: [...deadIds, ...liveIds] }, } as unknown as Session; @@ -846,6 +848,178 @@ describe("reconcileFoldCoverage owner-deletion drift (#2297)", () => { assert.equal(session.metadata["foldDriftStreak"], 8, "the streak keeps counting across the restart"); }); }); +describe("reconcileFoldCoverage view-deactivated recovery (#4050)", () => { + type LogLine = { level: string; msg: string }; + const makeOpts = (logs: LogLine[]): ReconcileOptions & { mode: "repair" } => + ({ sessionId: "s4050", mode: "repair", log: (level: string, m: string) => logs.push({ level, msg: m }) }); + const errorLines = (logs: LogLine[]) => logs.filter((l) => l.level === "error"); + // A live fold plus a fold deactivated by the LAST view skipping its span + // (kernel syncBlocks after a short request) — inactive, NOT expanded. + function dualSession(): Session { + const liveIds = Array.from({ length: 12 }, (_, i) => `l${i}`); + const viewIds = Array.from({ length: 5 }, (_, i) => `v${i}`); + const seedAnchors: Record = {}; + for (const id of [...liveIds, ...viewIds]) seedAnchors[id] = anchorOf(msg(id, "user", `seed text ${id} words`)); + return { + state: { + blocks: [ + { blockId: "live-block", active: true, effectiveMessageIds: liveIds }, + { blockId: "view-block", active: false, effectiveMessageIds: viewIds }, + ], + }, + metadata: { foldAnchors: seedAnchors, foldAnchorOrder: [...liveIds, ...viewIds] }, + } as unknown as Session; + } + const liveMsgs = Array.from({ length: 12 }, (_, i) => msg(`l${i}`, "user", `live turn ${i} payload words`)); + const viewMsgs = Array.from({ length: 5 }, (_, i) => msg(`v${i}`, "user", `view span ${i} content words`)); + const tailMsgs = Array.from({ length: 10 }, (_, i) => msg(`t${i}`, "assistant", `tail turn ${i} padding words`)); + + test("canonical-equivalent id churn re-keys the view-deactivated fold", () => { + // The reported shape: a short request deactivates the fold, then the + // main history returns with every id re-minted over canonical-equivalent + // bytes (whitespace churn). Pre-fix covered.size saw only active blocks + // and the stale v-ids could never re-anchor → permanent coverage loss. + const session = dualSession(); + const opts = makeOpts([]); + assert.equal(reconcileFoldCoverage(session, [...liveMsgs, ...viewMsgs, ...tailMsgs], opts).kind, "resend"); + const churned: CoreMessage[] = [ + ...liveMsgs.map((m, i) => msg(`L${i}`, m.role, m.text!.replaceAll(" ", " "))), + ...viewMsgs.map((m, i) => msg(`V${i}`, m.role, m.text!.replaceAll(" ", " "))), + ...tailMsgs.map((m, i) => msg(`T${i}`, m.role, m.text!.replaceAll(" ", " "))), + ]; + const result = reconcileFoldCoverage(session, churned, opts); + assert.equal(result.kind, "reanchored"); + assert.equal(result.claims, 17, "every churned cell corroborates and claims"); + assert.equal(result.unmatched, 0); + assert.deepEqual( + (session.state.blocks[0] as { effectiveMessageIds: string[] }).effectiveMessageIds, + Array.from({ length: 12 }, (_, i) => `L${i}`), + "the live fold re-keys under the churned ids", + ); + assert.deepEqual( + (session.state.blocks[1] as { effectiveMessageIds: string[] }).effectiveMessageIds, + Array.from({ length: 5 }, (_, i) => `V${i}`), + "the view-deactivated fold re-keys too — syncBlocks re-activates it on the next pipeline run", + ); + assert.equal((session.state.blocks[1] as { active: boolean }).active, false, + "reconcile only re-keys; reactivation stays the kernel sync's job (no blind flag flip)"); + }); + + test("sanctioned head-truncation of a verified span is never reaped", () => { + // The client truncated its own head history (the #2627/#3641/#3724 + // sanctioned-deletion class): every absent id has zero word evidence + // and the wire still continues from the witness tail → structurally + // absent, so the #2695 streak must stay at zero even for a verified + // (e===1) view-deactivated fold. The snapshot IS the session's memory + // of that span and must survive indefinitely. + const session = dualSession(); + const logs: LogLine[] = []; + const opts = makeOpts(logs); + assert.equal(reconcileFoldCoverage(session, [...liveMsgs, ...viewMsgs, ...tailMsgs], opts).kind, "resend"); + session.metadata[METADATA_FOLD_COVERAGE] = { "view-block": { p: 5, r: 0, t: 5, e: 1 } }; + // Head truncation cuts the OLDEST ids first: everything up to and + // including both folded spans is gone, the wire keeps its clean tail + // (same ids, re-serialized bytes) plus a fresh continuation — the + // common set is a contiguous suffix of the witness, which is what + // makes this the sanctioned class (a mid-span cut would stay honest + // drift instead). Alien vocabulary keeps the word-evidence census at + // zero deterministically. + const alienTail = Array.from({ length: 10 }, (_, i) => msg(`t${i}`, "assistant", `tail message ${String.fromCharCode(97 + i)} continuation context`)); + const appended = [msg("n0", "user", "fresh continuation question here"), msg("n1", "assistant", "fresh continuation answer now")]; + const truncated = [...alienTail, ...appended]; // l0..l11 + v0..v4 gone + for (let pass = 0; pass < 3; pass++) { + const result = reconcileFoldCoverage(session, truncated, opts); + assert.equal(result.reaped, 0, `pass ${pass + 1}: truncation-suppressed span is never reaped`); + assert.equal((session.metadata[METADATA_FOLD_COVERAGE] as Record)["view-block"].z, 0, + `pass ${pass + 1}: structural absence keeps the streak at zero`); + } + assert.deepEqual( + (session.state.blocks[1] as { effectiveMessageIds: string[] }).effectiveMessageIds, + viewMsgs.map((m) => m.id!), + "no corroboration → no re-key, the stale ids are kept for honest loss", + ); + assert.equal(session.state.blocks.length, 2, "the snapshot survives the truncation"); + assert.equal(errorLines(logs).length, 0, "continuity explains the absence — no drift escalation"); + assert.equal(session.metadata["foldDriftEscalated"], undefined, "no escalation latch set"); + }); + + test("a mid-history edit of a verified span accrues honest drift (same #2695 lifecycle as active folds)", () => { + // A genuine in-session rewrite of folded content breaks wire contiguity + // BY DESIGN (mid-history edits are not the sanctioned-truncation class), + // so the verified span accrues its zombie streak exactly like an active + // fold would: z climbs per pass and the third pass completes the #2695 + // reap. Two passes here pin the accrual without triggering the removal + // (the reap itself is pinned by the #2695 tests against active folds). + const session = dualSession(); + const logs: LogLine[] = []; + const opts = makeOpts(logs); + assert.equal(reconcileFoldCoverage(session, [...liveMsgs, ...viewMsgs, ...tailMsgs], opts).kind, "resend"); + session.metadata[METADATA_FOLD_COVERAGE] = { "view-block": { p: 5, r: 0, t: 5, e: 1 } }; + const edited: CoreMessage[] = [ + ...liveMsgs, + ...Array.from({ length: 5 }, (_, i) => msg(`V${i}`, "user", `alien rewrite ${["alpha", "beta", "gamma", "delta", "epsilon"][i]} omega`)), + ...tailMsgs, + ]; + for (let pass = 0; pass < 2; pass++) { + const result = reconcileFoldCoverage(session, edited, opts); + assert.equal(result.unmatched, 5, `pass ${pass + 1}: the rewritten cells stay honestly unmatched`); + assert.equal(result.reaped, 0, `pass ${pass + 1}: not yet ripe`); + assert.equal((session.metadata[METADATA_FOLD_COVERAGE] as Record)["view-block"].z, pass + 1, + `pass ${pass + 1}: honest streak accrual for the genuinely-gone verified span`); + } + assert.deepEqual( + (session.state.blocks[1] as { effectiveMessageIds: string[] }).effectiveMessageIds, + viewMsgs.map((m) => m.id!), + "no corroboration → no re-key while the span is still accounted for", + ); + }); + + test("consumed child ids dedupe against the surviving parent — no exclusion needed", () => { + // A merged-away (consumed) block keeps its pre-merge ids, a subset of + // the parent's ids. Both blocks ride the same claim: the Set dedupes, + // the claim applies once, and BOTH id lists get re-keyed. If someone + // later adds a consumed-exclusion here, this test catches the lost + // child re-key. + const parentIds = Array.from({ length: 5 }, (_, i) => `x${i}`); + const childIds = parentIds.slice(2); + const seedAnchors: Record = {}; + for (const id of parentIds) seedAnchors[id] = anchorOf(msg(id, "user", `merged turn ${id} words`)); + const session = { + state: { + blocks: [ + { blockId: "parent", active: true, effectiveMessageIds: parentIds }, + { blockId: "child", active: false, effectiveMessageIds: childIds }, + ], + }, + metadata: { foldAnchors: seedAnchors, foldAnchorOrder: [...parentIds] }, + } as unknown as Session; + const opts = makeOpts([]); + const tail = Array.from({ length: 6 }, (_, i) => msg(`z${i}`, "assistant", `dedupe tail ${i} words`)); + const originals = [ + ...Array.from({ length: 5 }, (_, i) => msg(`x${i}`, "user", `merged turn x${i} words`)), + ...tail, + ]; + assert.equal(reconcileFoldCoverage(session, originals, opts).kind, "resend"); + const churned: CoreMessage[] = [ + msg("x0", "user", "merged turn x0 words"), + msg("x1", "user", "merged turn x1 words"), + ...Array.from({ length: 3 }, (_, i) => msg(`X${i + 2}`, "user", `merged turn x${i + 2} words\r\n`)), + ...tail, + ]; + const result = reconcileFoldCoverage(session, churned, opts); + assert.equal(result.claims, 3, "each unique id claimed once despite two blocks listing it"); + assert.equal(result.unmatched, 0); + assert.deepEqual( + (session.state.blocks[0] as { effectiveMessageIds: string[] }).effectiveMessageIds, + ["x0", "x1", "X2", "X3", "X4"], + ); + assert.deepEqual( + (session.state.blocks[1] as { effectiveMessageIds: string[] }).effectiveMessageIds, + ["X2", "X3", "X4"], + "the consumed child re-keys alongside its parent", + ); + }); +}); describe("reconcileFoldCoverage anchor cap boundary (#2334)", () => { // MAX_ANCHORS (src/fold-reconcile.ts) pinned at 16384 — hardcoded here on // purpose so a constant move breaks the pin loudly instead of sliding it. diff --git a/tests/issue4050-short-replay.test.ts b/tests/issue4050-short-replay.test.ts new file mode 100644 index 0000000000..68dfd16f0d --- /dev/null +++ b/tests/issue4050-short-replay.test.ts @@ -0,0 +1,172 @@ +import { writeFileSync } from "node:fs"; +import assert from "node:assert/strict"; +import http from "node:http"; +import { once } from "node:events"; +import test from "node:test"; + +process.env.NODE_ENV = "test"; +process.env.BILI_ROLLOUT_SNAPSHOT_RENDER = "0"; +// Fail fast on the very first 429 instead of the default 3 attempts with +// exponential backoff — these tests are about the post-retry behavior. +process.env.BILI_REPLAY_RETRY_MAX = "1"; + +import { createCore, defaultConfig, type Config } from "acp-kernel"; +import { startServer } from "../src/server.ts"; +import { type CompressSettings, type ProxyOptions } from "../src/config.ts"; +import { SessionStore, _setStoreForTest } from "../src/persist.ts"; +import { getSession } from "../src/session.ts"; +import { _setForTest as setRegistryForTest } from "../src/registry.ts"; + +// #4050: a short request deactivates a retained fold (kernel syncBlocks, by +// design); when the main history then returns under canonical-equivalent id +// churn (client re-serialization), the fold must RECOVER its coverage instead +// of losing it forever (summary dropped from the wire, folded originals +// re-sent every turn). Four scenarios pin the contract end-to-end through a +// real HTTP proxy: two controls prove the material suffices (no-short churn +// recovers; exact-id resend recovers), the reported shape must recover too, +// and a genuinely edited span must stay an honest mismatch. + +function okSse(inputTokens: number): string { + return ( + `event: message_start\ndata: ${JSON.stringify({ type: "message_start", message: { id: "m1", role: "assistant", usage: { input_tokens: inputTokens } } })}\n\n` + + `event: content_block_start\ndata: ${JSON.stringify({ type: "content_block_start", index: 0, content_block: { type: "text", text: "" } })}\n\n` + + `event: content_block_delta\ndata: ${JSON.stringify({ type: "content_block_delta", index: 0, delta: { type: "text_delta", text: "ok" } })}\n\n` + + `event: content_block_stop\ndata: ${JSON.stringify({ type: "content_block_stop", index: 0 })}\n\n` + + `event: message_delta\ndata: ${JSON.stringify({ type: "message_delta", delta: { stop_reason: "end_turn", stop_sequence: null }, usage: { output_tokens: 3 } })}\n\n` + + `event: message_stop\ndata: ${JSON.stringify({ type: "message_stop" })}\n\n` + ); +} + +type Call = { stream: boolean; body: string }; + +function makeUpstreamOk(calls?: Call[]): http.Server { + return http.createServer((req, res) => { + const chunks: Buffer[] = []; + req.on("data", (c: Buffer) => chunks.push(c)); + req.on("end", () => { + const raw = Buffer.concat(chunks).toString("utf8"); + let parsed: { stream?: boolean } = {}; + try { parsed = JSON.parse(raw); } catch { /* keep {} */ } + calls?.push({ stream: !!parsed.stream, body: raw }); + if (parsed.stream) { + res.writeHead(200, { "content-type": "text/event-stream" }); + res.end(okSse(1000)); + } else { + res.writeHead(200, { "content-type": "application/json" }); + res.end(JSON.stringify({ content: [{ type: "text", text: "SUMMARY: the large recent user message was a deterministic load-growth payload; its raw content is no longer needed." }] })); + } + }); + }); +} + +function startProxy(upstreamPort: number, models: Record, kernelOverrides?: Partial, compressOverrides?: Partial): Promise { + _setStoreForTest(new SessionStore({ enabled: false })); + setRegistryForTest({}); + return startServer({ + port: 0, + host: "127.0.0.1", + upstream: "http://127.0.0.1", + routes: { [`http://127.0.0.1:${upstreamPort}`]: { models } }, + modelContextLimit: 400_000, + kernelConfig: defaultConfig(400_000, kernelOverrides), + compress: { injectTool: true, injectNudge: true, ...compressOverrides }, + promptCache: { routing: "auto" }, + sessionHeader: "x-acp-session", + log: false, + debug: false, + passthrough: false, + passthroughSource: null, + autoUpdate: false, + autoRestartOnUpdate: false, + updateTag: "latest", + advisoryCheck: false, + releaseNotesCheck: false, + compat: { roles: {} }, + streamErrorShape: "protocol", + mitm: { enabled: false, domains: [] }, + } as ProxyOptions); +} + +for (const scenario of ["isolated-normalized", "short-exact", "short-normalized", "isolated-edited"] as const) { + test(`issue4050 ${scenario}`, async () => { + const calls: Call[] = []; + const upstream = makeUpstreamOk(calls); + upstream.listen(0, "127.0.0.1"); + await once(upstream, "listening"); + const upstreamPort = (upstream.address() as { port: number }).port; + const proxy = await startProxy(upstreamPort, { "gpt-short-wire": { context: 400_000 } }); + await once(proxy, "listening"); + const proxyPort = (proxy.address() as { port: number }).port; + const sid = `issue4050-${scenario}`; + const post = async (input: unknown[]) => { + const response = await fetch(`http://127.0.0.1:${proxyPort}/bili/http://127.0.0.1:${upstreamPort}/v1/responses`, { + method: "POST", headers: { "content-type": "application/json", "x-acp-session": sid }, + body: JSON.stringify({ model: "gpt-short-wire", stream: true, max_output_tokens: 1024, input }), + }); + const body = await response.text(); + assert.equal(response.status, 200, body.slice(0, 300)); + }; + try { + const main = Array.from({ length: 24 }, (_, i) => ({ + type: "message", role: i % 2 ? "assistant" : "user", + content: `main turn ${i} ${(`UNIQUE_${i}_stable_text `).repeat(110)}`, + })); + await post(main); + const session = getSession(sid); + const messages = session.lastMessages; + assert.ok(messages && messages.length >= 24); + session.state = createCore().applyCompression({ + ranges: [{ startRef: "m00001", endRef: "m00007", summary: "Compressed main history: seven early turns preserved the investigation, implementation decisions, and verified test evidence." }], + messages, state: session.state, config: defaultConfig(400_000), + }).state; + await post(main); + assert.equal(session.state.blocks.length, 1); + assert.ok(session.state.blocks[0].active); + const baselineWireBytes = Buffer.byteLength(calls.at(-1)!.body); + const before = session.state.blocks[0].effectiveMessageIds.slice(); + let activeAfterShort: number | null = null; + if (scenario.startsWith("short-")) { + const short = Array.from({ length: 3 }, (_, i) => ({ + type: "message", role: "user", + content: Array.from({ length: 13 }, (_, j) => ({ type: "input_text", text: `utility ${i} part ${j} padding words here now` })), + })); + await post(short); + activeAfterShort = session.state.blocks.filter(b => b.active).length; + assert.equal(session.state.blocks.length, 1, "raw-count guard retains the block"); + assert.equal(activeAfterShort, 0, "short request deactivates retained block"); + } + const replay = main.map(m => ({...m, content: scenario === "short-exact" ? m.content : + scenario === "isolated-edited" ? "A genuinely different replacement with no prior semantic meaning." : m.content.replaceAll(" ", " ")})); + await post(replay); + const wire = calls.at(-1)!.body; + writeFileSync(`${process.env.TMPDIR ?? "/tmp"}/issue4050-wire-${scenario}.json`, wire); + const result = { + scenario, activeAfterShort, retainedBlocks: session.state.blocks.length, + finalActiveBlocks: session.state.blocks.filter(b => b.active).length, + coveredIdsChanged: JSON.stringify(before) !== JSON.stringify(session.state.blocks[0]?.effectiveMessageIds), + summaryOnWire: wire.includes("Compressed main history: seven early turns"), + foldedAssistantOriginalOnWire: wire.includes("UNIQUE_1_stable_text"), + baselineWireBytes, replayWireBytes: Buffer.byteLength(wire), + }; + console.log("ISSUE4050_RESULT " + JSON.stringify(result)); + if (scenario === "isolated-edited") { + // Negative control: a genuine edit is an honest mismatch — no + // blind restore, the folded span simply does not come back. + assert.equal(result.summaryOnWire, false, "a genuinely edited span is never restored"); + assert.equal(result.foldedAssistantOriginalOnWire, false); + assert.equal(result.finalActiveBlocks, 0); + assert.ok(result.replayWireBytes < result.baselineWireBytes, "the rewritten span replaces the seven folded turns"); + } else { + assert.equal(result.summaryOnWire, true, `${scenario}: the fold recovers its coverage`); + assert.equal(result.foldedAssistantOriginalOnWire, false, `${scenario}: the folded originals stay off the wire`); + assert.equal(result.finalActiveBlocks, 1, `${scenario}: the retained block is active again`); + assert.ok(result.replayWireBytes - result.baselineWireBytes < 5_000, + `${scenario}: no unfolded payload re-sent (pre-fix short-normalized paid +${80_867 - 63_850}B for the folded originals)`); + } + } finally { + proxy.close(); proxy.closeIdleConnections?.(); + upstream.close(); upstream.closeIdleConnections?.(); + await Promise.allSettled([once(proxy, "close"), once(upstream, "close")]); + } + }); +} From 8c7de33318862f95bab9dbe70e1bf22903999a9f Mon Sep 17 00:00:00 2001 From: awork Date: Wed, 21 Oct 2026 10:45:37 +0800 Subject: [PATCH 2/3] style: separate top-level describes with blank lines (#4050 test block) --- tests/fold-reconcile.test.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/tests/fold-reconcile.test.ts b/tests/fold-reconcile.test.ts index 5881cbe7f1..c30c51700c 100644 --- a/tests/fold-reconcile.test.ts +++ b/tests/fold-reconcile.test.ts @@ -848,6 +848,7 @@ describe("reconcileFoldCoverage owner-deletion drift (#2297)", () => { assert.equal(session.metadata["foldDriftStreak"], 8, "the streak keeps counting across the restart"); }); }); + describe("reconcileFoldCoverage view-deactivated recovery (#4050)", () => { type LogLine = { level: string; msg: string }; const makeOpts = (logs: LogLine[]): ReconcileOptions & { mode: "repair" } => @@ -1020,6 +1021,7 @@ describe("reconcileFoldCoverage view-deactivated recovery (#4050)", () => { ); }); }); + describe("reconcileFoldCoverage anchor cap boundary (#2334)", () => { // MAX_ANCHORS (src/fold-reconcile.ts) pinned at 16384 — hardcoded here on // purpose so a constant move breaks the pin loudly instead of sliding it. From ccc586f29fd0e40cc8600eae0b7670ed0e27f7cb Mon Sep 17 00:00:00 2001 From: awork Date: Wed, 21 Oct 2026 12:02:13 +0800 Subject: [PATCH 3/3] =?UTF-8?q?fix(tests):=20issue4050=20regression=20test?= =?UTF-8?q?=20=E2=80=94=20cross-platform=20temp=20path=20for=20wire=20arti?= =?UTF-8?q?facts=20(#4050)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit process.env.TMPDIR is unset on Windows (it uses TEMP/TMP), so the artifact write fell back to "/tmp" and resolved to a nonexistent D:\tmp\ on the windows-latest runners, failing all four scenarios with ENOENT (CI run 39538358942, windows-22 shard 2). Use node:os tmpdir(), which is valid on every platform. Verified locally: 4/4 pass, result lines unchanged. --- tests/issue4050-short-replay.test.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/tests/issue4050-short-replay.test.ts b/tests/issue4050-short-replay.test.ts index 68dfd16f0d..3d670f94ba 100644 --- a/tests/issue4050-short-replay.test.ts +++ b/tests/issue4050-short-replay.test.ts @@ -2,6 +2,7 @@ import { writeFileSync } from "node:fs"; import assert from "node:assert/strict"; import http from "node:http"; import { once } from "node:events"; +import { tmpdir } from "node:os"; import test from "node:test"; process.env.NODE_ENV = "test"; @@ -139,7 +140,7 @@ for (const scenario of ["isolated-normalized", "short-exact", "short-normalized" scenario === "isolated-edited" ? "A genuinely different replacement with no prior semantic meaning." : m.content.replaceAll(" ", " ")})); await post(replay); const wire = calls.at(-1)!.body; - writeFileSync(`${process.env.TMPDIR ?? "/tmp"}/issue4050-wire-${scenario}.json`, wire); + writeFileSync(`${tmpdir()}/issue4050-wire-${scenario}.json`, wire); const result = { scenario, activeAfterShort, retainedBlocks: session.state.blocks.length, finalActiveBlocks: session.state.blocks.filter(b => b.active).length,