From 1494a70ebd389e30c2683c600adca305eb8aa4b0 Mon Sep 17 00:00:00 2001 From: ScriptedAlchemy Date: Mon, 16 Nov 2026 02:12:41 -0800 Subject: [PATCH 01/37] test(server): a thread should keep one pending summary pass Each completed run inserts its own conversation-summary pass, so pending passes pile up and a context restart stays refused. The outbox still accepts a second run while the first is pending. Co-authored-by: Cursor --- .../src/orchestration-v2/EffectWorker.test.ts | 88 +++++++++++++++++++ 1 file changed, 88 insertions(+) diff --git a/apps/server/src/orchestration-v2/EffectWorker.test.ts b/apps/server/src/orchestration-v2/EffectWorker.test.ts index 53622ad0167c6..04f58e0864366 100644 --- a/apps/server/src/orchestration-v2/EffectWorker.test.ts +++ b/apps/server/src/orchestration-v2/EffectWorker.test.ts @@ -51,6 +51,7 @@ import { modelEvaluationEffects } from "../modelEvaluations/modelEvaluationSched import { ConversationSummaryPassError, ConversationSummaryRuntime, + conversationSummaryEffect, } from "../project/conversationSummaries/conversationSummarySchedule.ts"; import { DeliveryScrubRunner, @@ -201,6 +202,93 @@ it.effect("retries a failed summary pass before scheduling its continuation", () }), ); +it.effect("keeps at most one pending summary pass per thread", () => + Effect.gen(function* () { + const threadA = ThreadId.make("thread:summary-one-pending"); + const threadB = ThreadId.make("thread:summary-other"); + const first = conversationSummaryEffect({ + threadId: threadA, + runId: RunId.make("run:summary-one-pending-a"), + }); + const second = conversationSummaryEffect({ + threadId: threadA, + runId: RunId.make("run:summary-one-pending-b"), + }); + const other = conversationSummaryEffect({ + threadId: threadB, + runId: RunId.make("run:summary-one-pending-c"), + }); + const layer = EffectOutbox.layer.pipe(Layer.provide(SqlitePersistence.layerMemory)); + yield* Effect.gen(function* () { + const outbox = yield* EffectOutbox.EffectOutboxV2; + yield* outbox.enqueue([first, second, other]); + assert.isTrue(Option.isSome(yield* outbox.get(first.id))); + assert.isTrue(Option.isNone(yield* outbox.get(second.id))); + assert.isTrue(Option.isSome(yield* outbox.get(other.id))); + + const workerId = "summary-dedupe"; + const claimed = yield* outbox.claimNext({ workerId, lane: "maintenance" }); + assert.deepEqual( + Option.map(claimed, (effect) => effect.id), + Option.some(first.id), + ); + const otherClaimed = yield* outbox.claimNext({ workerId, lane: "maintenance" }); + assert.deepEqual( + Option.map(otherClaimed, (effect) => effect.id), + Option.some(other.id), + ); + assert.isTrue(yield* outbox.succeed({ effectId: other.id, workerId })); + + const continuation = conversationSummaryEffect({ + threadId: threadA, + runId: RunId.make("run:summary-one-pending-a"), + pass: 1, + }); + const third = conversationSummaryEffect({ + threadId: threadA, + runId: RunId.make("run:summary-one-pending-d"), + }); + yield* outbox.enqueue([continuation, third]); + assert.isTrue(Option.isSome(yield* outbox.get(continuation.id))); + assert.isTrue(Option.isNone(yield* outbox.get(third.id))); + + const retried = yield* outbox.retry({ + effectId: first.id, + workerId, + error: "OpenCode did not finish generating in time.", + delayMs: 0, + }); + assert.isTrue(retried); + const settled = yield* outbox.get(first.id); + assert.isTrue(Option.isSome(settled)); + if (Option.isSome(settled)) assert.notEqual(settled.value.status, "pending"); + const pendingContinuation = yield* outbox.get(continuation.id); + assert.isTrue(Option.isSome(pendingContinuation)); + if (Option.isSome(pendingContinuation)) + assert.equal(pendingContinuation.value.status, "pending"); + + const resumed = yield* outbox.claimNext({ workerId, lane: "maintenance" }); + assert.deepEqual( + Option.map(resumed, (effect) => effect.id), + Option.some(continuation.id), + ); + const successor = conversationSummaryEffect({ + threadId: threadA, + runId: RunId.make("run:summary-one-pending-a"), + pass: 2, + }); + yield* outbox.enqueue([successor]); + assert.deepEqual(yield* outbox.reconcileAfterProcessLoss, { requeued: 0, cancelled: 0 }); + const restarted = yield* outbox.get(continuation.id); + assert.isTrue(Option.isSome(restarted)); + if (Option.isSome(restarted)) assert.notEqual(restarted.value.status, "pending"); + const pendingSuccessor = yield* outbox.get(successor.id); + assert.isTrue(Option.isSome(pendingSuccessor)); + if (Option.isSome(pendingSuccessor)) assert.equal(pendingSuccessor.value.status, "pending"); + }).pipe(Effect.provide(layer)); + }), +); + it.effect.each(["turn", "maintenance"] as const)( "wakes the %s lane when the other lane is waiting first", (lane) => From 2097a4f0fcd2e297a7e409ecfb4ca3fb72ae1ccf Mon Sep 17 00:00:00 2001 From: ScriptedAlchemy Date: Mon, 16 Nov 2026 02:16:37 -0800 Subject: [PATCH 02/37] fix(server): keep one pending conversation-summary pass per thread A second run no longer starts its own chain while a pass is already pending. A retry or process restart leaves the queued successor and does not resume the pass it already replaced. Co-authored-by: Cursor --- .../src/orchestration-v2/EffectOutbox.ts | 63 ++++++++++++++++++- .../conversationSummarySchedule.ts | 1 + 2 files changed, 62 insertions(+), 2 deletions(-) diff --git a/apps/server/src/orchestration-v2/EffectOutbox.ts b/apps/server/src/orchestration-v2/EffectOutbox.ts index b52ea74530d92..c55c954fe521d 100644 --- a/apps/server/src/orchestration-v2/EffectOutbox.ts +++ b/apps/server/src/orchestration-v2/EffectOutbox.ts @@ -505,7 +505,8 @@ export const layer: Layer.Layer = La ${DateTime.formatIso(effect.availableAt ?? now)}, ${nowIso}, ${nowIso} - WHERE ${effect.request.type !== "project-knowledge.scrub-deliveries" || effect.request.afterId !== undefined ? sql`1 = 1` : sql`1 = 0`} + WHERE ( + ${effect.request.type !== "project-knowledge.scrub-deliveries" || effect.request.afterId !== undefined ? sql`1 = 1` : sql`1 = 0`} OR NOT EXISTS ( SELECT 1 FROM orchestration_v2_effect_outbox AS pending WHERE pending.thread_id = ${effect.threadId} @@ -513,6 +514,18 @@ export const layer: Layer.Layer = La AND pending.status = 'pending' AND json_extract(pending.payload_json, '$.afterId') IS NULL ) + ) + -- A running pass may enqueue its successor. Another pending pass would rehash the thread. + AND ${ + effect.request.type === "conversation-summary.generate" + ? sql`NOT EXISTS ( + SELECT 1 FROM orchestration_v2_effect_outbox AS pending_summary + WHERE pending_summary.thread_id = ${effect.threadId} + AND pending_summary.effect_type = 'conversation-summary.generate' + AND pending_summary.status = 'pending' + )` + : sql`1 = 1` + } ON CONFLICT(effect_id) DO NOTHING `, { concurrency: 1, discard: true }, @@ -614,6 +627,25 @@ export const layer: Layer.Layer = La AND effect_type IN ${sql.in(PROCESS_BOUND_EFFECT_TYPES)} RETURNING effect_id `; + // The successor was enqueued before the crash, so resuming this row too would run two passes. + const coveredRows = yield* sql<{ readonly effect_id: string }>` + UPDATE orchestration_v2_effect_outbox + SET + status = 'succeeded', + lease_owner = NULL, + completed_at = ${now}, + updated_at = ${now}, + last_error = NULL + WHERE status = 'running' + AND effect_type = 'conversation-summary.generate' + AND EXISTS ( + SELECT 1 FROM orchestration_v2_effect_outbox AS pending_summary + WHERE pending_summary.thread_id = orchestration_v2_effect_outbox.thread_id + AND pending_summary.effect_type = 'conversation-summary.generate' + AND pending_summary.status = 'pending' + ) + RETURNING effect_id + `; const requeuedRows = yield* sql<{ readonly effect_id: string }>` UPDATE orchestration_v2_effect_outbox SET @@ -626,7 +658,8 @@ export const layer: Layer.Layer = La AND effect_type IN ${sql.in(REPLAY_SAFE_EFFECT_TYPES_AFTER_PROCESS_LOSS)} RETURNING effect_id `; - if (requeuedRows.length > 0) yield* notifyAvailable(requeuedRows.length); + if (requeuedRows.length > 0 || coveredRows.length > 0) + yield* notifyAvailable(requeuedRows.length + coveredRows.length); return { requeued: requeuedRows.length, cancelled: cancelledRows.length }; }).pipe( Effect.mapError( @@ -756,6 +789,32 @@ export const layer: Layer.Layer = La const availableAt = DateTime.formatIso( DateTime.add(now, { milliseconds: Math.max(0, delayMs) }), ); + const yielded = yield* sql<{ readonly effect_id: string }>` + UPDATE orchestration_v2_effect_outbox + SET + status = 'failed', + lease_owner = NULL, + completed_at = ${nowIso}, + updated_at = ${nowIso}, + last_error = ${error} + WHERE effect_id = ${effectId} + AND status = 'running' + AND lease_owner = ${workerId} + AND effect_type = 'conversation-summary.generate' + AND EXISTS ( + SELECT 1 FROM orchestration_v2_effect_outbox AS pending_summary + WHERE pending_summary.thread_id = orchestration_v2_effect_outbox.thread_id + AND pending_summary.effect_type = 'conversation-summary.generate' + AND pending_summary.status = 'pending' + ) + RETURNING effect_id + `; + if (yielded.length === 1) { + cancellationSignals.delete(effectId); + yield* signalSettled([effectId]); + yield* notifyAvailable(); + return true; + } const rows = yield* sql<{ readonly effect_id: string }>` UPDATE orchestration_v2_effect_outbox SET diff --git a/apps/server/src/project/conversationSummaries/conversationSummarySchedule.ts b/apps/server/src/project/conversationSummaries/conversationSummarySchedule.ts index e359db0620d4a..0f7ff37500300 100644 --- a/apps/server/src/project/conversationSummaries/conversationSummarySchedule.ts +++ b/apps/server/src/project/conversationSummaries/conversationSummarySchedule.ts @@ -19,6 +19,7 @@ import type { PendingOrchestrationEffectV2 } from "../../orchestration-v2/Effect /** * The summary pass after one completed run, or nothing when the project has not opted in. The * effect id is derived from the run, so a replayed finalization coalesces into the queued pass. + * The outbox keeps one pending pass per thread, so a later run does not start another chain. */ export function conversationSummaryEffects(input: { readonly settings: ServerSettings; From c9a88d1171286485e973375cd101667a30179a6b Mon Sep 17 00:00:00 2001 From: ScriptedAlchemy Date: Mon, 16 Nov 2026 02:18:52 -0800 Subject: [PATCH 03/37] test(server): roll up covered roots before a later uncovered stretch A pass with eight current leaves and an uncovered tail still summarizes the tail first, so busy threads never build the roll-ups a handoff can fit. A gap in the middle must still be replaced before roots on either side are rolled together. Co-authored-by: Cursor --- .../ConversationSummaries.test.ts | 37 +++++++++++++++++++ 1 file changed, 37 insertions(+) diff --git a/apps/server/src/project/conversationSummaries/ConversationSummaries.test.ts b/apps/server/src/project/conversationSummaries/ConversationSummaries.test.ts index a286802f16670..8ae32d1315d9a 100644 --- a/apps/server/src/project/conversationSummaries/ConversationSummaries.test.ts +++ b/apps/server/src/project/conversationSummaries/ConversationSummaries.test.ts @@ -1127,6 +1127,43 @@ it.effect("records and retries a source change during model generation", () => { }).pipe(Effect.provide(makeLayer(model.generate, optedIn))); }); +it.effect("rolls up covered roots before summarizing a later uncovered stretch", () => { + const model = citing(); + return Effect.gen(function* () { + const coveredLeaves = 8; + const uncovered = 10; + yield* seedThread(coveredLeaves * 2 + uncovered + 6); + for (let index = 0; index < coveredLeaves; index++) + yield* persistSummary(index, [index * 2, index * 2 + 1]); + yield* summarize; + assert.equal(model.calls.length, 3); + assert.isTrue(isRollup(model.calls[0]!)); + assert.isTrue(isRollup(model.calls[1]!)); + assert.equal(model.calls[0]!.messages.length, 4); + assert.equal(model.calls[2]!.messages[0]!.text, rawText(coveredLeaves * 2)); + }).pipe(Effect.provide(makeLayer(model.generate, optedIn))); +}); + +it.effect("replaces a leaf beside a gap before rolling roots across that gap", () => { + const model = citing(); + return Effect.gen(function* () { + yield* seedThread(22); + for (let index = 0; index < 8; index++) + yield* persistSummary(index, [index * 2, index * 2 + 1], index === 3); + yield* summarize; + assert.isFalse(isRollup(model.calls[0]!)); + assert.equal(model.calls[0]!.messages[0]!.text, rawText(6)); + assert.isFalse( + model.calls.some( + (call) => + isRollup(call) && + call.messages.some((message) => message.text.includes("Summary 2")) && + call.messages.some((message) => message.text.includes("Summary 4")), + ), + ); + }).pipe(Effect.provide(makeLayer(model.generate, optedIn))); +}); + it.effect("continues coverage and handoff lookup beyond the first 500 summaries", () => { const model = citing(); return Effect.gen(function* () { From dcf1aa9bed76168091192263d95d4a10e825fbe6 Mon Sep 17 00:00:00 2001 From: ScriptedAlchemy Date: Mon, 16 Nov 2026 02:20:56 -0800 Subject: [PATCH 04/37] fix(server): roll up roots that end before the first summary gap A pass spent its whole cap on new leaves, so a busy thread never built roll-ups a handoff can fit. Runs of four current roots that end before the first uncovered gap now roll up first. Roots across that gap still wait for the replacement leaf. Co-authored-by: Cursor --- .../ConversationSummaries.test.ts | 9 +++--- .../ConversationSummaries.ts | 17 +++++++---- .../conversationSummaryTree.ts | 28 +++++++++++++++++++ docs/internals/context-handoffs.md | 6 ++-- 4 files changed, 48 insertions(+), 12 deletions(-) diff --git a/apps/server/src/project/conversationSummaries/ConversationSummaries.test.ts b/apps/server/src/project/conversationSummaries/ConversationSummaries.test.ts index 8ae32d1315d9a..559a7805213fa 100644 --- a/apps/server/src/project/conversationSummaries/ConversationSummaries.test.ts +++ b/apps/server/src/project/conversationSummaries/ConversationSummaries.test.ts @@ -1177,11 +1177,10 @@ it.effect("continues coverage and handoff lookup beyond the first 500 summaries" yield* persistSummary(index, [index * 2, index * 2 + 1]); yield* summarize; - yield* summarize; - const leafCalls = model.calls.filter((call) => !isRollup(call)); - assert.equal(leafCalls.length, 1); - assert.equal(leafCalls[0]!.messages[0]!.text, rawText(coveredMessages)); - assert.deepInclude((yield* list).lastPass, { waitingMessages: 0 }); + assert.isTrue(isRollup(model.calls[0]!)); + // Summary 501 covers the two messages just before the uncovered stretch. If the page hid it, + // those messages would be waiting too. + assert.deepInclude((yield* list).lastPass, { waitingMessages: 10 }); const service = yield* ConversationSummaries.ConversationSummaries; const sql = yield* SqlClient.SqlClient; diff --git a/apps/server/src/project/conversationSummaries/ConversationSummaries.ts b/apps/server/src/project/conversationSummaries/ConversationSummaries.ts index 9143dce1eef99..0c6d7e1ba8557 100644 --- a/apps/server/src/project/conversationSummaries/ConversationSummaries.ts +++ b/apps/server/src/project/conversationSummaries/ConversationSummaries.ts @@ -71,6 +71,7 @@ import { isRangeRef, leafPosition, planCondensation, + rootsBeforeFirstGap, type StoredSummary, type SummaryNode, type SummaryTree, @@ -1116,13 +1117,19 @@ const make = Effect.gen(function* () { }); }); - // Leaves first: a replacement leaf must exist before its stretch rolls up, or its old - // neighbours would roll up without it and the broken path could never be rebuilt alone. + // Roll up only roots that end before the first uncovered gap. Roots on the far side of a + // replaced leaf stay put until that leaf exists, or the roll-up would skip the broken path. const nextWork = () => { + const group = planCondensation( + rootsBeforeFirstGap({ + roots: tree.roots, + order: settled.map((source) => conversationSummarySourceKey(source.ref)), + covered, + }), + ); + if (group !== null) return { kind: "condense" as const, group }; const chunk = planLeafChunks({ settled, covered })[0]; - if (chunk !== undefined) return { kind: "leaf" as const, chunk }; - const group = planCondensation(tree.roots); - return group === null ? null : { kind: "condense" as const, group }; + return chunk === undefined ? null : { kind: "leaf" as const, chunk }; }; while (generated < MAX_SUMMARIES_PER_PASS) { const work = nextWork(); diff --git a/apps/server/src/project/conversationSummaries/conversationSummaryTree.ts b/apps/server/src/project/conversationSummaries/conversationSummaryTree.ts index 35be5d26e8980..ed3e37d9e4e6a 100644 --- a/apps/server/src/project/conversationSummaries/conversationSummaryTree.ts +++ b/apps/server/src/project/conversationSummaries/conversationSummaryTree.ts @@ -1,5 +1,6 @@ import { conversationSummarySourceIdentity, + conversationSummarySourceKey, type ConversationSummaryRangeRef, type ConversationSummarySourceRef, } from "@t3tools/contracts"; @@ -124,6 +125,33 @@ export function buildSummaryTree( }; } +/** + * Current roots whose ranges all end before the first uncovered source. A gap splits the forest, + * so a roll-up cannot join the neighbours of a missing leaf. + */ +export function rootsBeforeFirstGap(input: { + readonly roots: ReadonlyArray; + readonly order: ReadonlyArray; + readonly covered: ReadonlySet; +}): ReadonlyArray { + const gapAt = input.order.findIndex((key) => !input.covered.has(key)); + if (gapAt === -1) return input.roots; + const indexByKey = new Map(input.order.map((key, index) => [key, index])); + const prefix: Array = []; + for (const root of input.roots) { + const positions = root.leafSources.map((source) => + indexByKey.get(conversationSummarySourceKey(source)), + ); + if ( + positions.length === 0 || + positions.some((position) => position === undefined || position >= gapAt) + ) + break; + prefix.push(root); + } + return prefix; +} + /** * The next roots to condense, or null. It takes the oldest run of four adjacent roots in which at * least three share the run's greatest depth, preferring the lowest such depth. That keeps depth diff --git a/docs/internals/context-handoffs.md b/docs/internals/context-handoffs.md index 1e8f4fe85d034..6687f78788401 100644 --- a/docs/internals/context-handoffs.md +++ b/docs/internals/context-handoffs.md @@ -43,8 +43,10 @@ roots and the exact ranges beneath a roll-up are derived from the rows on every stored, so there is no second owner of structure or validity to keep in sync. A roll-up is current only while every range beneath it is; a stale leaf therefore withholds its ancestors' text, and the pass deletes a dead roll-up (unless a handoff references it) so its current children become roots -again. The pass generates any pending leaf before it rolls up: otherwise the old neighbours of a -replaced leaf would roll up without it, and more than the broken path would be summarized again. +again. The pass rolls up a run of four current roots when that run ends before the first uncovered +gap, and makes a new leaf only after those runs. A gap keeps the roots on its far side out of +that run, so the neighbours of a replaced leaf are not rolled up without the replacement. +Doing so would summarize more than the broken path, and that path could not be rebuilt on its own. A roll-up offer carries no delivered-knowledge evidence, unlike a leaf offer: the evidence of a few hundred items would never fit beside it. Roll-ups are capped by rendered bytes, as delivery measures them, so several fit beside the verbatim tail of a 16 KB handoff. From 01fd8a85243cffaae9798bfc42fdf0bbd138e49a Mon Sep 17 00:00:00 2001 From: ScriptedAlchemy Date: Mon, 16 Nov 2026 02:23:35 -0800 Subject: [PATCH 05/37] test(server): a bad summary chunk should not stall the thread Empty or invalid output from the oldest chunk fails the whole pass, so the next pass retries that chunk and later stretches stay uncovered. A timeout should still fail the pass. Co-authored-by: Cursor --- .../ConversationSummaries.test.ts | 94 +++++++++++++++++++ 1 file changed, 94 insertions(+) diff --git a/apps/server/src/project/conversationSummaries/ConversationSummaries.test.ts b/apps/server/src/project/conversationSummaries/ConversationSummaries.test.ts index 559a7805213fa..5bf8cfc04a9d3 100644 --- a/apps/server/src/project/conversationSummaries/ConversationSummaries.test.ts +++ b/apps/server/src/project/conversationSummaries/ConversationSummaries.test.ts @@ -669,6 +669,100 @@ it.effect("records an unavailable model as a failed pass without publishing a su }).pipe(Effect.provide(makeLayer(model.generate, optedIn))); }); +it.effect.each([ + "OpenCode returned empty output.", + "OpenCode returned invalid structured output.", +] as const)("summarizes the next stretch after %s", (detail) => { + const model = scripted((input) => + input.messages[0]?.text === rawText(0) + ? Effect.fail(new TextGenerationError({ operation: "generateConversationSummary", detail })) + : Effect.succeed({ + statements: [{ text: "The later stretch.", citations: [input.messages[0]!.ref] }], + }), + ); + return Effect.gen(function* () { + // 32 settled messages: one full leaf, then a second leaf of eight. + yield* seedThread(38); + const first = yield* summarize; + assert.isTrue(first.hasMore); + assert.equal(model.calls.filter((call) => call.messages[0]?.text === rawText(0)).length, 1); + assert.equal(model.calls.filter((call) => call.messages[0]?.text === rawText(24)).length, 1); + const covered = (yield* list).summaries.flatMap((read) => + read.state === "available" + ? read.summary.sources.flatMap((source) => + source.kind === "message" ? [source.messageId] : [], + ) + : [], + ); + assert.notInclude(covered, messageId(0)); + assert.include(covered, messageId(24)); + + const second = yield* summarize; + assert.isFalse(second.hasMore); + assert.equal(model.calls.filter((call) => call.messages[0]?.text === rawText(0)).length, 2); + assert.include((yield* list).lastPass?.reason ?? "", detail); + + const calls = model.calls.length; + const third = yield* summarize; + assert.isFalse(third.hasMore); + assert.equal(model.calls.length, calls); + const service = yield* ConversationSummaries.ConversationSummaries; + const offered = yield* service.forHandoff({ + projectId, + handoffs: [yield* prepareHandoff(38)], + itemIds: new Set(Array.from({ length: 32 }, (_, index) => itemId(index))), + }); + const offeredIds = offered.flatMap((offer) => offer.coveredItemIds); + assert.notInclude(offeredIds, itemId(0)); + assert.include(offeredIds, itemId(24)); + }).pipe(Effect.provide(makeLayer(model.generate, optedIn))); +}); + +it.effect("summarizes the next stretch when the model cites none of the chunk", () => { + const model = scripted((input) => + Effect.succeed({ + statements: [ + { + text: input.messages[0]?.text === rawText(0) ? "Uncited." : "The later stretch.", + citations: input.messages[0]?.text === rawText(0) ? ["M999"] : [input.messages[0]!.ref], + }, + ], + }), + ); + return Effect.gen(function* () { + yield* seedThread(38); + yield* summarize; + assert.equal(model.calls.filter((call) => call.messages[0]?.text === rawText(24)).length, 1); + assert.notInclude( + (yield* list).summaries.flatMap((read) => + read.state === "available" + ? read.summary.sources.flatMap((source) => + source.kind === "message" ? [source.messageId] : [], + ) + : [], + ), + messageId(0), + ); + }).pipe(Effect.provide(makeLayer(model.generate, optedIn))); +}); + +it.effect("retries a timed-out summary chunk instead of skipping to the next stretch", () => { + const model = scripted(() => + Effect.fail( + new TextGenerationError({ + operation: "generateConversationSummary", + detail: "OpenCode did not finish generating in time.", + }), + ), + ); + return Effect.gen(function* () { + yield* seedThread(38); + assert.instanceOf(yield* summarize.pipe(Effect.flip), ConversationSummaryPassError); + assert.equal(model.calls.length, 1); + assert.deepEqual((yield* list).summaries, []); + }).pipe(Effect.provide(makeLayer(model.generate, optedIn))); +}); + it.effect( "covers every range of a long source and offers it only after all ranges are summarized", () => { From b0a0f8c4d0b6156f6d8b925e7511c7635d688dbf Mon Sep 17 00:00:00 2001 From: ScriptedAlchemy Date: Mon, 16 Nov 2026 02:27:13 -0800 Subject: [PATCH 06/37] fix(server): skip a summary chunk after two empty or invalid replies A deterministic failure of the oldest chunk failed the whole pass, so later stretches never ran. The pass records that failure and continues. After the second one it leaves the chunk uncovered instead of retrying it. Timeouts still fail the pass. Co-authored-by: Cursor --- .../ConversationSummaries.ts | 92 ++++++++++++++++--- .../conversationSummaryTree.ts | 2 + .../contracts/src/conversationSummaries.ts | 14 +++ 3 files changed, 95 insertions(+), 13 deletions(-) diff --git a/apps/server/src/project/conversationSummaries/ConversationSummaries.ts b/apps/server/src/project/conversationSummaries/ConversationSummaries.ts index 0c6d7e1ba8557..c7032691c2bcd 100644 --- a/apps/server/src/project/conversationSummaries/ConversationSummaries.ts +++ b/apps/server/src/project/conversationSummaries/ConversationSummaries.ts @@ -82,6 +82,13 @@ const FRESH_TAIL_MESSAGES = 6; // Bounds the cost of opting in on a long thread; later passes continue where this one stopped. // Leaves and roll-ups share it. const MAX_SUMMARIES_PER_PASS = 3; +// One empty or invalid reply can be a cold start. The second is the chunk, and retrying it +// again only rehashes the thread. +const CHUNK_FAILURES_BEFORE_SKIP = 2; +const isDeterministicChunkFailure = (reason: string) => + /returned empty/i.test(reason) || + /invalid structured output/i.test(reason) || + reason === "The model returned no statements citing the summarized sources."; // Measured as delivery measures it, so a few roll-ups fit beside the verbatim tail of a 16 KB // handoff in any script. The prompt asks for fewer characters, so this cut is a backstop. const CONDENSED_MAX_BYTES = 1_536; @@ -853,6 +860,10 @@ const make = Effect.gen(function* () { ) .map((row) => row.id); }; + const chunkFailures = new Map< + string, + NonNullable[number] + >(); const finish = ( result: ConversationSummaryPass["result"], reason: string | null, @@ -862,16 +873,18 @@ const make = Effect.gen(function* () { ) => cleanupSuperseded(superseded()).pipe( Effect.andThen(DateTime.now), - Effect.flatMap((now) => - recordPass(projectId, threadId, { + Effect.flatMap((now) => { + const stored = [...chunkFailures.values()]; + return recordPass(projectId, threadId, { runId, result, reason, generated, waitingMessages, at: DateTime.formatIso(now), - }), - ), + ...(stored.length === 0 ? {} : { chunkFailures: stored }), + }); + }), Effect.as({ hasMore }), ); if (records.thread.deletedAt !== null) @@ -1117,36 +1130,89 @@ const make = Effect.gen(function* () { }); }); + const priorRows = yield* sql<{ readonly payload_json: string }>` + SELECT payload_json FROM conversation_summary_passes WHERE thread_id = ${threadId} + `; + if (priorRows[0] !== undefined) { + const prior = yield* decodePass(priorRows[0].payload_json).pipe( + Effect.orElseSucceed(() => undefined), + ); + for (const failure of prior?.chunkFailures ?? []) chunkFailures.set(failure.key, failure); + } + const leafChunkKey = (chunk: ReadonlyArray) => + chunk + .map((source) => `${conversationSummarySourceKey(source.ref)}:${source.ref.digest}`) + .join("\n"); + const rollupKey = (group: ReadonlyArray) => + group.map((node) => node.row.id).join("\n"); + const live = new Set(); + for (const chunk of planLeafChunks({ settled, covered })) live.add(leafChunkKey(chunk)); + for (let start = 0; start + 4 <= tree.roots.length; start++) + live.add(rollupKey(tree.roots.slice(start, start + 4))); + for (const key of chunkFailures.keys()) if (!live.has(key)) chunkFailures.delete(key); + // Roll up only roots that end before the first uncovered gap. Roots on the far side of a // replaced leaf stay put until that leaf exists, or the roll-up would skip the broken path. - const nextWork = () => { + const held = (key: string, extra: ReadonlySet) => + chunkFailures.get(key)?.skipped === true || extra.has(key); + const selectWork = (extra: ReadonlySet) => { const group = planCondensation( rootsBeforeFirstGap({ roots: tree.roots, order: settled.map((source) => conversationSummarySourceKey(source.ref)), covered, }), + (run) => !held(rollupKey(run), extra), + ); + if (group !== null) return { kind: "condense" as const, group, key: rollupKey(group) }; + const chunk = planLeafChunks({ settled, covered }).find( + (candidate) => !held(leafChunkKey(candidate), extra), ); - if (group !== null) return { kind: "condense" as const, group }; - const chunk = planLeafChunks({ settled, covered })[0]; - return chunk === undefined ? null : { kind: "leaf" as const, chunk }; + return chunk === undefined + ? null + : { kind: "leaf" as const, chunk, key: leafChunkKey(chunk) }; }; - while (generated < MAX_SUMMARIES_PER_PASS) { - const work = nextWork(); + const blocked = new Set(); + let attempts = 0; + while (generated < MAX_SUMMARIES_PER_PASS && attempts < MAX_SUMMARIES_PER_PASS) { + const work = selectWork(blocked); if (work === null) break; + attempts += 1; const published = work.kind === "leaf" ? yield* summarizeLeaf(work.chunk) : yield* condense(work.group); - if (!published.ok) return yield* failPass(published.reason); + if (!published.ok) { + if (!isDeterministicChunkFailure(published.reason)) + return yield* failPass(published.reason); + const count = (chunkFailures.get(work.key)?.failures ?? 0) + 1; + chunkFailures.set(work.key, { + key: work.key, + failures: count, + ...(count >= CHUNK_FAILURES_BEFORE_SKIP ? { skipped: true } : {}), + reason: published.reason.slice(0, 300), + }); + blocked.add(work.key); + continue; + } + chunkFailures.delete(work.key); rows.set(published.row.id, published.row); rebuild(); generated += 1; } + const skipped = [...chunkFailures.values()].filter((failure) => failure.skipped); + const skipReason = + skipped.length === 0 + ? null + : `Skipped ${skipped.length === 1 ? "a stretch" : `${skipped.length} stretches`} after ${CHUNK_FAILURES_BEFORE_SKIP} empty or invalid summaries. ${skipped[0]!.reason}`.slice( + 0, + 300, + ); return yield* finish( generated > 0 ? "ran" : "skipped", - generated > 0 ? null : "No settled stretch is long enough to summarize yet.", + skipReason ?? + (generated > 0 ? null : "No settled stretch is long enough to summarize yet."), generated, waiting(), - nextWork() !== null, + selectWork(new Set()) !== null, ); }, (effect, { runId }) => diff --git a/apps/server/src/project/conversationSummaries/conversationSummaryTree.ts b/apps/server/src/project/conversationSummaries/conversationSummaryTree.ts index ed3e37d9e4e6a..6340d3b33c98a 100644 --- a/apps/server/src/project/conversationSummaries/conversationSummaryTree.ts +++ b/apps/server/src/project/conversationSummaries/conversationSummaryTree.ts @@ -160,6 +160,7 @@ export function rootsBeforeFirstGap(input: { */ export function planCondensation( roots: ReadonlyArray, + accept: (group: ReadonlyArray) => boolean = () => true, ): ReadonlyArray | null { let best: { readonly start: number; readonly depth: number } | null = null; for (let start = 0; start + CONDENSE_FAN_IN <= roots.length; start++) { @@ -167,6 +168,7 @@ export function planCondensation( const depth = Math.max(...run.map((node) => node.depth)); if ( run.filter((node) => node.depth === depth).length >= CONDENSE_FAN_IN - 1 && + accept(run) && (best === null || depth < best.depth) ) best = { start, depth }; diff --git a/packages/contracts/src/conversationSummaries.ts b/packages/contracts/src/conversationSummaries.ts index 3fd05d6c43490..058409379b5ae 100644 --- a/packages/contracts/src/conversationSummaries.ts +++ b/packages/contracts/src/conversationSummaries.ts @@ -156,6 +156,20 @@ export const ConversationSummaryPass = Schema.Struct({ /** Settled messages still waiting for a summary after this pass. */ waitingMessages: NonNegativeInt, at: IsoDateTime, + /** + * Chunks whose model output was empty or invalid. A skipped chunk stays uncovered, so delivery + * still treats its items as a gap. + */ + chunkFailures: Schema.optionalKey( + Schema.Array( + Schema.Struct({ + key: Schema.String, + failures: NonNegativeInt, + skipped: Schema.optionalKey(Schema.Boolean), + reason: Schema.String, + }), + ), + ), }); export type ConversationSummaryPass = typeof ConversationSummaryPass.Type; From fdac97c470ed1aab24ce9dda26a45aff68b90558 Mon Sep 17 00:00:00 2001 From: ScriptedAlchemy Date: Mon, 16 Nov 2026 02:31:31 -0800 Subject: [PATCH 07/37] docs: clarify why roll-ups stop at the first summary gap Co-Authored-By: Claude Opus 5.5 --- docs/internals/context-handoffs.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/internals/context-handoffs.md b/docs/internals/context-handoffs.md index 6687f78788401..36ded38adc76b 100644 --- a/docs/internals/context-handoffs.md +++ b/docs/internals/context-handoffs.md @@ -45,8 +45,8 @@ only while every range beneath it is; a stale leaf therefore withholds its ances pass deletes a dead roll-up (unless a handoff references it) so its current children become roots again. The pass rolls up a run of four current roots when that run ends before the first uncovered gap, and makes a new leaf only after those runs. A gap keeps the roots on its far side out of -that run, so the neighbours of a replaced leaf are not rolled up without the replacement. -Doing so would summarize more than the broken path, and that path could not be rebuilt on its own. +that run, so the neighbours of a replaced leaf never roll up without the replacement. Rolling +them up early would summarize more than the broken path, which could then not be rebuilt alone. A roll-up offer carries no delivered-knowledge evidence, unlike a leaf offer: the evidence of a few hundred items would never fit beside it. Roll-ups are capped by rendered bytes, as delivery measures them, so several fit beside the verbatim tail of a 16 KB handoff. From d764f743edae2ff0a71be41da9fd2728b2612bb4 Mon Sep 17 00:00:00 2001 From: ScriptedAlchemy Date: Mon, 16 Nov 2026 03:02:48 -0800 Subject: [PATCH 08/37] test(server): a summary pass that steps aside is pruned, and a retrying pass does not absorb a later run's Co-Authored-By: Claude Opus 5.5 --- .../src/orchestration-v2/EffectWorker.test.ts | 63 +++++++++++++++++-- 1 file changed, 57 insertions(+), 6 deletions(-) diff --git a/apps/server/src/orchestration-v2/EffectWorker.test.ts b/apps/server/src/orchestration-v2/EffectWorker.test.ts index 04f58e0864366..8f4f0da534c82 100644 --- a/apps/server/src/orchestration-v2/EffectWorker.test.ts +++ b/apps/server/src/orchestration-v2/EffectWorker.test.ts @@ -259,9 +259,10 @@ it.effect("keeps at most one pending summary pass per thread", () => delayMs: 0, }); assert.isTrue(retried); - const settled = yield* outbox.get(first.id); - assert.isTrue(Option.isSome(settled)); - if (Option.isSome(settled)) assert.notEqual(settled.value.status, "pending"); + assert.equal( + Option.map(yield* outbox.get(first.id), (row) => row.status).pipe(Option.getOrNull), + "cancelled", + ); const pendingContinuation = yield* outbox.get(continuation.id); assert.isTrue(Option.isSome(pendingContinuation)); if (Option.isSome(pendingContinuation)) @@ -279,12 +280,62 @@ it.effect("keeps at most one pending summary pass per thread", () => }); yield* outbox.enqueue([successor]); assert.deepEqual(yield* outbox.reconcileAfterProcessLoss, { requeued: 0, cancelled: 0 }); - const restarted = yield* outbox.get(continuation.id); - assert.isTrue(Option.isSome(restarted)); - if (Option.isSome(restarted)) assert.notEqual(restarted.value.status, "pending"); + assert.equal( + Option.map(yield* outbox.get(continuation.id), (row) => row.status).pipe(Option.getOrNull), + "cancelled", + ); const pendingSuccessor = yield* outbox.get(successor.id); assert.isTrue(Option.isSome(pendingSuccessor)); if (Option.isSome(pendingSuccessor)) assert.equal(pendingSuccessor.value.status, "pending"); + + yield* TestClock.adjust( + Duration.sum(EffectOutbox.SETTLED_EFFECT_RETENTION, Duration.days(1)), + ); + yield* outbox.pruneSettled; + assert.isTrue(Option.isNone(yield* outbox.get(first.id))); + assert.isTrue(Option.isNone(yield* outbox.get(continuation.id))); + }).pipe(Effect.provide(layer)); + }), +); + +it.effect("hands a later run's summary pass to a fresh row when the queued pass is retrying", () => + Effect.gen(function* () { + const threadId = ThreadId.make("thread:summary-retrying"); + const first = conversationSummaryEffect({ + threadId, + runId: RunId.make("run:summary-retrying-a"), + }); + const later = conversationSummaryEffect({ + threadId, + runId: RunId.make("run:summary-retrying-b"), + }); + const layer = EffectOutbox.layer.pipe(Layer.provide(SqlitePersistence.layerMemory)); + yield* Effect.gen(function* () { + const outbox = yield* EffectOutbox.EffectOutboxV2; + const workerId = "summary-retrying"; + yield* outbox.enqueue([first]); + yield* outbox.claimNext({ workerId, lane: "maintenance" }); + assert.isTrue( + yield* outbox.retry({ effectId: first.id, workerId, error: "Timed out.", delayMs: 0 }), + ); + + // The retrying row may exhaust its attempts, so it cannot stand in for this run's pass. + yield* outbox.enqueue([later]); + assert.isTrue(Option.isSome(yield* outbox.get(later.id))); + + const retried = yield* outbox.claimNext({ workerId, lane: "maintenance" }); + assert.deepEqual( + Option.map(retried, (effect) => effect.id), + Option.some(first.id), + ); + assert.isTrue( + yield* outbox.retry({ effectId: first.id, workerId, error: "Timed out.", delayMs: 0 }), + ); + const next = yield* outbox.claimNext({ workerId, lane: "maintenance" }); + assert.deepEqual( + Option.map(next, (effect) => effect.id), + Option.some(later.id), + ); }).pipe(Effect.provide(layer)); }), ); From 83991b3fa927a91d2b4edbc67eb2698231554ba6 Mon Sep 17 00:00:00 2001 From: ScriptedAlchemy Date: Mon, 16 Nov 2026 03:21:49 -0800 Subject: [PATCH 09/37] fix(server): a superseded summary pass is cancelled, and only a fresh pass absorbs a later run's A pass that stepped aside for a pending successor landed as failed, which pruning never deletes, while the restart path marked the same case succeeded. Both now cancel with one reason. A later run's pass collapsed into any pending pass, including one already retrying, so exhausting that retry dropped the later run's summaries. It now collapses only into a pass that has not started. Co-Authored-By: Claude Opus 5.5 --- .../src/orchestration-v2/EffectOutbox.ts | 38 ++++++++++--------- 1 file changed, 20 insertions(+), 18 deletions(-) diff --git a/apps/server/src/orchestration-v2/EffectOutbox.ts b/apps/server/src/orchestration-v2/EffectOutbox.ts index c55c954fe521d..7822fdbe56bef 100644 --- a/apps/server/src/orchestration-v2/EffectOutbox.ts +++ b/apps/server/src/orchestration-v2/EffectOutbox.ts @@ -232,6 +232,7 @@ export const OrchestrationEffectStatusV2 = Schema.Literals([ export type OrchestrationEffectStatusV2 = typeof OrchestrationEffectStatusV2.Type; /** Receipts deduplicate retries, and restart re-enqueues need far less than a week. Retain failed rows to keep deleted-thread worktrees. */ +const SUMMARY_PASS_SUPERSEDED = "Superseded by a pending summary pass for the same thread."; export const SETTLED_EFFECT_RETENTION = Duration.days(7); const PRUNE_BATCH_SIZE = 500; @@ -406,6 +407,17 @@ export const layer: Layer.Layer = La ).pipe(Effect.uninterruptible); }; // Retry backoff must block later effects so turns cannot race a pending rollback. + // A pending pass for the same thread re-reads the whole thread, so this row has nothing left to do. + const summaryPassHasPendingSuccessor = sql` + orchestration_v2_effect_outbox.effect_type = 'conversation-summary.generate' + AND EXISTS ( + SELECT 1 FROM orchestration_v2_effect_outbox AS pending_summary + WHERE pending_summary.thread_id = orchestration_v2_effect_outbox.thread_id + AND pending_summary.effect_type = 'conversation-summary.generate' + AND pending_summary.status = 'pending' + ) + `; + const claimableCandidatePredicate = ( availableBefore?: string, excludeRestartContinuations = false, @@ -516,6 +528,7 @@ export const layer: Layer.Layer = La ) ) -- A running pass may enqueue its successor. Another pending pass would rehash the thread. + -- A retrying pass can still exhaust its attempts, so it does not stand in for this one. AND ${ effect.request.type === "conversation-summary.generate" ? sql`NOT EXISTS ( @@ -523,6 +536,7 @@ export const layer: Layer.Layer = La WHERE pending_summary.thread_id = ${effect.threadId} AND pending_summary.effect_type = 'conversation-summary.generate' AND pending_summary.status = 'pending' + AND pending_summary.attempt_count = 0 )` : sql`1 = 1` } @@ -631,19 +645,13 @@ export const layer: Layer.Layer = La const coveredRows = yield* sql<{ readonly effect_id: string }>` UPDATE orchestration_v2_effect_outbox SET - status = 'succeeded', + status = 'cancelled', lease_owner = NULL, completed_at = ${now}, updated_at = ${now}, - last_error = NULL + last_error = ${SUMMARY_PASS_SUPERSEDED} WHERE status = 'running' - AND effect_type = 'conversation-summary.generate' - AND EXISTS ( - SELECT 1 FROM orchestration_v2_effect_outbox AS pending_summary - WHERE pending_summary.thread_id = orchestration_v2_effect_outbox.thread_id - AND pending_summary.effect_type = 'conversation-summary.generate' - AND pending_summary.status = 'pending' - ) + AND ${summaryPassHasPendingSuccessor} RETURNING effect_id `; const requeuedRows = yield* sql<{ readonly effect_id: string }>` @@ -792,21 +800,15 @@ export const layer: Layer.Layer = La const yielded = yield* sql<{ readonly effect_id: string }>` UPDATE orchestration_v2_effect_outbox SET - status = 'failed', + status = 'cancelled', lease_owner = NULL, completed_at = ${nowIso}, updated_at = ${nowIso}, - last_error = ${error} + last_error = ${SUMMARY_PASS_SUPERSEDED} WHERE effect_id = ${effectId} AND status = 'running' AND lease_owner = ${workerId} - AND effect_type = 'conversation-summary.generate' - AND EXISTS ( - SELECT 1 FROM orchestration_v2_effect_outbox AS pending_summary - WHERE pending_summary.thread_id = orchestration_v2_effect_outbox.thread_id - AND pending_summary.effect_type = 'conversation-summary.generate' - AND pending_summary.status = 'pending' - ) + AND ${summaryPassHasPendingSuccessor} RETURNING effect_id `; if (yielded.length === 1) { From bb93b9474c05d5382d3434b3c75818fb70225c62 Mon Sep 17 00:00:00 2001 From: ScriptedAlchemy Date: Mon, 16 Nov 2026 03:22:46 -0800 Subject: [PATCH 10/37] test: empty and unreadable model replies carry a typed kind that summaries act on Co-Authored-By: Claude Opus 5.5 --- .../ConversationSummaries.test.ts | 10 ++++++---- .../server/src/textGeneration/TextGenerators.test.ts | 12 ++++++++++++ .../src/server/textGenerationOperations.test.ts | 1 + .../src/server/textGeneration.test.ts | 1 + .../provider-pi/src/server/textGeneration.test.ts | 2 ++ 5 files changed, 22 insertions(+), 4 deletions(-) diff --git a/apps/server/src/project/conversationSummaries/ConversationSummaries.test.ts b/apps/server/src/project/conversationSummaries/ConversationSummaries.test.ts index 5bf8cfc04a9d3..90f80ae0d46a7 100644 --- a/apps/server/src/project/conversationSummaries/ConversationSummaries.test.ts +++ b/apps/server/src/project/conversationSummaries/ConversationSummaries.test.ts @@ -670,12 +670,14 @@ it.effect("records an unavailable model as a failed pass without publishing a su }); it.effect.each([ - "OpenCode returned empty output.", - "OpenCode returned invalid structured output.", -] as const)("summarizes the next stretch after %s", (detail) => { + { kind: "empty", detail: "Router returned no text." }, + { kind: "invalid-output", detail: "Router returned a reply T3 Code couldn't read." }, +] as const)("summarizes the next stretch after $kind output", ({ kind, detail }) => { const model = scripted((input) => input.messages[0]?.text === rawText(0) - ? Effect.fail(new TextGenerationError({ operation: "generateConversationSummary", detail })) + ? Effect.fail( + new TextGenerationError({ operation: "generateConversationSummary", detail, kind }), + ) : Effect.succeed({ statements: [{ text: "The later stretch.", citations: [input.messages[0]!.ref] }], }), diff --git a/apps/server/src/textGeneration/TextGenerators.test.ts b/apps/server/src/textGeneration/TextGenerators.test.ts index 0806789b97fc9..91df3ec53e38a 100644 --- a/apps/server/src/textGeneration/TextGenerators.test.ts +++ b/apps/server/src/textGeneration/TextGenerators.test.ts @@ -48,12 +48,14 @@ it.effect.each([ path: "/v1/chat/completions", auth: ["authorization", "Bearer secret"], reply: { choices: [{ finish_reason: "stop", message: { content: '{"title":"Fix login"}' } }] }, + empty: { choices: [{ finish_reason: "stop", message: { content: " " } }] }, }, { kind: "anthropic", path: "/v1/messages", auth: ["x-api-key", "secret"], reply: { stop_reason: "end_turn", content: [{ type: "text", text: '{"title":"Fix login"}' }] }, + empty: { stop_reason: "end_turn", content: [] }, }, ] as const)("$kind generates structured text with its API's request shape", (api) => Effect.gen(function* () { @@ -84,6 +86,16 @@ it.effect.each([ run!(request).pipe(Effect.provideService(FetchHttpClient.Fetch, upstream)), ); expect(failure.detail).toMatch(/rejected the API key: Incorrect API key provided$/); + expect(failure.kind).toBeUndefined(); + + const kindOf = (reply: unknown) => { + upstream.mockResolvedValueOnce(Response.json(reply)); + return Effect.flip( + run!(request).pipe(Effect.provideService(FetchHttpClient.Fetch, upstream)), + ).pipe(Effect.map((error) => error.kind)); + }; + expect(yield* kindOf(api.empty)).toBe("empty"); + expect(yield* kindOf({ unexpected: true })).toBe("invalid-output"); }), ); diff --git a/packages/provider-core/src/server/textGenerationOperations.test.ts b/packages/provider-core/src/server/textGenerationOperations.test.ts index 30f9aead5b135..cd4e7f7417098 100644 --- a/packages/provider-core/src/server/textGenerationOperations.test.ts +++ b/packages/provider-core/src/server/textGenerationOperations.test.ts @@ -154,6 +154,7 @@ it.effect("rejects extra evaluator output fields before a decoder can discard th JSON.stringify(output), ).pipe(Effect.flip); expect(error.detail).toContain("invalid structured output"); + expect(error.kind).toBe("invalid-output"); } }), ); diff --git a/packages/provider-opencode/src/server/textGeneration.test.ts b/packages/provider-opencode/src/server/textGeneration.test.ts index c5f17d44523bc..65b0556747976 100644 --- a/packages/provider-opencode/src/server/textGeneration.test.ts +++ b/packages/provider-opencode/src/server/textGeneration.test.ts @@ -711,6 +711,7 @@ it.layer(layerOpenCodeTextGenerationTest)("OpenCodeTextGeneration", (it) => { .pipe(Effect.flip); expect(error.message).toContain("OpenCode returned empty output."); + expect(error.kind).toBe("empty"); expect(error.cause).toMatchObject({ _tag: "OpenCodeTextGenerationEmptyOutputError", operation: "generateCommitMessage", diff --git a/packages/provider-pi/src/server/textGeneration.test.ts b/packages/provider-pi/src/server/textGeneration.test.ts index b66129ee9a2b1..d5eb382f79bde 100644 --- a/packages/provider-pi/src/server/textGeneration.test.ts +++ b/packages/provider-pi/src/server/textGeneration.test.ts @@ -297,6 +297,7 @@ it.effect("reports Pi's turn error when the reply is empty", () => assert.equal(error._tag, "TextGenerationError"); assert.equal(error.detail, "Pi could not generate text: the model provider returned HTTP 401."); + assert.isUndefined(error.kind); }).pipe(Effect.provide(NodeServices.layer)), ); @@ -330,6 +331,7 @@ it.effect("drops an earlier error once a later attempt succeeds", () => ]).pipe(Effect.flip); assert.equal(error.detail, "Pi returned empty output."); + assert.equal(error.kind, "empty"); }).pipe(Effect.provide(NodeServices.layer)), ); From cb1974b3abfd8be71bdc868a5ccd8006ee829ec7 Mon Sep 17 00:00:00 2001 From: ScriptedAlchemy Date: Mon, 16 Nov 2026 03:23:21 -0800 Subject: [PATCH 11/37] fix(server): summaries classify an unusable reply by its typed kind, not its wording Summaries decided whether a failed chunk could be skipped by matching error messages, which missed the custom text generators' "returned no text." and "couldn't read" replies. TextGenerationError now carries kind: empty or invalid-output, set where each adapter produces such a reply, and passed through the Claude and Codex driver wrappers that used to drop it. Outages, timeouts, sign-in, cancellation and unsupported providers stay unclassified. Co-Authored-By: Claude Opus 5.5 --- .../ConversationSummaries.ts | 22 ++++++++------- .../src/provider/Drivers/ClaudeDriver.ts | 6 ++++- .../src/provider/Drivers/CodexDriver.ts | 10 +++---- .../provider/Drivers/CodexManagedProvider.ts | 13 ++++----- .../AntigravityTextGeneration.ts | 1 + .../textGeneration/ClaudeTextGeneration.ts | 1 + .../src/textGeneration/CodexTextGeneration.ts | 1 + .../src/textGeneration/TextGenerators.ts | 1 + .../textGeneration/textGeneratorDrivers.ts | 27 ++++++++++++++++--- packages/contracts/src/git.ts | 8 ++++++ .../src/server/textGenerationOperations.ts | 1 + .../src/server/textGeneration.ts | 1 + .../src/server/textGeneration.ts | 12 ++++----- .../src/server/textGeneration.ts | 1 + .../src/server/textGeneration.ts | 1 + .../src/server/v2/textGeneration.ts | 1 + .../provider-pi/src/server/textGeneration.ts | 9 ++++--- 17 files changed, 79 insertions(+), 37 deletions(-) diff --git a/apps/server/src/project/conversationSummaries/ConversationSummaries.ts b/apps/server/src/project/conversationSummaries/ConversationSummaries.ts index c7032691c2bcd..2fdf8ef268944 100644 --- a/apps/server/src/project/conversationSummaries/ConversationSummaries.ts +++ b/apps/server/src/project/conversationSummaries/ConversationSummaries.ts @@ -85,10 +85,6 @@ const MAX_SUMMARIES_PER_PASS = 3; // One empty or invalid reply can be a cold start. The second is the chunk, and retrying it // again only rehashes the thread. const CHUNK_FAILURES_BEFORE_SKIP = 2; -const isDeterministicChunkFailure = (reason: string) => - /returned empty/i.test(reason) || - /invalid structured output/i.test(reason) || - reason === "The model returned no statements citing the summarized sources."; // Measured as delivery measures it, so a few roll-ups fit beside the verbatim tail of a 16 KB // handoff in any script. The prompt asks for fewer characters, so this cut is a backstop. const CONDENSED_MAX_BYTES = 1_536; @@ -1030,10 +1026,14 @@ const make = Effect.gen(function* () { Effect.map((result) => ({ ok: true as const, statements: result.statements })), Effect.catchTags({ TextGenerationError: (error) => - Effect.succeed({ ok: false as const, detail: error.detail }), + Effect.succeed({ + ok: false as const, + reason: error.detail, + unusableReply: error.kind !== undefined, + }), }), ); - if (!reply.ok) return { ok: false as const, reason: reply.detail }; + if (!reply.ok) return reply; const cited: Array = []; for (const statement of reply.statements.slice(0, MAX_STATEMENTS)) { const text = statement.text.trim().slice(0, MAX_STATEMENT_CHARS).trim(); @@ -1049,10 +1049,15 @@ const make = Effect.gen(function* () { return { ok: false as const, reason: "The model returned no statements citing the summarized sources.", + unusableReply: true, }; const current = yield* readRanges({ projectId, threadId, sources: input.ranges }); if (current.some((source) => source.state !== "available")) - return { ok: false as const, reason: "A source changed while it was being summarized." }; + return { + ok: false as const, + reason: "A source changed while it was being summarized.", + unusableReply: false, + }; // A child id already digests the child's exact ranges, so it stands in for a digest. const id = `summary:${yield* digest( [ @@ -1181,8 +1186,7 @@ const make = Effect.gen(function* () { const published = work.kind === "leaf" ? yield* summarizeLeaf(work.chunk) : yield* condense(work.group); if (!published.ok) { - if (!isDeterministicChunkFailure(published.reason)) - return yield* failPass(published.reason); + if (!published.unusableReply) return yield* failPass(published.reason); const count = (chunkFailures.get(work.key)?.failures ?? 0) + 1; chunkFailures.set(work.key, { key: work.key, diff --git a/apps/server/src/provider/Drivers/ClaudeDriver.ts b/apps/server/src/provider/Drivers/ClaudeDriver.ts index a248f177e2bd5..36e5718fcb8ab 100644 --- a/apps/server/src/provider/Drivers/ClaudeDriver.ts +++ b/apps/server/src/provider/Drivers/ClaudeDriver.ts @@ -406,7 +406,11 @@ export const ClaudeDriver: ProviderDriver< const protect = (operation: string, task: Effect.Effect) => withAccess(task).pipe( Effect.scoped, - Effect.mapError((cause) => new TextGenerationError({ operation, detail: cause.detail })), + Effect.mapError((cause) => + cause._tag === "TextGenerationError" + ? cause + : new TextGenerationError({ operation, detail: cause.detail }), + ), ); const textGeneration: ProviderInstance["textGeneration"] = auth ? { diff --git a/apps/server/src/provider/Drivers/CodexDriver.ts b/apps/server/src/provider/Drivers/CodexDriver.ts index 7d14b48c4aa54..2a81d26f8c862 100644 --- a/apps/server/src/provider/Drivers/CodexDriver.ts +++ b/apps/server/src/provider/Drivers/CodexDriver.ts @@ -451,12 +451,10 @@ export const CodexDriver: ProviderDriver< const protect = (operation: string, task: Effect.Effect) => withAccess(task).pipe( Effect.scoped, - Effect.mapError( - (cause) => - new TextGenerationError({ - operation, - detail: cause.detail, - }), + Effect.mapError((cause) => + cause._tag === "TextGenerationError" + ? cause + : new TextGenerationError({ operation, detail: cause.detail }), ), ); const textGeneration: ProviderInstance["textGeneration"] = auth diff --git a/apps/server/src/provider/Drivers/CodexManagedProvider.ts b/apps/server/src/provider/Drivers/CodexManagedProvider.ts index c0041be317593..fca25d9894151 100644 --- a/apps/server/src/provider/Drivers/CodexManagedProvider.ts +++ b/apps/server/src/provider/Drivers/CodexManagedProvider.ts @@ -273,12 +273,13 @@ export const makeManagedCodexProvider = Effect.fn("makeManagedCodexProvider")(fu const protect = (operation: string, effect: Effect.Effect) => runtime.auth.controller.withAccess!(effect).pipe( Effect.scoped, - Effect.mapError( - (cause) => - new TextGenerationError({ - operation, - detail: "detail" in cause ? cause.detail : "Codex text generation failed.", - }), + Effect.mapError((cause) => + cause._tag === "TextGenerationError" + ? cause + : new TextGenerationError({ + operation, + detail: "detail" in cause ? cause.detail : "Codex text generation failed.", + }), ), ); const textGeneration: ProviderInstance["textGeneration"] = { diff --git a/apps/server/src/textGeneration/AntigravityTextGeneration.ts b/apps/server/src/textGeneration/AntigravityTextGeneration.ts index cc3e7d59a49f3..9f351d344883d 100644 --- a/apps/server/src/textGeneration/AntigravityTextGeneration.ts +++ b/apps/server/src/textGeneration/AntigravityTextGeneration.ts @@ -302,6 +302,7 @@ export const makeAntigravityTextGeneration = Effect.fn("makeAntigravityTextGener return yield* new TextGenerationError({ operation, detail: "Antigravity returned empty text generation output.", + kind: "empty", }); } return yield* TextGenerationOperations.decodeJsonReply(input, "Antigravity", rawResult); diff --git a/apps/server/src/textGeneration/ClaudeTextGeneration.ts b/apps/server/src/textGeneration/ClaudeTextGeneration.ts index b5eef19186a77..9e1d59a3dba77 100644 --- a/apps/server/src/textGeneration/ClaudeTextGeneration.ts +++ b/apps/server/src/textGeneration/ClaudeTextGeneration.ts @@ -374,6 +374,7 @@ export const makeClaudeTextGeneration = Effect.fn("makeClaudeTextGeneration")(fu new TextGenerationError({ operation, detail: "Claude returned invalid structured output.", + kind: "invalid-output", cause, }), ), diff --git a/apps/server/src/textGeneration/CodexTextGeneration.ts b/apps/server/src/textGeneration/CodexTextGeneration.ts index 65f42c4f8d705..7ec403656bd7a 100644 --- a/apps/server/src/textGeneration/CodexTextGeneration.ts +++ b/apps/server/src/textGeneration/CodexTextGeneration.ts @@ -698,6 +698,7 @@ export const makeCodexTextGeneration = Effect.fn("makeCodexTextGeneration")(func new TextGenerationError({ operation, detail: "Codex returned invalid structured output.", + kind: "invalid-output", cause, }), ), diff --git a/apps/server/src/textGeneration/TextGenerators.ts b/apps/server/src/textGeneration/TextGenerators.ts index 8ffbda4fffb41..9b12bf4ee1c5a 100644 --- a/apps/server/src/textGeneration/TextGenerators.ts +++ b/apps/server/src/textGeneration/TextGenerators.ts @@ -99,6 +99,7 @@ export const make = Effect.gen(function* () { new TextGenerationError({ operation: request.operation, detail: error.detail, + ...(error.kind === undefined ? {} : { kind: error.kind }), cause: error, }), ), diff --git a/apps/server/src/textGeneration/textGeneratorDrivers.ts b/apps/server/src/textGeneration/textGeneratorDrivers.ts index ef7860c84dbc9..419d614516412 100644 --- a/apps/server/src/textGeneration/textGeneratorDrivers.ts +++ b/apps/server/src/textGeneration/textGeneratorDrivers.ts @@ -1,4 +1,8 @@ -import type { TextGeneratorKind, TextGeneratorModel } from "@t3tools/contracts"; +import { + TextGenerationFailureKind, + type TextGeneratorKind, + type TextGeneratorModel, +} from "@t3tools/contracts"; import * as Effect from "effect/Effect"; import * as Schema from "effect/Schema"; import { @@ -19,7 +23,11 @@ export interface TextGeneratorConnection { /** Why a model API call failed, worded for the person who configured it. */ export class TextGeneratorRequestError extends Schema.TaggedError()( "TextGeneratorRequestError", - { detail: Schema.String, cause: Schema.optional(Schema.Defect()) }, + { + detail: Schema.String, + kind: Schema.optional(TextGenerationFailureKind), + cause: Schema.optional(Schema.Defect()), + }, ) {} export interface TextGeneratorDriver { @@ -96,6 +104,7 @@ const sendJson = Effect.fn("TextGenerator.sendJson")(function* new TextGeneratorRequestError({ detail: `${label} returned a reply T3 Code couldn't read.`, + kind: "invalid-output", cause, }), ), @@ -154,7 +163,12 @@ const openAICompatible: TextGeneratorDriver = { } return text ? Effect.succeed(text) - : Effect.fail(new TextGeneratorRequestError({ detail: `${label} returned no text.` })); + : Effect.fail( + new TextGeneratorRequestError({ + detail: `${label} returned no text.`, + kind: "empty", + }), + ); }), withTimeout(label, GENERATE_TIMEOUT), ); @@ -218,7 +232,12 @@ const anthropic: TextGeneratorDriver = { .trim(); return text ? Effect.succeed(text) - : Effect.fail(new TextGeneratorRequestError({ detail: `${label} returned no text.` })); + : Effect.fail( + new TextGeneratorRequestError({ + detail: `${label} returned no text.`, + kind: "empty", + }), + ); }), withTimeout(label, GENERATE_TIMEOUT), ); diff --git a/packages/contracts/src/git.ts b/packages/contracts/src/git.ts index 45d68c5e9ca44..81524dea82143 100644 --- a/packages/contracts/src/git.ts +++ b/packages/contracts/src/git.ts @@ -393,11 +393,19 @@ export class GitCommandError extends Schema.TaggedError()("GitC } } +/** + * A reply the model produced but that held no text or no readable result. Unlike an outage or a + * timeout, the same input may keep producing it. + */ +export const TextGenerationFailureKind = Schema.Literals(["empty", "invalid-output"]); +export type TextGenerationFailureKind = typeof TextGenerationFailureKind.Type; + export class TextGenerationError extends Schema.TaggedError()( "TextGenerationError", { operation: Schema.String, detail: Schema.String, + kind: Schema.optional(TextGenerationFailureKind), cause: Schema.optional(Schema.Defect()), }, ) { diff --git a/packages/provider-core/src/server/textGenerationOperations.ts b/packages/provider-core/src/server/textGenerationOperations.ts index 6bab650c27885..d1a9c9c9055af 100644 --- a/packages/provider-core/src/server/textGenerationOperations.ts +++ b/packages/provider-core/src/server/textGenerationOperations.ts @@ -69,6 +69,7 @@ export const decodeJsonReply = ( new TextGenerationError({ operation: request.operation, detail: `${provider} returned invalid structured output.`, + kind: "invalid-output", cause, }), ), diff --git a/packages/provider-cursor/src/server/textGeneration.ts b/packages/provider-cursor/src/server/textGeneration.ts index 51708a63a1b3f..4598cc651a110 100644 --- a/packages/provider-cursor/src/server/textGeneration.ts +++ b/packages/provider-cursor/src/server/textGeneration.ts @@ -247,6 +247,7 @@ export const makeCursorTextGeneration = Effect.fn("makeCursorTextGeneration")(fu return yield* new TextGenerationError({ operation, detail: cursorSdkResultDetail(promptResult), + ...(promptResult.status === "finished" ? { kind: "empty" as const } : {}), ...(promptResult.error ? { cause: promptResult.error } : {}), }); } diff --git a/packages/provider-grok/src/server/textGeneration.ts b/packages/provider-grok/src/server/textGeneration.ts index 3be9e0c9122cf..df4274136412e 100644 --- a/packages/provider-grok/src/server/textGeneration.ts +++ b/packages/provider-grok/src/server/textGeneration.ts @@ -112,13 +112,11 @@ export const makeGrokTextGeneration = Effect.fn("makeGrokTextGeneration")(functi const trimmed = (yield* Ref.get(outputRef)).trim(); if (!trimmed) { - return yield* new TextGenerationError({ - operation, - detail: - promptResult.stopReason === "cancelled" - ? "Grok ACP request was cancelled." - : "Grok Agent returned empty output.", - }); + return yield* new TextGenerationError( + promptResult.stopReason === "cancelled" + ? { operation, detail: "Grok ACP request was cancelled." } + : { operation, detail: "Grok Agent returned empty output.", kind: "empty" }, + ); } return yield* TextGenerationOperations.decodeJsonReply(request, "Grok Agent", trimmed); diff --git a/packages/provider-muse/src/server/textGeneration.ts b/packages/provider-muse/src/server/textGeneration.ts index 81ce92be9aec5..f986d27b1a34c 100644 --- a/packages/provider-muse/src/server/textGeneration.ts +++ b/packages/provider-muse/src/server/textGeneration.ts @@ -281,6 +281,7 @@ export const makeMuseTextGeneration = Effect.fn("makeMuseTextGeneration")(functi new TextGenerationError({ operation, detail: "Muse returned invalid structured output.", + kind: "invalid-output", cause, }), ), diff --git a/packages/provider-opencode/src/server/textGeneration.ts b/packages/provider-opencode/src/server/textGeneration.ts index efc0e5483e75d..f71cb10c96b1b 100644 --- a/packages/provider-opencode/src/server/textGeneration.ts +++ b/packages/provider-opencode/src/server/textGeneration.ts @@ -396,6 +396,7 @@ export const makeOpenCodeTextGeneration = Effect.fn("makeOpenCodeTextGeneration" new TextGenerationError({ operation: cause.operation, detail: "OpenCode returned empty output.", + kind: "empty", cause, }), ), diff --git a/packages/provider-opencode/src/server/v2/textGeneration.ts b/packages/provider-opencode/src/server/v2/textGeneration.ts index d38c7a1f3ce17..5ad7086263824 100644 --- a/packages/provider-opencode/src/server/v2/textGeneration.ts +++ b/packages/provider-opencode/src/server/v2/textGeneration.ts @@ -235,6 +235,7 @@ const runOnServer = Effect.fn("Opencode2TextGeneration.runOnServer")(function* ( return yield* new TextGenerationError({ operation: input.operation, detail: "OpenCode returned empty output.", + kind: "empty", }); } return result.text; diff --git a/packages/provider-pi/src/server/textGeneration.ts b/packages/provider-pi/src/server/textGeneration.ts index 7bf9764781aa3..01a6273585b60 100644 --- a/packages/provider-pi/src/server/textGeneration.ts +++ b/packages/provider-pi/src/server/textGeneration.ts @@ -214,10 +214,11 @@ export const makePiTextGeneration = Effect.fn("makePiTextGeneration")(function* ? (data as { text: string }).text.trim() : ""; if (!text) { - return yield* new TextGenerationError({ - operation, - detail: turnError ?? "Pi returned empty output.", - }); + return yield* new TextGenerationError( + turnError === undefined + ? { operation, detail: "Pi returned empty output.", kind: "empty" } + : { operation, detail: turnError }, + ); } return yield* TextGenerationOperations.decodeJsonReply(request, "Pi", text); }, From 2977ca73c9603bb5d94020fb34304a5e1d7fc5cb Mon Sep 17 00:00:00 2001 From: ScriptedAlchemy Date: Mon, 16 Nov 2026 03:24:21 -0800 Subject: [PATCH 12/37] test(server): a skipped summary stretch needs other stretches to succeed, expires with the model, and does not block roll-ups Co-Authored-By: Claude Opus 5.5 --- .../ConversationSummaries.test.ts | 127 ++++++++++++------ 1 file changed, 85 insertions(+), 42 deletions(-) diff --git a/apps/server/src/project/conversationSummaries/ConversationSummaries.test.ts b/apps/server/src/project/conversationSummaries/ConversationSummaries.test.ts index 90f80ae0d46a7..533570d0abf44 100644 --- a/apps/server/src/project/conversationSummaries/ConversationSummaries.test.ts +++ b/apps/server/src/project/conversationSummaries/ConversationSummaries.test.ts @@ -669,54 +669,97 @@ it.effect("records an unavailable model as a failed pass without publishing a su }).pipe(Effect.provide(makeLayer(model.generate, optedIn))); }); -it.effect.each([ - { kind: "empty", detail: "Router returned no text." }, - { kind: "invalid-output", detail: "Router returned a reply T3 Code couldn't read." }, -] as const)("summarizes the next stretch after $kind output", ({ kind, detail }) => { +const failingStretch = (kind: "empty" | "invalid-output") => + new TextGenerationError({ + operation: "generateConversationSummary", + detail: + kind === "empty" + ? "Router returned no text." + : "Router returned a reply T3 Code couldn't read.", + kind, + }); + +it.effect.each(["empty", "invalid-output"] as const)( + "skips a stretch whose summary is always %s while other stretches summarize, and rolls up past it", + (kind) => { + const model = scripted((input) => + input.messages[0]?.text === rawText(0) + ? Effect.fail(failingStretch(kind)) + : Effect.succeed({ + statements: [{ text: "A later stretch.", citations: [input.messages[0]!.ref] }], + }), + ); + const firstStretchCalls = () => + model.calls.filter((call) => call.messages[0]?.text === rawText(0)).length; + return Effect.gen(function* () { + // Five full leaves of 24 settled messages. + yield* seedThread(5 * 24 + 6); + yield* summarize; + yield* summarize; + assert.equal(firstStretchCalls(), 2); + const skipped = (yield* list).lastPass; + assert.include(skipped?.reason ?? "", "Skipped a stretch"); + assert.notProperty(skipped, "chunkFailures"); + + yield* summarize; + assert.equal(firstStretchCalls(), 2); + assert.isTrue(isRollup(model.calls.at(-1)!)); + const service = yield* ConversationSummaries.ConversationSummaries; + const offered = yield* service.forHandoff({ + projectId, + handoffs: [yield* prepareHandoff(5 * 24 + 6)], + itemIds: new Set(Array.from({ length: 5 * 24 }, (_, index) => itemId(index))), + }); + const offeredIds = offered.flatMap((offer) => offer.coveredItemIds); + assert.notInclude(offeredIds, itemId(0)); + assert.include(offeredIds, itemId(24)); + + const settings = yield* ServerSettings.ServerSettingsService; + yield* settings.updateSettings({ + projectSettingsOverrides: { [projectId]: { enableConversationSummaries: false } }, + }); + yield* summarize; + yield* settings.updateSettings(optedIn); + yield* summarize; + assert.equal(firstStretchCalls(), 2); + + yield* settings.updateSettings({ + textGenerationModelSelection: { instanceId, model: "gpt-5-mini" }, + }); + yield* summarize; + assert.equal(firstStretchCalls(), 3); + }).pipe(Effect.provide(makeLayer(model.generate, optedIn))); + }, +); + +it.effect("skips nothing while every summary comes back empty", () => { + let down = true; const model = scripted((input) => - input.messages[0]?.text === rawText(0) - ? Effect.fail( - new TextGenerationError({ operation: "generateConversationSummary", detail, kind }), - ) + down + ? Effect.fail(failingStretch("empty")) : Effect.succeed({ - statements: [{ text: "The later stretch.", citations: [input.messages[0]!.ref] }], + statements: [{ text: "Recovered.", citations: [input.messages[0]!.ref] }], }), ); return Effect.gen(function* () { - // 32 settled messages: one full leaf, then a second leaf of eight. - yield* seedThread(38); - const first = yield* summarize; - assert.isTrue(first.hasMore); - assert.equal(model.calls.filter((call) => call.messages[0]?.text === rawText(0)).length, 1); - assert.equal(model.calls.filter((call) => call.messages[0]?.text === rawText(24)).length, 1); - const covered = (yield* list).summaries.flatMap((read) => - read.state === "available" - ? read.summary.sources.flatMap((source) => - source.kind === "message" ? [source.messageId] : [], - ) - : [], + yield* seedThread(5 * 24 + 6); + for (let pass = 0; pass < 3; pass++) assert.isFalse((yield* summarize).hasMore); + assert.deepEqual((yield* list).summaries, []); + + down = false; + const before = model.calls.length; + yield* summarize; + assert.equal(model.calls[before]?.messages[0]?.text, rawText(0)); + assert.include( + (yield* list).summaries.flatMap((read) => + read.state === "available" + ? read.summary.sources.flatMap((source) => + source.kind === "message" ? [source.messageId] : [], + ) + : [], + ), + messageId(0), ); - assert.notInclude(covered, messageId(0)); - assert.include(covered, messageId(24)); - - const second = yield* summarize; - assert.isFalse(second.hasMore); - assert.equal(model.calls.filter((call) => call.messages[0]?.text === rawText(0)).length, 2); - assert.include((yield* list).lastPass?.reason ?? "", detail); - - const calls = model.calls.length; - const third = yield* summarize; - assert.isFalse(third.hasMore); - assert.equal(model.calls.length, calls); - const service = yield* ConversationSummaries.ConversationSummaries; - const offered = yield* service.forHandoff({ - projectId, - handoffs: [yield* prepareHandoff(38)], - itemIds: new Set(Array.from({ length: 32 }, (_, index) => itemId(index))), - }); - const offeredIds = offered.flatMap((offer) => offer.coveredItemIds); - assert.notInclude(offeredIds, itemId(0)); - assert.include(offeredIds, itemId(24)); }).pipe(Effect.provide(makeLayer(model.generate, optedIn))); }); From 8b1ece2b706dfc0b8fc37582319fe49c9e5534ff Mon Sep 17 00:00:00 2001 From: ScriptedAlchemy Date: Mon, 16 Nov 2026 03:27:50 -0800 Subject: [PATCH 13/37] fix(server): an outage skips no summaries, a skip expires with the model, and roll-ups pass a skipped stretch A chunk counted a failure even when every call failed, so an outage or a model without structured output skipped a thread's whole history for good. A failure now counts only when another summary in the same pass succeeded; a pass with no success records the failure and stops its chain. Skip keys digest the summary model with the chunk, so changing the model gives the stretch a new chance. A skipped stretch never gets a leaf, yet it was the first gap, so nothing after it could roll up. It no longer splits the forest; its items stay uncovered, so delivery still replays them. The failure ledger left the client contract. It is stored beside the pass on the server, hashed and capped, and is read before the deleted, archived and summaries-off paths so they no longer wipe it. Co-Authored-By: Claude Opus 5.5 --- .../ConversationSummaries.ts | 118 ++++++++++++------ .../conversationSummaryTree.ts | 6 +- .../contracts/src/conversationSummaries.ts | 14 --- 3 files changed, 87 insertions(+), 51 deletions(-) diff --git a/apps/server/src/project/conversationSummaries/ConversationSummaries.ts b/apps/server/src/project/conversationSummaries/ConversationSummaries.ts index 2fdf8ef268944..6a9ea1b7bcf31 100644 --- a/apps/server/src/project/conversationSummaries/ConversationSummaries.ts +++ b/apps/server/src/project/conversationSummaries/ConversationSummaries.ts @@ -85,6 +85,8 @@ const MAX_SUMMARIES_PER_PASS = 3; // One empty or invalid reply can be a cold start. The second is the chunk, and retrying it // again only rehashes the thread. const CHUNK_FAILURES_BEFORE_SKIP = 2; +// Live keys only survive a pass, so this bounds a thread with many failing stretches. +const MAX_CHUNK_FAILURES = 64; // Measured as delivery measures it, so a few roll-ups fit beside the verbatim tail of a 16 KB // handoff in any script. The prompt asks for fewer characters, so this cut is a backstop. const CONDENSED_MAX_BYTES = 1_536; @@ -124,8 +126,24 @@ const encodeStatements = Schema.encodeSync( Schema.fromJsonString(ConversationSummary.fields.statements), ); const encodeIds = Schema.encodeSync(Schema.fromJsonString(Schema.Array(Schema.String))); +const encodeModelSelection = Schema.encodeSync( + Schema.fromJsonString(ConversationSummary.fields.modelSelection), +); const decodePass = Schema.decodeUnknownEffect(Schema.fromJsonString(ConversationSummaryPass)); -const encodePass = Schema.encodeSync(Schema.fromJsonString(ConversationSummaryPass)); +// Server-only. A key digests the summary model with the chunk, so another model gets a new chance. +const ChunkFailure = Schema.Struct({ + key: Schema.String, + failures: Schema.Int, + skipped: Schema.optionalKey(Schema.Boolean), + reason: Schema.String, +}); +type ChunkFailure = typeof ChunkFailure.Type; +const StoredPass = Schema.Struct({ + ...ConversationSummaryPass.fields, + chunkFailures: Schema.optionalKey(Schema.Array(ChunkFailure)), +}); +const decodeStoredPass = Schema.decodeUnknownEffect(Schema.fromJsonString(StoredPass)); +const encodeStoredPass = Schema.encodeSync(Schema.fromJsonString(StoredPass)); const isConversationSummaryError = Schema.is(ConversationSummaryError); const isConversationSummaryPassError = Schema.is(ConversationSummaryPassError); @@ -765,11 +783,11 @@ const make = Effect.gen(function* () { const recordPass = Effect.fn("ConversationSummaries.recordPass")(function* ( projectId: ProjectId, threadId: ThreadId, - pass: ConversationSummaryPass, + pass: typeof StoredPass.Type, ) { yield* sql` INSERT INTO conversation_summary_passes (thread_id, project_id, payload_json) - VALUES (${threadId}, ${projectId}, ${encodePass(pass)}) + VALUES (${threadId}, ${projectId}, ${encodeStoredPass(pass)}) ON CONFLICT (thread_id) DO UPDATE SET project_id = excluded.project_id, payload_json = excluded.payload_json @@ -856,10 +874,18 @@ const make = Effect.gen(function* () { ) .map((row) => row.id); }; - const chunkFailures = new Map< - string, - NonNullable[number] - >(); + const priorRows = yield* sql<{ readonly payload_json: string }>` + SELECT payload_json FROM conversation_summary_passes WHERE thread_id = ${threadId} + `; + const prior = + priorRows[0] === undefined + ? undefined + : yield* decodeStoredPass(priorRows[0].payload_json).pipe( + Effect.orElseSucceed(() => undefined), + ); + const chunkFailures = new Map( + (prior?.chunkFailures ?? []).map((failure) => [failure.key, failure]), + ); const finish = ( result: ConversationSummaryPass["result"], reason: string | null, @@ -870,7 +896,7 @@ const make = Effect.gen(function* () { cleanupSuperseded(superseded()).pipe( Effect.andThen(DateTime.now), Effect.flatMap((now) => { - const stored = [...chunkFailures.values()]; + const stored = [...chunkFailures.values()].slice(-MAX_CHUNK_FAILURES); return recordPass(projectId, threadId, { runId, result, @@ -1135,49 +1161,61 @@ const make = Effect.gen(function* () { }); }); - const priorRows = yield* sql<{ readonly payload_json: string }>` - SELECT payload_json FROM conversation_summary_passes WHERE thread_id = ${threadId} - `; - if (priorRows[0] !== undefined) { - const prior = yield* decodePass(priorRows[0].payload_json).pipe( - Effect.orElseSucceed(() => undefined), - ); - for (const failure of prior?.chunkFailures ?? []) chunkFailures.set(failure.key, failure); - } + const modelKey = encodeModelSelection(settings.textGenerationModelSelection); + const keys = new Map(); + const keyOf = Effect.fnUntraced(function* (raw: string) { + const known = keys.get(raw); + if (known !== undefined) return known; + const key = yield* digest(`${modelKey}\n${raw}`); + keys.set(raw, key); + return key; + }); const leafChunkKey = (chunk: ReadonlyArray) => chunk .map((source) => `${conversationSummarySourceKey(source.ref)}:${source.ref.digest}`) .join("\n"); const rollupKey = (group: ReadonlyArray) => group.map((node) => node.row.id).join("\n"); - const live = new Set(); - for (const chunk of planLeafChunks({ settled, covered })) live.add(leafChunkKey(chunk)); + for (const chunk of planLeafChunks({ settled, covered })) yield* keyOf(leafChunkKey(chunk)); for (let start = 0; start + 4 <= tree.roots.length; start++) - live.add(rollupKey(tree.roots.slice(start, start + 4))); + yield* keyOf(rollupKey(tree.roots.slice(start, start + 4))); + const live = new Set(keys.values()); for (const key of chunkFailures.keys()) if (!live.has(key)) chunkFailures.delete(key); + const isSkipped = (raw: string) => { + const key = keys.get(raw); + return key !== undefined && chunkFailures.get(key)?.skipped === true; + }; + const held = (raw: string, blocked: ReadonlySet) => + blocked.has(raw) || isSkipped(raw); // Roll up only roots that end before the first uncovered gap. Roots on the far side of a // replaced leaf stay put until that leaf exists, or the roll-up would skip the broken path. - const held = (key: string, extra: ReadonlySet) => - chunkFailures.get(key)?.skipped === true || extra.has(key); - const selectWork = (extra: ReadonlySet) => { + // A skipped stretch gets no replacement, so it is no gap. + const selectWork = (blocked: ReadonlySet) => { + const chunks = planLeafChunks({ settled, covered }); const group = planCondensation( rootsBeforeFirstGap({ roots: tree.roots, order: settled.map((source) => conversationSummarySourceKey(source.ref)), covered, + skipped: new Set( + chunks + .filter((chunk) => isSkipped(leafChunkKey(chunk))) + .flatMap((chunk) => + chunk.map((source) => conversationSummarySourceKey(source.ref)), + ), + ), }), - (run) => !held(rollupKey(run), extra), + (run) => !held(rollupKey(run), blocked), ); if (group !== null) return { kind: "condense" as const, group, key: rollupKey(group) }; - const chunk = planLeafChunks({ settled, covered }).find( - (candidate) => !held(leafChunkKey(candidate), extra), - ); + const chunk = chunks.find((candidate) => !held(leafChunkKey(candidate), blocked)); return chunk === undefined ? null : { kind: "leaf" as const, chunk, key: leafChunkKey(chunk) }; }; const blocked = new Set(); + const failed: Array<{ readonly raw: string; readonly reason: string }> = []; let attempts = 0; while (generated < MAX_SUMMARIES_PER_PASS && attempts < MAX_SUMMARIES_PER_PASS) { const work = selectWork(blocked); @@ -1187,21 +1225,31 @@ const make = Effect.gen(function* () { work.kind === "leaf" ? yield* summarizeLeaf(work.chunk) : yield* condense(work.group); if (!published.ok) { if (!published.unusableReply) return yield* failPass(published.reason); - const count = (chunkFailures.get(work.key)?.failures ?? 0) + 1; - chunkFailures.set(work.key, { - key: work.key, - failures: count, - ...(count >= CHUNK_FAILURES_BEFORE_SKIP ? { skipped: true } : {}), - reason: published.reason.slice(0, 300), - }); + failed.push({ raw: work.key, reason: published.reason }); blocked.add(work.key); continue; } - chunkFailures.delete(work.key); + const key = keys.get(work.key); + if (key !== undefined) chunkFailures.delete(key); rows.set(published.row.id, published.row); rebuild(); generated += 1; } + // With nothing else succeeding, the model may be down or unable to answer at all. Blaming + // the chunk would skip the thread's whole history. + if (generated === 0 && failed.length > 0) + return yield* finish("failed", failed[0]!.reason.slice(0, 300), 0, waiting()); + for (const { raw, reason } of failed) { + const key = yield* keyOf(raw); + const failures = (chunkFailures.get(key)?.failures ?? 0) + 1; + chunkFailures.delete(key); + chunkFailures.set(key, { + key, + failures, + ...(failures >= CHUNK_FAILURES_BEFORE_SKIP ? { skipped: true } : {}), + reason: reason.slice(0, 300), + }); + } const skipped = [...chunkFailures.values()].filter((failure) => failure.skipped); const skipReason = skipped.length === 0 diff --git a/apps/server/src/project/conversationSummaries/conversationSummaryTree.ts b/apps/server/src/project/conversationSummaries/conversationSummaryTree.ts index 6340d3b33c98a..b46a665dd2a9e 100644 --- a/apps/server/src/project/conversationSummaries/conversationSummaryTree.ts +++ b/apps/server/src/project/conversationSummaries/conversationSummaryTree.ts @@ -127,14 +127,16 @@ export function buildSummaryTree( /** * Current roots whose ranges all end before the first uncovered source. A gap splits the forest, - * so a roll-up cannot join the neighbours of a missing leaf. + * so a roll-up cannot join the neighbours of a missing leaf. Skipped sources will get no leaf, so + * they split nothing. */ export function rootsBeforeFirstGap(input: { readonly roots: ReadonlyArray; readonly order: ReadonlyArray; readonly covered: ReadonlySet; + readonly skipped: ReadonlySet; }): ReadonlyArray { - const gapAt = input.order.findIndex((key) => !input.covered.has(key)); + const gapAt = input.order.findIndex((key) => !input.covered.has(key) && !input.skipped.has(key)); if (gapAt === -1) return input.roots; const indexByKey = new Map(input.order.map((key, index) => [key, index])); const prefix: Array = []; diff --git a/packages/contracts/src/conversationSummaries.ts b/packages/contracts/src/conversationSummaries.ts index 058409379b5ae..3fd05d6c43490 100644 --- a/packages/contracts/src/conversationSummaries.ts +++ b/packages/contracts/src/conversationSummaries.ts @@ -156,20 +156,6 @@ export const ConversationSummaryPass = Schema.Struct({ /** Settled messages still waiting for a summary after this pass. */ waitingMessages: NonNegativeInt, at: IsoDateTime, - /** - * Chunks whose model output was empty or invalid. A skipped chunk stays uncovered, so delivery - * still treats its items as a gap. - */ - chunkFailures: Schema.optionalKey( - Schema.Array( - Schema.Struct({ - key: Schema.String, - failures: NonNegativeInt, - skipped: Schema.optionalKey(Schema.Boolean), - reason: Schema.String, - }), - ), - ), }); export type ConversationSummaryPass = typeof ConversationSummaryPass.Type; From d71b7de1b539754dc25822c59f955072c8fd9ac4 Mon Sep 17 00:00:00 2001 From: ScriptedAlchemy Date: Mon, 16 Nov 2026 03:28:33 -0800 Subject: [PATCH 14/37] docs: say what a skipped summary stretch means and that roll-ups pass it Co-Authored-By: Claude Opus 5.5 --- docs/internals/context-handoffs.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/docs/internals/context-handoffs.md b/docs/internals/context-handoffs.md index 36ded38adc76b..11d4cee858dac 100644 --- a/docs/internals/context-handoffs.md +++ b/docs/internals/context-handoffs.md @@ -47,6 +47,11 @@ again. The pass rolls up a run of four current roots when that run ends before t gap, and makes a new leaf only after those runs. A gap keeps the roots on its far side out of that run, so the neighbours of a replaced leaf never roll up without the replacement. Rolling them up early would summarize more than the broken path, which could then not be rebuilt alone. +A stretch is skipped after two passes in which its own summary came back empty or unreadable while +another summary succeeded; a pass where every summary fails blames the model, not the stretch, and +skips nothing. A skipped stretch gets no leaf, so it is not a gap: roll-ups proceed past it. Its +items stay uncovered, and delivery replays them verbatim. Skips are keyed by the summary model, +so choosing another model tries the stretch again. A roll-up offer carries no delivered-knowledge evidence, unlike a leaf offer: the evidence of a few hundred items would never fit beside it. Roll-ups are capped by rendered bytes, as delivery measures them, so several fit beside the verbatim tail of a 16 KB handoff. From c34e8a31c753b239c9a5db4e03b19454534b2b2b Mon Sep 17 00:00:00 2001 From: ScriptedAlchemy Date: Mon, 16 Nov 2026 03:48:57 -0800 Subject: [PATCH 15/37] test(server): three summaries that fail together do not stop a thread's progress Co-Authored-By: Claude Opus 5.5 --- .../ConversationSummaries.test.ts | 56 +++++++++++++++++++ 1 file changed, 56 insertions(+) diff --git a/apps/server/src/project/conversationSummaries/ConversationSummaries.test.ts b/apps/server/src/project/conversationSummaries/ConversationSummaries.test.ts index 533570d0abf44..b1e5bf62c6d01 100644 --- a/apps/server/src/project/conversationSummaries/ConversationSummaries.test.ts +++ b/apps/server/src/project/conversationSummaries/ConversationSummaries.test.ts @@ -763,6 +763,62 @@ it.effect("skips nothing while every summary comes back empty", () => { }).pipe(Effect.provide(makeLayer(model.generate, optedIn))); }); +it.effect("moves past three bad leaf stretches at the front and skips them", () => { + const bad = new Set([rawText(0), rawText(24), rawText(48)]); + const model = scripted((input) => + bad.has(input.messages[0]!.text) + ? Effect.fail(failingStretch("invalid-output")) + : Effect.succeed({ + statements: [{ text: "A later stretch.", citations: [input.messages[0]!.ref] }], + }), + ); + const badCalls = () => model.calls.filter((call) => bad.has(call.messages[0]?.text ?? "")).length; + return Effect.gen(function* () { + yield* seedThread(7 * 24 + 6); + yield* summarize; + yield* summarize; + assert.isNotEmpty((yield* list).summaries); + + for (let pass = 0; pass < 3; pass++) yield* summarize; + assert.include((yield* list).lastPass?.reason ?? "", "Skipped 3 stretches"); + const settled = badCalls(); + yield* summarize; + assert.equal(badCalls(), settled); + assert.isTrue(model.calls.some(isRollup)); + }).pipe(Effect.provide(makeLayer(model.generate, optedIn))); +}); + +it.effect("moves past roll-ups that all contain one bad summary", () => { + const model = scripted((input) => + isRollup(input) && input.messages.some((message) => message.text === "- Summary 2") + ? Effect.fail(failingStretch("invalid-output")) + : Effect.succeed({ + statements: [{ text: "Summarized.", citations: [input.messages[0]!.ref] }], + }), + ); + const badCalls = () => + model.calls.filter((call) => call.messages.some((message) => message.text === "- Summary 2")) + .length; + return Effect.gen(function* () { + yield* seedThread(6 * 2 + 6 * 24 + 6); + for (let index = 0; index < 6; index++) + yield* persistSummary(index, [index * 2, index * 2 + 1]); + yield* summarize; + assert.equal(badCalls(), 3); + yield* summarize; + const sources = (yield* list).summaries.flatMap((read) => + read.state === "available" ? read.summary.sources : [], + ); + assert.isTrue( + sources.some((source) => source.kind === "message" && source.messageId === messageId(12)), + ); + + for (let pass = 0; pass < 3; pass++) yield* summarize; + assert.equal((yield* list).lastPass?.waitingMessages, 0); + assert.equal(badCalls(), 3); + }).pipe(Effect.provide(makeLayer(model.generate, optedIn))); +}); + it.effect("summarizes the next stretch when the model cites none of the chunk", () => { const model = scripted((input) => Effect.succeed({ From cfca0cf5b77898e93749e9fa8661566f0375b6c1 Mon Sep 17 00:00:00 2001 From: ScriptedAlchemy Date: Mon, 16 Nov 2026 03:51:58 -0800 Subject: [PATCH 16/37] fix(server): summaries that fail together become suspects, so a thread keeps progressing A pass whose three attempts all failed recorded nothing, as protection against a model outage. When three correlated pieces of work failed, such as every roll-up window holding one bad child or three bad leaf stretches at the front, each later pass retried them first and the thread never progressed. Such a pass now marks its failures as suspects without counting them. Later passes try suspects after other work, and the first pass that succeeds elsewhere counts them toward the skip. An outage still counts nothing and costs at most three calls per pass. Co-Authored-By: Claude Opus 5.5 --- .../ConversationSummaries.ts | 39 ++++++++++++------- docs/internals/context-handoffs.md | 12 +++--- 2 files changed, 32 insertions(+), 19 deletions(-) diff --git a/apps/server/src/project/conversationSummaries/ConversationSummaries.ts b/apps/server/src/project/conversationSummaries/ConversationSummaries.ts index 6a9ea1b7bcf31..580a158e4c558 100644 --- a/apps/server/src/project/conversationSummaries/ConversationSummaries.ts +++ b/apps/server/src/project/conversationSummaries/ConversationSummaries.ts @@ -135,6 +135,8 @@ const ChunkFailure = Schema.Struct({ key: Schema.String, failures: Schema.Int, skipped: Schema.optionalKey(Schema.Boolean), + // Failed in a pass where nothing succeeded, so not counted until a later pass succeeds. + suspect: Schema.optionalKey(Schema.Boolean), reason: Schema.String, }); type ChunkFailure = typeof ChunkFailure.Type; @@ -1182,16 +1184,16 @@ const make = Effect.gen(function* () { const live = new Set(keys.values()); for (const key of chunkFailures.keys()) if (!live.has(key)) chunkFailures.delete(key); - const isSkipped = (raw: string) => { + const failureOf = (raw: string) => { const key = keys.get(raw); - return key !== undefined && chunkFailures.get(key)?.skipped === true; + return key === undefined ? undefined : chunkFailures.get(key); }; - const held = (raw: string, blocked: ReadonlySet) => - blocked.has(raw) || isSkipped(raw); + const isSkipped = (raw: string) => failureOf(raw)?.skipped === true; // Roll up only roots that end before the first uncovered gap. Roots on the far side of a // replaced leaf stay put until that leaf exists, or the roll-up would skip the broken path. // A skipped stretch gets no replacement, so it is no gap. - const selectWork = (blocked: ReadonlySet) => { + const selectFrom = (avoid: (raw: string) => boolean) => { + const held = (raw: string) => avoid(raw) || isSkipped(raw); const chunks = planLeafChunks({ settled, covered }); const group = planCondensation( rootsBeforeFirstGap({ @@ -1206,14 +1208,18 @@ const make = Effect.gen(function* () { ), ), }), - (run) => !held(rollupKey(run), blocked), + (run) => !held(rollupKey(run)), ); if (group !== null) return { kind: "condense" as const, group, key: rollupKey(group) }; - const chunk = chunks.find((candidate) => !held(leafChunkKey(candidate), blocked)); + const chunk = chunks.find((candidate) => !held(leafChunkKey(candidate))); return chunk === undefined ? null : { kind: "leaf" as const, chunk, key: leafChunkKey(chunk) }; }; + // Suspects go last, so work that failed together cannot hold the front of every pass. + const selectWork = (blocked: ReadonlySet) => + selectFrom((raw) => blocked.has(raw) || failureOf(raw)?.suspect === true) ?? + selectFrom((raw) => blocked.has(raw)); const blocked = new Set(); const failed: Array<{ readonly raw: string; readonly reason: string }> = []; let attempts = 0; @@ -1236,20 +1242,25 @@ const make = Effect.gen(function* () { generated += 1; } // With nothing else succeeding, the model may be down or unable to answer at all. Blaming - // the chunk would skip the thread's whole history. - if (generated === 0 && failed.length > 0) - return yield* finish("failed", failed[0]!.reason.slice(0, 300), 0, waiting()); - for (const { raw, reason } of failed) { - const key = yield* keyOf(raw); - const failures = (chunkFailures.get(key)?.failures ?? 0) + 1; + // the chunk would skip the thread's whole history, so a failure stays a suspect until a + // later pass succeeds elsewhere. + const charge = (key: string, reason: string, suspect: boolean) => { + const failures = (chunkFailures.get(key)?.failures ?? 0) + (suspect ? 0 : 1); chunkFailures.delete(key); chunkFailures.set(key, { key, failures, ...(failures >= CHUNK_FAILURES_BEFORE_SKIP ? { skipped: true } : {}), + ...(suspect ? { suspect: true } : {}), reason: reason.slice(0, 300), }); - } + }; + if (generated > 0) + for (const failure of chunkFailures.values()) + if (failure.suspect === true) charge(failure.key, failure.reason, false); + for (const { raw, reason } of failed) charge(yield* keyOf(raw), reason, generated === 0); + if (generated === 0 && failed.length > 0) + return yield* finish("failed", failed[0]!.reason.slice(0, 300), 0, waiting()); const skipped = [...chunkFailures.values()].filter((failure) => failure.skipped); const skipReason = skipped.length === 0 diff --git a/docs/internals/context-handoffs.md b/docs/internals/context-handoffs.md index 11d4cee858dac..fcfc96f48341c 100644 --- a/docs/internals/context-handoffs.md +++ b/docs/internals/context-handoffs.md @@ -47,11 +47,13 @@ again. The pass rolls up a run of four current roots when that run ends before t gap, and makes a new leaf only after those runs. A gap keeps the roots on its far side out of that run, so the neighbours of a replaced leaf never roll up without the replacement. Rolling them up early would summarize more than the broken path, which could then not be rebuilt alone. -A stretch is skipped after two passes in which its own summary came back empty or unreadable while -another summary succeeded; a pass where every summary fails blames the model, not the stretch, and -skips nothing. A skipped stretch gets no leaf, so it is not a gap: roll-ups proceed past it. Its -items stay uncovered, and delivery replays them verbatim. Skips are keyed by the summary model, -so choosing another model tries the stretch again. +A stretch is skipped after its summary comes back empty or unreadable twice. A failure counts only +once another summary succeeds, in that pass or a later one. A pass where every summary fails may be +a model outage, so its stretches become suspects: later passes try them after other work, and the +first pass that succeeds elsewhere counts them. An outage skips nothing, and stretches that fail +together cannot hold the front of every pass. A skipped stretch gets no leaf, so it is not a gap: +roll-ups proceed past it. Its items stay uncovered, and delivery replays them verbatim. Skips are +keyed by the summary model, so choosing another model tries the stretch again. A roll-up offer carries no delivered-knowledge evidence, unlike a leaf offer: the evidence of a few hundred items would never fit beside it. Roll-ups are capped by rendered bytes, as delivery measures them, so several fit beside the verbatim tail of a 16 KB handoff. From 3ef34394ddf5f9f51ce7aa0f5be314149757e371 Mon Sep 17 00:00:00 2001 From: ScriptedAlchemy Date: Mon, 16 Nov 2026 03:53:16 -0800 Subject: [PATCH 17/37] test(server): a skipped summary stretch survives a full failure ledger Co-Authored-By: Claude Opus 5.5 --- .../ConversationSummaries.test.ts | 28 +++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/apps/server/src/project/conversationSummaries/ConversationSummaries.test.ts b/apps/server/src/project/conversationSummaries/ConversationSummaries.test.ts index b1e5bf62c6d01..6f8e9f14d7c6c 100644 --- a/apps/server/src/project/conversationSummaries/ConversationSummaries.test.ts +++ b/apps/server/src/project/conversationSummaries/ConversationSummaries.test.ts @@ -819,6 +819,34 @@ it.effect("moves past roll-ups that all contain one bad summary", () => { }).pipe(Effect.provide(makeLayer(model.generate, optedIn))); }); +it.effect("keeps a skipped stretch skipped when an outage fills the failure ledger", () => { + let down = false; + const model = scripted((input) => + down || input.messages[0]?.text === rawText(1) + ? Effect.fail(failingStretch("empty")) + : Effect.succeed({ + statements: [{ text: "Summarized.", citations: [input.messages[0]!.ref] }], + }), + ); + const skippedCalls = () => + model.calls.filter((call) => call.messages[0]?.text === rawText(1)).length; + return Effect.gen(function* () { + // Leaves over the even messages leave each odd message a stretch of its own. + const leaves = 70; + yield* seedThread(leaves * 2 + 6); + for (let index = 0; index < leaves; index++) yield* persistSummary(index, [index * 2]); + yield* summarize; + yield* summarize; + assert.include((yield* list).lastPass?.reason ?? "", "Skipped a stretch"); + + down = true; + for (let pass = 0; pass < 25; pass++) yield* summarize; + down = false; + for (let pass = 0; pass < 10; pass++) yield* summarize; + assert.equal(skippedCalls(), 2); + }).pipe(Effect.provide(makeLayer(model.generate, optedIn))); +}); + it.effect("summarizes the next stretch when the model cites none of the chunk", () => { const model = scripted((input) => Effect.succeed({ From d9f05c41d26cf3ba374c684b162d59f65ef02c74 Mon Sep 17 00:00:00 2001 From: ScriptedAlchemy Date: Mon, 16 Nov 2026 03:54:28 -0800 Subject: [PATCH 18/37] fix(server): trimming the summary failure ledger keeps skipped stretches The ledger keeps its last 64 entries in insertion order. A skipped stretch is never tried again, so it is never re-inserted and drifts to the front, where the cap dropped it first. A long outage that marks many stretches as suspects could then evict a skip and retry known-bad work. Trimming now drops other failures before skips. Co-Authored-By: Claude Opus 5.5 --- .../project/conversationSummaries/ConversationSummaries.ts | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/apps/server/src/project/conversationSummaries/ConversationSummaries.ts b/apps/server/src/project/conversationSummaries/ConversationSummaries.ts index 580a158e4c558..2c79f9805b460 100644 --- a/apps/server/src/project/conversationSummaries/ConversationSummaries.ts +++ b/apps/server/src/project/conversationSummaries/ConversationSummaries.ts @@ -85,7 +85,8 @@ const MAX_SUMMARIES_PER_PASS = 3; // One empty or invalid reply can be a cold start. The second is the chunk, and retrying it // again only rehashes the thread. const CHUNK_FAILURES_BEFORE_SKIP = 2; -// Live keys only survive a pass, so this bounds a thread with many failing stretches. +// Live keys only survive a pass, so this bounds a thread with many failing stretches. Trimming +// drops other failures before skips, which are never re-recorded and would otherwise age out. const MAX_CHUNK_FAILURES = 64; // Measured as delivery measures it, so a few roll-ups fit beside the verbatim tail of a 16 KB // handoff in any script. The prompt asks for fewer characters, so this cut is a backstop. @@ -898,7 +899,9 @@ const make = Effect.gen(function* () { cleanupSuperseded(superseded()).pipe( Effect.andThen(DateTime.now), Effect.flatMap((now) => { - const stored = [...chunkFailures.values()].slice(-MAX_CHUNK_FAILURES); + const stored = [...chunkFailures.values()] + .toSorted((a, b) => Number(a.skipped === true) - Number(b.skipped === true)) + .slice(-MAX_CHUNK_FAILURES); return recordPass(projectId, threadId, { runId, result, From 184c45f03c4cddeb28b0516c41cc5a50bbdf57a4 Mon Sep 17 00:00:00 2001 From: ScriptedAlchemy Date: Mon, 16 Nov 2026 03:55:44 -0800 Subject: [PATCH 19/37] test(server): a Claude error result is not labelled an unreadable reply Co-Authored-By: Claude Opus 5.5 --- .../ClaudeTextGeneration.test.ts | 38 +++++++++++++++++++ 1 file changed, 38 insertions(+) diff --git a/apps/server/src/textGeneration/ClaudeTextGeneration.test.ts b/apps/server/src/textGeneration/ClaudeTextGeneration.test.ts index 866fa072f834a..a5a05f2bb83bf 100644 --- a/apps/server/src/textGeneration/ClaudeTextGeneration.test.ts +++ b/apps/server/src/textGeneration/ClaudeTextGeneration.test.ts @@ -493,6 +493,44 @@ it.layer(layerClaudeTextGenerationTest)("ClaudeTextGeneration", (it) => { ), ); + it.effect.each([ + [ + "an unreadable success payload", + { type: "result", subtype: "success", structured_output: { title: 42 } }, + "invalid-output", + ], + ["running out of structured output retries", structuredOutputFailure, "invalid-output"], + [ + "an execution error", + { type: "result", subtype: "error_during_execution", is_error: true, errors: [apiError] }, + undefined, + ], + [ + "an API error result", + { type: "result", subtype: "success", is_error: true, result: apiError }, + undefined, + ], + ] as const)("labels %s by whether the model answered", ([, result, kind]) => + withFakeClaudeEnv( + { output: JSON.stringify([{ type: "system", subtype: "init" }, result]) }, + (textGeneration) => + Effect.gen(function* () { + const error = yield* Effect.flip( + textGeneration.generateThreadTitle({ + cwd: process.cwd(), + message: "Name this thread", + modelSelection: { + instanceId: ProviderInstanceId.make("claudeAgent"), + model: SYNTHETIC_CLAUDE_STANDARD_MODEL, + }, + }), + ); + + expect(error.kind).toBe(kind); + }), + ), + ); + it.effect("does not report the raw result JSON when a failed run writes nothing to stderr", () => withFakeClaudeEnv( { output: JSON.stringify(structuredOutputFailure), exitCode: 1 }, From 41016cf85e96f92770def49b43d42fb7d5f3c458 Mon Sep 17 00:00:00 2001 From: ScriptedAlchemy Date: Mon, 16 Nov 2026 03:57:11 -0800 Subject: [PATCH 20/37] fix(server): only a Claude reply the model gave is labelled unreadable An exit-0 run whose final result had no readable structured output was always labelled invalid-output. That included error_during_execution and API error results, so summaries blamed the stretch for a failed run. The label now follows the result: a success result with an unreadable payload, or running out of structured output retries. Co-Authored-By: Claude Opus 5.5 --- .../src/textGeneration/ClaudeTextGeneration.ts | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/apps/server/src/textGeneration/ClaudeTextGeneration.ts b/apps/server/src/textGeneration/ClaudeTextGeneration.ts index 9e1d59a3dba77..72cc37a083001 100644 --- a/apps/server/src/textGeneration/ClaudeTextGeneration.ts +++ b/apps/server/src/textGeneration/ClaudeTextGeneration.ts @@ -58,12 +58,18 @@ const NO_SESSION_PERSISTENCE = "--no-session-persistence"; // Claude Code before 2.0.63 exits with this on stderr; those runs retry without the flag. const NO_SESSION_PERSISTENCE_REJECTED = `error: unknown option '${NO_SESSION_PERSISTENCE}'`; +const ClaudeResultStatus = { + subtype: Schema.optionalKey(Schema.String), + is_error: Schema.optionalKey(Schema.Boolean), +}; const ClaudeOutputEnvelope = Schema.Struct({ structured_output: Schema.Unknown, + ...ClaudeResultStatus, }); const ClaudeOutputMessage = Schema.Struct({ type: Schema.String, structured_output: Schema.optionalKey(Schema.Unknown), + ...ClaudeResultStatus, }); const isClaudeOutputEnvelope = Schema.is(ClaudeOutputEnvelope); @@ -362,6 +368,12 @@ export const makeClaudeTextGeneration = Effect.fn("makeClaudeTextGeneration")(fu const envelope = isClaudeOutputEnvelope(output) ? output : output.findLast((message) => message.type === "result"); + // Only a reply the model gave is unreadable. Other error results stopped the run before one. + const modelAnswered = + envelope?.subtype === "error_max_structured_output_retries" || + (envelope !== undefined && + envelope.is_error !== true && + (envelope.subtype ?? "success") === "success"); const decodeOutput = Schema.decodeEffect( outputSchemaJson, @@ -374,7 +386,7 @@ export const makeClaudeTextGeneration = Effect.fn("makeClaudeTextGeneration")(fu new TextGenerationError({ operation, detail: "Claude returned invalid structured output.", - kind: "invalid-output", + ...(modelAnswered ? { kind: "invalid-output" as const } : {}), cause, }), ), From 551014381723fecef0b9ea40cc5572ada717aee1 Mon Sep 17 00:00:00 2001 From: ScriptedAlchemy Date: Mon, 16 Nov 2026 03:57:40 -0800 Subject: [PATCH 21/37] style(server): keep the retention comment on the retention constant Co-Authored-By: Claude Opus 5.5 --- apps/server/src/orchestration-v2/EffectOutbox.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/apps/server/src/orchestration-v2/EffectOutbox.ts b/apps/server/src/orchestration-v2/EffectOutbox.ts index 7822fdbe56bef..03c6cafb0f232 100644 --- a/apps/server/src/orchestration-v2/EffectOutbox.ts +++ b/apps/server/src/orchestration-v2/EffectOutbox.ts @@ -231,8 +231,8 @@ export const OrchestrationEffectStatusV2 = Schema.Literals([ ]); export type OrchestrationEffectStatusV2 = typeof OrchestrationEffectStatusV2.Type; -/** Receipts deduplicate retries, and restart re-enqueues need far less than a week. Retain failed rows to keep deleted-thread worktrees. */ const SUMMARY_PASS_SUPERSEDED = "Superseded by a pending summary pass for the same thread."; +/** Receipts deduplicate retries, and restart re-enqueues need far less than a week. Retain failed rows to keep deleted-thread worktrees. */ export const SETTLED_EFFECT_RETENTION = Duration.days(7); const PRUNE_BATCH_SIZE = 500; From 5e6bfceedca3cfbbe1e1ab376b1bdc931a97c830 Mon Sep 17 00:00:00 2001 From: ScriptedAlchemy Date: Mon, 16 Nov 2026 04:19:20 -0800 Subject: [PATCH 22/37] test(server): a Claude run that exits 1 out of structured output retries is labelled unreadable Co-Authored-By: Claude Opus 5.5 --- .../src/textGeneration/ClaudeTextGeneration.test.ts | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/apps/server/src/textGeneration/ClaudeTextGeneration.test.ts b/apps/server/src/textGeneration/ClaudeTextGeneration.test.ts index a5a05f2bb83bf..d7e51aae96409 100644 --- a/apps/server/src/textGeneration/ClaudeTextGeneration.test.ts +++ b/apps/server/src/textGeneration/ClaudeTextGeneration.test.ts @@ -493,26 +493,30 @@ it.layer(layerClaudeTextGenerationTest)("ClaudeTextGeneration", (it) => { ), ); + // Error results exit 1, as in the failure fixtures above. it.effect.each([ [ "an unreadable success payload", { type: "result", subtype: "success", structured_output: { title: 42 } }, + 0, "invalid-output", ], - ["running out of structured output retries", structuredOutputFailure, "invalid-output"], + ["running out of structured output retries", structuredOutputFailure, 1, "invalid-output"], [ "an execution error", { type: "result", subtype: "error_during_execution", is_error: true, errors: [apiError] }, + 1, undefined, ], [ "an API error result", { type: "result", subtype: "success", is_error: true, result: apiError }, + 1, undefined, ], - ] as const)("labels %s by whether the model answered", ([, result, kind]) => + ] as const)("labels %s by whether the model answered", ([, result, exitCode, kind]) => withFakeClaudeEnv( - { output: JSON.stringify([{ type: "system", subtype: "init" }, result]) }, + { output: JSON.stringify([{ type: "system", subtype: "init" }, result]), exitCode }, (textGeneration) => Effect.gen(function* () { const error = yield* Effect.flip( From b30622f276402ec63429360dfd62202023cf8314 Mon Sep 17 00:00:00 2001 From: ScriptedAlchemy Date: Mon, 16 Nov 2026 04:20:51 -0800 Subject: [PATCH 23/37] fix(server): a Claude run that exits 1 out of structured output retries is labelled unreadable The CLI exits 1 when the model never produced valid structured output, so the label set on the exit-0 path never reached it. Summaries then failed the whole pass on that chunk instead of counting it. Co-Authored-By: Claude Opus 5.5 --- .../textGeneration/ClaudeTextGeneration.ts | 26 ++++++++++++------- 1 file changed, 17 insertions(+), 9 deletions(-) diff --git a/apps/server/src/textGeneration/ClaudeTextGeneration.ts b/apps/server/src/textGeneration/ClaudeTextGeneration.ts index 72cc37a083001..6ce08be7929dd 100644 --- a/apps/server/src/textGeneration/ClaudeTextGeneration.ts +++ b/apps/server/src/textGeneration/ClaudeTextGeneration.ts @@ -82,6 +82,7 @@ const decodeClaudeOutput = Schema.decodeEffect( // error_max_structured_output_retries report through `errors` instead. const ClaudeErrorResult = Schema.Struct({ is_error: Schema.Literal(true), + subtype: Schema.optionalKey(Schema.String), result: Schema.optionalKey(Schema.String), errors: Schema.optionalKey(Schema.Array(Schema.String)), }); @@ -89,11 +90,14 @@ const isClaudeErrorResult = Schema.is(ClaudeErrorResult); const decodeJsonOption = Schema.decodeUnknownOption(Schema.fromJsonString(Schema.Unknown)); // Claude reports JSON errors on stdout; stderr may contain only wrapper notices. -function claudeErrorResult(stdout: string): string | undefined { +function claudeErrorResults(stdout: string) { const output = Option.getOrUndefined(decodeJsonOption(stdout)); const messages: ReadonlyArray = Array.isArray(output) ? output : [output]; - return messages - .filter(isClaudeErrorResult) + return messages.filter(isClaudeErrorResult); +} + +function claudeErrorDetail(results: ReadonlyArray) { + return results .map((message) => ( message.result ?? @@ -327,9 +331,13 @@ export const makeClaudeTextGeneration = Effect.fn("makeClaudeTextGeneration")(fu if (exitCode === 0) return Effect.succeed(stdout); const stderrDetail = stderr.trim(); const stdoutDetail = stdout.trim(); + const results = claudeErrorResults(stdoutDetail); const detail = - claudeErrorResult(stdoutDetail) ?? - (stderrDetail.length > 0 ? stderrDetail : stdoutDetail); + claudeErrorDetail(results) ?? (stderrDetail.length > 0 ? stderrDetail : stdoutDetail); + // The model answered, but never in the requested shape. + const modelAnswered = results.some( + (result) => result.subtype === "error_max_structured_output_retries", + ); return Effect.fail( new TextGenerationError({ operation, @@ -337,6 +345,7 @@ export const makeClaudeTextGeneration = Effect.fn("makeClaudeTextGeneration")(fu detail.length > 0 ? `Claude CLI command failed: ${detail}` : `Claude CLI command failed with code ${exitCode}.`, + ...(modelAnswered ? { kind: "invalid-output" as const } : {}), }), ); }), @@ -370,10 +379,9 @@ export const makeClaudeTextGeneration = Effect.fn("makeClaudeTextGeneration")(fu : output.findLast((message) => message.type === "result"); // Only a reply the model gave is unreadable. Other error results stopped the run before one. const modelAnswered = - envelope?.subtype === "error_max_structured_output_retries" || - (envelope !== undefined && - envelope.is_error !== true && - (envelope.subtype ?? "success") === "success"); + envelope !== undefined && + envelope.is_error !== true && + (envelope.subtype ?? "success") === "success"; const decodeOutput = Schema.decodeEffect( outputSchemaJson, From 7edb72348932ee46d76d4d949527cbc3a0a28618 Mon Sep 17 00:00:00 2001 From: ScriptedAlchemy Date: Mon, 16 Nov 2026 04:22:30 -0800 Subject: [PATCH 24/37] test(server): after an outage, a summary stretch is charged only for its own failures beside a success Co-Authored-By: Claude Opus 5.5 --- .../ConversationSummaries.test.ts | 28 +++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/apps/server/src/project/conversationSummaries/ConversationSummaries.test.ts b/apps/server/src/project/conversationSummaries/ConversationSummaries.test.ts index 6f8e9f14d7c6c..bafe952da8c14 100644 --- a/apps/server/src/project/conversationSummaries/ConversationSummaries.test.ts +++ b/apps/server/src/project/conversationSummaries/ConversationSummaries.test.ts @@ -763,6 +763,34 @@ it.effect("skips nothing while every summary comes back empty", () => { }).pipe(Effect.provide(makeLayer(model.generate, optedIn))); }); +it.effect("counts only a stretch's own failures beside a success after an outage", () => { + let down = true; + let flaky = rawText(0); + const model = scripted((input) => + down || input.messages[0]?.text === flaky + ? Effect.fail(failingStretch("empty")) + : Effect.succeed({ + statements: [{ text: "Summarized.", citations: [input.messages[0]!.ref] }], + }), + ); + return Effect.gen(function* () { + yield* seedThread(5 * 24 + 6); + yield* summarize; + + down = false; + yield* summarize; + assert.notInclude((yield* list).lastPass?.reason ?? "", "Skipped"); + + flaky = rawText(48); + yield* summarize; + assert.notInclude((yield* list).lastPass?.reason ?? "", "Skipped"); + + flaky = ""; + for (let pass = 0; pass < 2; pass++) yield* summarize; + assert.equal((yield* list).lastPass?.waitingMessages, 0); + }).pipe(Effect.provide(makeLayer(model.generate, optedIn))); +}); + it.effect("moves past three bad leaf stretches at the front and skips them", () => { const bad = new Set([rawText(0), rawText(24), rawText(48)]); const model = scripted((input) => From df1b5d27e56f2954cfe30a9e3146b8cb01537dbc Mon Sep 17 00:00:00 2001 From: ScriptedAlchemy Date: Mon, 16 Nov 2026 04:26:21 -0800 Subject: [PATCH 25/37] fix(server): a summary stretch is charged only for its own failure beside a success The first pass to succeed after an outage charged every suspect at once, even those it never retried, and a retried suspect that failed got charged twice. A slightly flaky model then skipped healthy history. Now only a retried stretch that fails in a pass where another summary succeeded is charged, once. Once a pass has a success, suspects are tried in order like other work; until then they still go last. Co-Authored-By: Claude Opus 5.5 --- .../ConversationSummaries.test.ts | 6 ++++-- .../ConversationSummaries.ts | 18 ++++++++---------- 2 files changed, 12 insertions(+), 12 deletions(-) diff --git a/apps/server/src/project/conversationSummaries/ConversationSummaries.test.ts b/apps/server/src/project/conversationSummaries/ConversationSummaries.test.ts index bafe952da8c14..ad5e6161099a2 100644 --- a/apps/server/src/project/conversationSummaries/ConversationSummaries.test.ts +++ b/apps/server/src/project/conversationSummaries/ConversationSummaries.test.ts @@ -802,7 +802,7 @@ it.effect("moves past three bad leaf stretches at the front and skips them", () ); const badCalls = () => model.calls.filter((call) => bad.has(call.messages[0]?.text ?? "")).length; return Effect.gen(function* () { - yield* seedThread(7 * 24 + 6); + yield* seedThread(8 * 24 + 6); yield* summarize; yield* summarize; assert.isNotEmpty((yield* list).summaries); @@ -843,7 +843,9 @@ it.effect("moves past roll-ups that all contain one bad summary", () => { for (let pass = 0; pass < 3; pass++) yield* summarize; assert.equal((yield* list).lastPass?.waitingMessages, 0); - assert.equal(badCalls(), 3); + const settled = badCalls(); + yield* summarize; + assert.equal(badCalls(), settled); }).pipe(Effect.provide(makeLayer(model.generate, optedIn))); }); diff --git a/apps/server/src/project/conversationSummaries/ConversationSummaries.ts b/apps/server/src/project/conversationSummaries/ConversationSummaries.ts index 2c79f9805b460..ef21b30d0d968 100644 --- a/apps/server/src/project/conversationSummaries/ConversationSummaries.ts +++ b/apps/server/src/project/conversationSummaries/ConversationSummaries.ts @@ -136,7 +136,7 @@ const ChunkFailure = Schema.Struct({ key: Schema.String, failures: Schema.Int, skipped: Schema.optionalKey(Schema.Boolean), - // Failed in a pass where nothing succeeded, so not counted until a later pass succeeds. + // Last failed in a pass where nothing succeeded, so that failure was not counted. suspect: Schema.optionalKey(Schema.Boolean), reason: Schema.String, }); @@ -1219,10 +1219,12 @@ const make = Effect.gen(function* () { ? null : { kind: "leaf" as const, chunk, key: leafChunkKey(chunk) }; }; - // Suspects go last, so work that failed together cannot hold the front of every pass. + // Until a summary succeeds, suspects go last, so work that failed together cannot hold the + // front of every pass. const selectWork = (blocked: ReadonlySet) => - selectFrom((raw) => blocked.has(raw) || failureOf(raw)?.suspect === true) ?? - selectFrom((raw) => blocked.has(raw)); + (generated === 0 + ? selectFrom((raw) => blocked.has(raw) || failureOf(raw)?.suspect === true) + : null) ?? selectFrom((raw) => blocked.has(raw)); const blocked = new Set(); const failed: Array<{ readonly raw: string; readonly reason: string }> = []; let attempts = 0; @@ -1244,9 +1246,8 @@ const make = Effect.gen(function* () { rebuild(); generated += 1; } - // With nothing else succeeding, the model may be down or unable to answer at all. Blaming - // the chunk would skip the thread's whole history, so a failure stays a suspect until a - // later pass succeeds elsewhere. + // With nothing succeeding, the model may be down or unable to answer at all. Blaming the + // chunk would skip the thread's whole history, so that failure is not counted. const charge = (key: string, reason: string, suspect: boolean) => { const failures = (chunkFailures.get(key)?.failures ?? 0) + (suspect ? 0 : 1); chunkFailures.delete(key); @@ -1258,9 +1259,6 @@ const make = Effect.gen(function* () { reason: reason.slice(0, 300), }); }; - if (generated > 0) - for (const failure of chunkFailures.values()) - if (failure.suspect === true) charge(failure.key, failure.reason, false); for (const { raw, reason } of failed) charge(yield* keyOf(raw), reason, generated === 0); if (generated === 0 && failed.length > 0) return yield* finish("failed", failed[0]!.reason.slice(0, 300), 0, waiting()); From 93c64497f4f9be0b5c4eb4a240be1cdd7d13cdcd Mon Sep 17 00:00:00 2001 From: ScriptedAlchemy Date: Mon, 16 Nov 2026 04:27:26 -0800 Subject: [PATCH 26/37] test(server): a summary pass with only suspect stretches makes one model call while nothing succeeds Co-Authored-By: Claude Opus 5.5 --- .../conversationSummaries/ConversationSummaries.test.ts | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/apps/server/src/project/conversationSummaries/ConversationSummaries.test.ts b/apps/server/src/project/conversationSummaries/ConversationSummaries.test.ts index ad5e6161099a2..a7d77ad34ccbe 100644 --- a/apps/server/src/project/conversationSummaries/ConversationSummaries.test.ts +++ b/apps/server/src/project/conversationSummaries/ConversationSummaries.test.ts @@ -743,7 +743,14 @@ it.effect("skips nothing while every summary comes back empty", () => { ); return Effect.gen(function* () { yield* seedThread(5 * 24 + 6); - for (let pass = 0; pass < 3; pass++) assert.isFalse((yield* summarize).hasMore); + const callsPerPass: Array = []; + for (let pass = 0; pass < 3; pass++) { + const before = model.calls.length; + assert.isFalse((yield* summarize).hasMore); + callsPerPass.push(model.calls.length - before); + } + // Once every stretch is a suspect, one call per pass tests the model. + assert.deepEqual(callsPerPass, [3, 3, 1]); assert.deepEqual((yield* list).summaries, []); down = false; From b7cebf9188fd750c13b00d04cbd8d841441b42bf Mon Sep 17 00:00:00 2001 From: ScriptedAlchemy Date: Mon, 16 Nov 2026 04:28:40 -0800 Subject: [PATCH 27/37] fix(server): a summary pass tries one suspect stretch while nothing has succeeded A thread with only suspect stretches spent three model calls a pass on a model that may be down. Until a summary succeeds, a pass now tries one suspect. Co-Authored-By: Claude Opus 5.5 --- .../ConversationSummaries.ts | 16 +++++++++++----- 1 file changed, 11 insertions(+), 5 deletions(-) diff --git a/apps/server/src/project/conversationSummaries/ConversationSummaries.ts b/apps/server/src/project/conversationSummaries/ConversationSummaries.ts index ef21b30d0d968..cd27625a6116a 100644 --- a/apps/server/src/project/conversationSummaries/ConversationSummaries.ts +++ b/apps/server/src/project/conversationSummaries/ConversationSummaries.ts @@ -1219,12 +1219,17 @@ const make = Effect.gen(function* () { ? null : { kind: "leaf" as const, chunk, key: leafChunkKey(chunk) }; }; + const isSuspect = (raw: string) => failureOf(raw)?.suspect === true; // Until a summary succeeds, suspects go last, so work that failed together cannot hold the - // front of every pass. - const selectWork = (blocked: ReadonlySet) => - (generated === 0 - ? selectFrom((raw) => blocked.has(raw) || failureOf(raw)?.suspect === true) - : null) ?? selectFrom((raw) => blocked.has(raw)); + // front of every pass, and one suspect is enough to test a model that may be down. + let suspectTried = false; + const selectWork = (blocked: ReadonlySet) => { + if (generated > 0) return selectFrom((raw) => blocked.has(raw)); + return ( + selectFrom((raw) => blocked.has(raw) || isSuspect(raw)) ?? + (suspectTried ? null : selectFrom((raw) => blocked.has(raw))) + ); + }; const blocked = new Set(); const failed: Array<{ readonly raw: string; readonly reason: string }> = []; let attempts = 0; @@ -1232,6 +1237,7 @@ const make = Effect.gen(function* () { const work = selectWork(blocked); if (work === null) break; attempts += 1; + if (isSuspect(work.key)) suspectTried = true; const published = work.kind === "leaf" ? yield* summarizeLeaf(work.chunk) : yield* condense(work.group); if (!published.ok) { From da79eae333f4cfdbe9226b81caf511d9cf53135d Mon Sep 17 00:00:00 2001 From: ScriptedAlchemy Date: Mon, 16 Nov 2026 04:34:54 -0800 Subject: [PATCH 28/37] test(server): a summary stretch that fails twice is skipped even when skipped stretches fill the ledger Co-Authored-By: Claude Opus 5.5 --- .../ConversationSummaries.test.ts | 46 +++++++++++++++++++ 1 file changed, 46 insertions(+) diff --git a/apps/server/src/project/conversationSummaries/ConversationSummaries.test.ts b/apps/server/src/project/conversationSummaries/ConversationSummaries.test.ts index a7d77ad34ccbe..b38dcebe0e4b9 100644 --- a/apps/server/src/project/conversationSummaries/ConversationSummaries.test.ts +++ b/apps/server/src/project/conversationSummaries/ConversationSummaries.test.ts @@ -884,6 +884,52 @@ it.effect("keeps a skipped stretch skipped when an outage fills the failure ledg }).pipe(Effect.provide(makeLayer(model.generate, optedIn))); }); +it.effect("skips a stretch that fails twice when the ledger is full of skipped stretches", () => { + let down = true; + const lateStretch = rawText(66 * 2 + 1); + const model = scripted((input) => + down || input.messages[0]?.text === lateStretch + ? Effect.fail(failingStretch("empty")) + : Effect.succeed({ + statements: [{ text: "Summarized.", citations: [input.messages[0]!.ref] }], + }), + ); + const lateCalls = () => + model.calls.filter((call) => call.messages[0]?.text === lateStretch).length; + return Effect.gen(function* () { + // Leaves over the even messages leave each odd message a stretch of its own. + const stretches = 71; + yield* seedThread(stretches * 2 + 6); + for (let index = 0; index < stretches; index++) yield* persistSummary(index, [index * 2]); + // An outage records the first 66 stretches, three a pass. Marking them skipped stands in + // for the hundreds of passes it takes to skip that many. + for (let pass = 0; pass < 22; pass++) yield* summarize; + const sql = yield* SqlClient.SqlClient; + const [row] = yield* sql<{ readonly payload_json: string }>` + SELECT payload_json FROM conversation_summary_passes WHERE thread_id = ${threadId} + `; + const stored: { chunkFailures: ReadonlyArray<{ readonly key: string }> } = JSON.parse( + row!.payload_json, + ); + assert.lengthOf(stored.chunkFailures, 64); + const skipped = stored.chunkFailures.map(({ key }) => ({ + key, + failures: 2, + skipped: true, + reason: "Router returned no text.", + })); + yield* sql` + UPDATE conversation_summary_passes + SET payload_json = ${JSON.stringify({ ...stored, chunkFailures: skipped })} + WHERE thread_id = ${threadId} + `; + + down = false; + for (let pass = 0; pass < 30; pass++) yield* summarize; + assert.equal(lateCalls(), 2); + }).pipe(Effect.provide(makeLayer(model.generate, optedIn))); +}); + it.effect("summarizes the next stretch when the model cites none of the chunk", () => { const model = scripted((input) => Effect.succeed({ From d5f3a5851def9d926dce1caac537cc782e3927c6 Mon Sep 17 00:00:00 2001 From: ScriptedAlchemy Date: Mon, 16 Nov 2026 04:36:54 -0800 Subject: [PATCH 29/37] fix(server): skipped summary stretches leave room in the failure ledger for new failures Trimming kept every skip first, so with 64 or more skips a new failure was dropped before it was saved. It never reached a skip and blocked roll-ups for good. Trimming now keeps at most the 48 newest skips. Co-Authored-By: Claude Opus 5.5 --- .../conversationSummaries/ConversationSummaries.ts | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/apps/server/src/project/conversationSummaries/ConversationSummaries.ts b/apps/server/src/project/conversationSummaries/ConversationSummaries.ts index cd27625a6116a..663c5483a5946 100644 --- a/apps/server/src/project/conversationSummaries/ConversationSummaries.ts +++ b/apps/server/src/project/conversationSummaries/ConversationSummaries.ts @@ -85,9 +85,11 @@ const MAX_SUMMARIES_PER_PASS = 3; // One empty or invalid reply can be a cold start. The second is the chunk, and retrying it // again only rehashes the thread. const CHUNK_FAILURES_BEFORE_SKIP = 2; -// Live keys only survive a pass, so this bounds a thread with many failing stretches. Trimming -// drops other failures before skips, which are never re-recorded and would otherwise age out. +// Live keys only survive a pass, so this bounds a thread with many failing stretches. const MAX_CHUNK_FAILURES = 64; +// Trimming keeps skips, which are never re-recorded, over other failures, but only this many, so +// failures still being counted always keep room to reach a skip. +const MAX_SKIPPED_CHUNKS = 48; // Measured as delivery measures it, so a few roll-ups fit beside the verbatim tail of a 16 KB // handoff in any script. The prompt asks for fewer characters, so this cut is a backstop. const CONDENSED_MAX_BYTES = 1_536; @@ -899,9 +901,11 @@ const make = Effect.gen(function* () { cleanupSuperseded(superseded()).pipe( Effect.andThen(DateTime.now), Effect.flatMap((now) => { - const stored = [...chunkFailures.values()] - .toSorted((a, b) => Number(a.skipped === true) - Number(b.skipped === true)) - .slice(-MAX_CHUNK_FAILURES); + const failures = [...chunkFailures.values()]; + const stored = [ + ...failures.filter((failure) => failure.skipped !== true), + ...failures.filter((failure) => failure.skipped === true).slice(-MAX_SKIPPED_CHUNKS), + ].slice(-MAX_CHUNK_FAILURES); return recordPass(projectId, threadId, { runId, result, From a451a1d64ff304200e3d067a403770203e22eddc Mon Sep 17 00:00:00 2001 From: ScriptedAlchemy Date: Mon, 16 Nov 2026 04:37:58 -0800 Subject: [PATCH 30/37] docs: state when a summary failure counts and how an outage interacts with later failures Co-Authored-By: Claude Opus 5.5 --- docs/internals/context-handoffs.md | 20 +++++++++++++------- 1 file changed, 13 insertions(+), 7 deletions(-) diff --git a/docs/internals/context-handoffs.md b/docs/internals/context-handoffs.md index fcfc96f48341c..1df2eccfab92f 100644 --- a/docs/internals/context-handoffs.md +++ b/docs/internals/context-handoffs.md @@ -47,13 +47,19 @@ again. The pass rolls up a run of four current roots when that run ends before t gap, and makes a new leaf only after those runs. A gap keeps the roots on its far side out of that run, so the neighbours of a replaced leaf never roll up without the replacement. Rolling them up early would summarize more than the broken path, which could then not be rebuilt alone. -A stretch is skipped after its summary comes back empty or unreadable twice. A failure counts only -once another summary succeeds, in that pass or a later one. A pass where every summary fails may be -a model outage, so its stretches become suspects: later passes try them after other work, and the -first pass that succeeds elsewhere counts them. An outage skips nothing, and stretches that fail -together cannot hold the front of every pass. A skipped stretch gets no leaf, so it is not a gap: -roll-ups proceed past it. Its items stay uncovered, and delivery replays them verbatim. Skips are -keyed by the summary model, so choosing another model tries the stretch again. +A stretch is skipped after its summary comes back empty or unreadable twice, and a failure counts +only when another summary succeeds in the same pass. A pass where nothing succeeds may be a model +outage, so none of its failures count, and the stretches it tried become suspects. Until a pass has +a success, suspects go after other work and only one is tried, so stretches that fail together +cannot hold the front of every pass, and an outage that has made every stretch a suspect costs one +call a pass. After a success, suspects are tried like other work. A suspect counts only a failure +of its own beside a success, so a suspect the pass never reaches counts nothing. An outage neither +adds to a stretch's count nor clears it: a stretch that failed once before the outage is skipped by +its next failure beside a success. A skipped stretch gets no leaf, so it is not a gap: roll-ups +proceed past it. Its items stay uncovered, and delivery replays them verbatim. Skips are keyed by +the summary model, so choosing another model tries the stretch again. The per-thread failure record +is bounded and keeps fewer skips than entries, so a failure still being counted always has room. +When skips overflow, the oldest fall out and those stretches are tried again. A roll-up offer carries no delivered-knowledge evidence, unlike a leaf offer: the evidence of a few hundred items would never fit beside it. Roll-ups are capped by rendered bytes, as delivery measures them, so several fit beside the verbatim tail of a 16 KB handoff. From 66d133e3147a66a29740f11099f8cf7805f71592 Mon Sep 17 00:00:00 2001 From: ScriptedAlchemy Date: Mon, 16 Nov 2026 08:12:24 -0800 Subject: [PATCH 31/37] test(server): summary failures that should be worked around, retried on re-enable, or reported - A chunk that always times out must not hold every pass, and a bad oldest suspect must not hold every pass after an outage. - Skipped sources no longer wait, and re-enabling summaries retries them. - A stretch that failed once keeps its count when an outage overflows the ledger. - An output-limit reply carries a kind, and process-loss reconcile reports the summary passes it cancels. Co-Authored-By: Claude Opus 5.5 --- .../src/orchestration-v2/EffectWorker.test.ts | 2 +- .../ConversationSummaries.test.ts | 216 ++++++++++++------ .../src/textGeneration/TextGenerators.test.ts | 3 + 3 files changed, 146 insertions(+), 75 deletions(-) diff --git a/apps/server/src/orchestration-v2/EffectWorker.test.ts b/apps/server/src/orchestration-v2/EffectWorker.test.ts index 8f4f0da534c82..6cff65045ea90 100644 --- a/apps/server/src/orchestration-v2/EffectWorker.test.ts +++ b/apps/server/src/orchestration-v2/EffectWorker.test.ts @@ -279,7 +279,7 @@ it.effect("keeps at most one pending summary pass per thread", () => pass: 2, }); yield* outbox.enqueue([successor]); - assert.deepEqual(yield* outbox.reconcileAfterProcessLoss, { requeued: 0, cancelled: 0 }); + assert.deepEqual(yield* outbox.reconcileAfterProcessLoss, { requeued: 0, cancelled: 1 }); assert.equal( Option.map(yield* outbox.get(continuation.id), (row) => row.status).pipe(Option.getOrNull), "cancelled", diff --git a/apps/server/src/project/conversationSummaries/ConversationSummaries.test.ts b/apps/server/src/project/conversationSummaries/ConversationSummaries.test.ts index b38dcebe0e4b9..32f30c5c5a239 100644 --- a/apps/server/src/project/conversationSummaries/ConversationSummaries.test.ts +++ b/apps/server/src/project/conversationSummaries/ConversationSummaries.test.ts @@ -42,10 +42,13 @@ import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator"; import { historyCost } from "@t3tools/provider-core/server/handoffBudget"; import * as Digest from "effect/crypto/Digest"; import * as DateTime from "effect/DateTime"; +import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; import * as Hex from "effect/encoding/Hex"; import * as Layer from "effect/Layer"; +import * as Queue from "effect/Queue"; import * as Schema from "effect/Schema"; +import * as Stream from "effect/Stream"; import { McpSchema, McpServer } from "effect/ai"; import * as SqlClient from "effect/sql/SqlClient"; @@ -192,6 +195,43 @@ const verbose = () => const isRollup = (call: Parameters[0]) => call.messages.some((message) => message.role === "summary"); +// An update returns once the service has pulled the next change, so its reaction has finished. +const settingsLayer = (overrides: Parameters[0]) => + Layer.effect( + ServerSettings.ServerSettingsService, + Effect.gen(function* () { + const base = yield* ServerSettings.ServerSettingsService; + const changes = yield* Queue.unbounded<{ + readonly settings: ServerSettingsSchema; + readonly handled: Deferred.Deferred; + }>(); + let handling: Deferred.Deferred | undefined; + const stream = Stream.fromEffectRepeat( + Effect.gen(function* () { + if (handling !== undefined) yield* Deferred.succeed(handling, undefined); + const next = yield* Queue.take(changes); + handling = next.handled; + return next.settings; + }), + ); + return { + ...base, + updateSettings: (patch) => + base.updateSettings(patch).pipe( + Effect.tap((settings) => + Effect.gen(function* () { + const handled = yield* Deferred.make(); + yield* Queue.offer(changes, { settings, handled }); + yield* Deferred.await(handled); + }), + ), + ), + streamChanges: stream, + subscribeChanges: Effect.succeed(stream), + } satisfies ServerSettings.ServerSettingsService["Service"]; + }), + ).pipe(Layer.provide(ServerSettings.layerTest(overrides))); + const makeLayer = (generate: Generate, settings: Parameters[0]) => Layer.merge(ConversationSummaries.layer, ContextHandoffService.layer).pipe( Layer.provide( @@ -211,7 +251,7 @@ const makeLayer = (generate: Generate, settings: Parameters { - let down = true; - const model = scripted((input) => - down - ? Effect.fail(failingStretch("empty")) - : Effect.succeed({ - statements: [{ text: "Recovered.", citations: [input.messages[0]!.ref] }], - }), - ); - return Effect.gen(function* () { - yield* seedThread(5 * 24 + 6); - const callsPerPass: Array = []; - for (let pass = 0; pass < 3; pass++) { - const before = model.calls.length; - assert.isFalse((yield* summarize).hasMore); - callsPerPass.push(model.calls.length - before); - } - // Once every stretch is a suspect, one call per pass tests the model. - assert.deepEqual(callsPerPass, [3, 3, 1]); - assert.deepEqual((yield* list).summaries, []); - - down = false; - const before = model.calls.length; - yield* summarize; - assert.equal(model.calls[before]?.messages[0]?.text, rawText(0)); - assert.include( - (yield* list).summaries.flatMap((read) => - read.state === "available" - ? read.summary.sources.flatMap((source) => - source.kind === "message" ? [source.messageId] : [], - ) - : [], - ), - messageId(0), +it.effect.each([ + { recovered: messageId(0), stuck: undefined }, + { recovered: messageId(24), stuck: rawText(0) }, +])( + "skips nothing while every summary comes back empty, then summarizes $recovered", + ({ recovered, stuck }) => { + let down = true; + const model = scripted((input) => + down || input.messages[0]?.text === stuck + ? Effect.fail(failingStretch("empty")) + : Effect.succeed({ + statements: [{ text: "Recovered.", citations: [input.messages[0]!.ref] }], + }), ); - }).pipe(Effect.provide(makeLayer(model.generate, optedIn))); -}); + return Effect.gen(function* () { + yield* seedThread(5 * 24 + 6); + const callsPerPass: Array = []; + for (let pass = 0; pass < 3; pass++) { + const before = model.calls.length; + assert.isFalse((yield* summarize).hasMore); + callsPerPass.push(model.calls.length - before); + } + // Once every stretch is a suspect, one call per pass tests the model. + assert.deepEqual(callsPerPass, [3, 3, 1]); + assert.deepEqual((yield* list).summaries, []); + + down = false; + yield* summarize; + assert.include( + (yield* list).summaries.flatMap((read) => + read.state === "available" + ? read.summary.sources.flatMap((source) => + source.kind === "message" ? [source.messageId] : [], + ) + : [], + ), + recovered, + ); + }).pipe(Effect.provide(makeLayer(model.generate, optedIn))); + }, +); it.effect("counts only a stretch's own failures beside a success after an outage", () => { let down = true; @@ -856,33 +901,36 @@ it.effect("moves past roll-ups that all contain one bad summary", () => { }).pipe(Effect.provide(makeLayer(model.generate, optedIn))); }); -it.effect("keeps a skipped stretch skipped when an outage fills the failure ledger", () => { - let down = false; - const model = scripted((input) => - down || input.messages[0]?.text === rawText(1) - ? Effect.fail(failingStretch("empty")) - : Effect.succeed({ - statements: [{ text: "Summarized.", citations: [input.messages[0]!.ref] }], - }), - ); - const skippedCalls = () => - model.calls.filter((call) => call.messages[0]?.text === rawText(1)).length; - return Effect.gen(function* () { - // Leaves over the even messages leave each odd message a stretch of its own. - const leaves = 70; - yield* seedThread(leaves * 2 + 6); - for (let index = 0; index < leaves; index++) yield* persistSummary(index, [index * 2]); - yield* summarize; - yield* summarize; - assert.include((yield* list).lastPass?.reason ?? "", "Skipped a stretch"); - - down = true; - for (let pass = 0; pass < 25; pass++) yield* summarize; - down = false; - for (let pass = 0; pass < 10; pass++) yield* summarize; - assert.equal(skippedCalls(), 2); - }).pipe(Effect.provide(makeLayer(model.generate, optedIn))); -}); +it.effect.each([ + { counted: "skipped", stretches: 70, passesBefore: 2, calls: 2 }, + { counted: "failed once", stretches: 80, passesBefore: 1, calls: 3 }, +])( + "keeps a stretch $counted when an outage fills the failure ledger", + ({ stretches, passesBefore, calls }) => { + let down = false; + const model = scripted((input) => + down || input.messages[0]?.text === rawText(1) + ? Effect.fail(failingStretch("empty")) + : Effect.succeed({ + statements: [{ text: "Summarized.", citations: [input.messages[0]!.ref] }], + }), + ); + const skippedCalls = () => + model.calls.filter((call) => call.messages[0]?.text === rawText(1)).length; + return Effect.gen(function* () { + // Leaves over the even messages leave each odd message a stretch of its own. + yield* seedThread(stretches * 2 + 6); + for (let index = 0; index < stretches; index++) yield* persistSummary(index, [index * 2]); + for (let pass = 0; pass < passesBefore; pass++) yield* summarize; + + down = true; + for (let pass = 0; pass < 25; pass++) yield* summarize; + down = false; + for (let pass = 0; pass < 10; pass++) yield* summarize; + assert.equal(skippedCalls(), calls); + }).pipe(Effect.provide(makeLayer(model.generate, optedIn))); + }, +); it.effect("skips a stretch that fails twice when the ledger is full of skipped stretches", () => { let down = true; @@ -958,20 +1006,40 @@ it.effect("summarizes the next stretch when the model cites none of the chunk", }).pipe(Effect.provide(makeLayer(model.generate, optedIn))); }); -it.effect("retries a timed-out summary chunk instead of skipping to the next stretch", () => { - const model = scripted(() => - Effect.fail( - new TextGenerationError({ - operation: "generateConversationSummary", - detail: "OpenCode did not finish generating in time.", - }), - ), +it.effect("works around a chunk that always times out, without skipping it", () => { + const model = scripted((input) => + input.messages[0]?.text === rawText(0) + ? Effect.fail( + new TextGenerationError({ + operation: "generateConversationSummary", + detail: "OpenCode did not finish generating in time.", + }), + ) + : Effect.succeed({ + statements: [{ text: "The later stretch.", citations: [input.messages[0]!.ref] }], + }), ); + const firstChunkCalls = () => + model.calls.filter((call) => call.messages[0]?.text === rawText(0)).length; return Effect.gen(function* () { yield* seedThread(38); assert.instanceOf(yield* summarize.pipe(Effect.flip), ConversationSummaryPassError); assert.equal(model.calls.length, 1); assert.deepEqual((yield* list).summaries, []); + + for (let pass = 0; pass < 3; pass++) + assert.instanceOf(yield* summarize.pipe(Effect.flip), ConversationSummaryPassError); + assert.equal(firstChunkCalls(), 4); + assert.include( + (yield* list).summaries.flatMap((read) => + read.state === "available" + ? read.summary.sources.flatMap((source) => + source.kind === "message" ? [source.messageId] : [], + ) + : [], + ), + messageId(24), + ); }).pipe(Effect.provide(makeLayer(model.generate, optedIn))); }); diff --git a/apps/server/src/textGeneration/TextGenerators.test.ts b/apps/server/src/textGeneration/TextGenerators.test.ts index 91df3ec53e38a..a49440a243e99 100644 --- a/apps/server/src/textGeneration/TextGenerators.test.ts +++ b/apps/server/src/textGeneration/TextGenerators.test.ts @@ -49,6 +49,7 @@ it.effect.each([ auth: ["authorization", "Bearer secret"], reply: { choices: [{ finish_reason: "stop", message: { content: '{"title":"Fix login"}' } }] }, empty: { choices: [{ finish_reason: "stop", message: { content: " " } }] }, + cutOff: { choices: [{ finish_reason: "length", message: { content: '{"title":' } }] }, }, { kind: "anthropic", @@ -56,6 +57,7 @@ it.effect.each([ auth: ["x-api-key", "secret"], reply: { stop_reason: "end_turn", content: [{ type: "text", text: '{"title":"Fix login"}' }] }, empty: { stop_reason: "end_turn", content: [] }, + cutOff: { stop_reason: "max_tokens", content: [{ type: "text", text: '{"title":' }] }, }, ] as const)("$kind generates structured text with its API's request shape", (api) => Effect.gen(function* () { @@ -96,6 +98,7 @@ it.effect.each([ }; expect(yield* kindOf(api.empty)).toBe("empty"); expect(yield* kindOf({ unexpected: true })).toBe("invalid-output"); + expect(yield* kindOf(api.cutOff)).toBe("output-limit"); }), ); From bd4d473acb169e003a26ad5005fb0909bcdebb24 Mon Sep 17 00:00:00 2001 From: ScriptedAlchemy Date: Mon, 16 Nov 2026 08:13:05 -0800 Subject: [PATCH 32/37] fix(server): summary failures have a way around, a way out, and a visible label - An unlabelled failure such as a timeout or an HTTP 400 still fails the pass, but its chunk becomes an uncounted suspect, so the next pass works around it. Earlier failures in that pass are recorded instead of dropped. - Output-limit replies are labelled, so they count toward a skip. - While nothing has succeeded, the suspect that waited longest is the one tried, so a stretch that keeps failing cannot stall a thread after an outage. - Skipped sources leave the waiting count. A pass that wrote summaries shows its skip reason. Turning summaries back on for a project clears its failure ledger. - Ledger trimming drops zero-count suspects before counted failures. - Process-loss reconcile reports the summary passes it cancels. Roll-up keys use CONDENSE_FAN_IN. Co-Authored-By: Claude Opus 5.5 --- .../src/orchestration-v2/EffectOutbox.ts | 5 +- .../ConversationSummaries.ts | 128 ++++++++++++++---- .../conversationSummaryTree.ts | 2 +- .../textGeneration/textGeneratorDrivers.ts | 10 +- .../src/conversationSummaries/index.ts | 2 +- packages/contracts/src/git.ts | 10 +- 6 files changed, 119 insertions(+), 38 deletions(-) diff --git a/apps/server/src/orchestration-v2/EffectOutbox.ts b/apps/server/src/orchestration-v2/EffectOutbox.ts index 03c6cafb0f232..7c5ff1e9280c2 100644 --- a/apps/server/src/orchestration-v2/EffectOutbox.ts +++ b/apps/server/src/orchestration-v2/EffectOutbox.ts @@ -668,7 +668,10 @@ export const layer: Layer.Layer = La `; if (requeuedRows.length > 0 || coveredRows.length > 0) yield* notifyAvailable(requeuedRows.length + coveredRows.length); - return { requeued: requeuedRows.length, cancelled: cancelledRows.length }; + return { + requeued: requeuedRows.length, + cancelled: cancelledRows.length + coveredRows.length, + }; }).pipe( Effect.mapError( (cause) => new EffectOutboxError({ operation: "reconcile-process-loss", cause }), diff --git a/apps/server/src/project/conversationSummaries/ConversationSummaries.ts b/apps/server/src/project/conversationSummaries/ConversationSummaries.ts index 663c5483a5946..b79fc0cbb13c9 100644 --- a/apps/server/src/project/conversationSummaries/ConversationSummaries.ts +++ b/apps/server/src/project/conversationSummaries/ConversationSummaries.ts @@ -23,6 +23,7 @@ import { type OrchestrationV2UserMessageInputIntent, type ProjectId, type RunId, + type ServerSettings as ServerSettingsValue, type ThreadId, type TurnItemId, } from "@t3tools/contracts"; @@ -42,9 +43,11 @@ import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; import * as Schema from "effect/Schema"; import * as SqlClient from "effect/sql/SqlClient"; +import * as Stream from "effect/Stream"; import * as ProjectStore from "../../orchestration-v2/ProjectStore.ts"; import * as ProjectionStore from "../../orchestration-v2/ProjectionStore.ts"; +import { forkParked } from "../../serverActivation.ts"; import * as ServerSettings from "../../serverSettings.ts"; import * as TextGeneration from "../../textGeneration/TextGeneration.ts"; import * as ProjectKnowledge from "../knowledge/ProjectKnowledge.ts"; @@ -66,6 +69,7 @@ import { import { buildSummaryTree, childIds, + CONDENSE_FAN_IN, condensedPosition, handoffCover, isRangeRef, @@ -835,6 +839,40 @@ const make = Effect.gen(function* () { `; }); + // Turning summaries back on is how a user retries skipped stretches. + const forgetFailuresOnReenable = Effect.fn("ConversationSummaries.forgetFailuresOnReenable")( + function* (before: ServerSettingsValue, after: ServerSettingsValue) { + const enabled = (settings: ServerSettingsValue, projectId: ProjectId) => + resolveProjectSettings(settings, projectId).settings.enableConversationSummaries; + const rows = yield* sql<{ readonly project_id: ProjectId }>` + SELECT DISTINCT project_id FROM conversation_summary_passes + WHERE json_extract(payload_json, '$.chunkFailures') IS NOT NULL + `; + const reenabled = rows + .map((row) => row.project_id) + .filter((projectId) => !enabled(before, projectId) && enabled(after, projectId)); + if (reenabled.length === 0) return; + yield* sql` + UPDATE conversation_summary_passes + SET payload_json = json_remove(payload_json, '$.chunkFailures') + WHERE ${sql.in("project_id", reenabled)} + `; + }, + ); + const settingsChanges = yield* serverSettings.subscribeChanges; + let lastSettings = yield* serverSettings.getSettings.pipe(Effect.orDie); + yield* forkParked( + Stream.runForEach(settingsChanges, (settings) => { + const before = lastSettings; + lastSettings = settings; + return forgetFailuresOnReenable(before, settings).pipe( + Effect.catchCause((cause) => + Effect.logWarning("Could not reset summary failures for re-enabled projects.", cause), + ), + ); + }), + ); + const summarizeThread: ConversationSummaries["Service"]["summarizeThread"] = Effect.fn( "ConversationSummaries.summarizeThread", )( @@ -902,8 +940,10 @@ const make = Effect.gen(function* () { Effect.andThen(DateTime.now), Effect.flatMap((now) => { const failures = [...chunkFailures.values()]; + const open = failures.filter((failure) => failure.skipped !== true); const stored = [ - ...failures.filter((failure) => failure.skipped !== true), + ...open.filter((failure) => failure.failures === 0), + ...open.filter((failure) => failure.failures > 0), ...failures.filter((failure) => failure.skipped === true).slice(-MAX_SKIPPED_CHUNKS), ].slice(-MAX_CHUNK_FAILURES); return recordPass(projectId, threadId, { @@ -1018,17 +1058,7 @@ const make = Effect.gen(function* () { for (const source of root.leafSources) covered.add(conversationSummarySourceKey(source)); }; rebuild(); - const waiting = () => - new Set( - settled - .filter((source) => !covered.has(conversationSummarySourceKey(source.ref))) - .map((source) => conversationSummarySourceIdentity(source.ref)), - ).size; let generated = 0; - const failPass = (reason: string) => - finish("failed", reason.slice(0, 300), generated, waiting()).pipe( - Effect.andThen(Effect.fail(new ConversationSummaryPassError({ runId, cause: reason }))), - ); const publish = Effect.fnUntraced(function* (input: { readonly messages: ReadonlyArray<{ @@ -1186,8 +1216,8 @@ const make = Effect.gen(function* () { const rollupKey = (group: ReadonlyArray) => group.map((node) => node.row.id).join("\n"); for (const chunk of planLeafChunks({ settled, covered })) yield* keyOf(leafChunkKey(chunk)); - for (let start = 0; start + 4 <= tree.roots.length; start++) - yield* keyOf(rollupKey(tree.roots.slice(start, start + 4))); + for (let start = 0; start + CONDENSE_FAN_IN <= tree.roots.length; start++) + yield* keyOf(rollupKey(tree.roots.slice(start, start + CONDENSE_FAN_IN))); const live = new Set(keys.values()); for (const key of chunkFailures.keys()) if (!live.has(key)) chunkFailures.delete(key); @@ -1196,6 +1226,23 @@ const make = Effect.gen(function* () { return key === undefined ? undefined : chunkFailures.get(key); }; const isSkipped = (raw: string) => failureOf(raw)?.skipped === true; + const skippedSources = (chunks: ReadonlyArray>) => + new Set( + chunks + .filter((chunk) => isSkipped(leafChunkKey(chunk))) + .flatMap((chunk) => chunk.map((source) => conversationSummarySourceKey(source.ref))), + ); + const waiting = () => { + const skipped = skippedSources(planLeafChunks({ settled, covered })); + return new Set( + settled + .filter((source) => { + const key = conversationSummarySourceKey(source.ref); + return !covered.has(key) && !skipped.has(key); + }) + .map((source) => conversationSummarySourceIdentity(source.ref)), + ).size; + }; // Roll up only roots that end before the first uncovered gap. Roots on the far side of a // replaced leaf stay put until that leaf exists, or the roll-up would skip the broken path. // A skipped stretch gets no replacement, so it is no gap. @@ -1207,13 +1254,7 @@ const make = Effect.gen(function* () { roots: tree.roots, order: settled.map((source) => conversationSummarySourceKey(source.ref)), covered, - skipped: new Set( - chunks - .filter((chunk) => isSkipped(leafChunkKey(chunk))) - .flatMap((chunk) => - chunk.map((source) => conversationSummarySourceKey(source.ref)), - ), - ), + skipped: skippedSources(chunks), }), (run) => !held(rollupKey(run)), ); @@ -1225,17 +1266,29 @@ const make = Effect.gen(function* () { }; const isSuspect = (raw: string) => failureOf(raw)?.suspect === true; // Until a summary succeeds, suspects go last, so work that failed together cannot hold the - // front of every pass, and one suspect is enough to test a model that may be down. + // front of every pass, and one suspect is enough to test a model that may be down. That one + // is the suspect that waited longest, so a stretch that keeps failing cannot hold every pass. let suspectTried = false; const selectWork = (blocked: ReadonlySet) => { if (generated > 0) return selectFrom((raw) => blocked.has(raw)); - return ( - selectFrom((raw) => blocked.has(raw) || isSuspect(raw)) ?? - (suspectTried ? null : selectFrom((raw) => blocked.has(raw))) - ); + const fresh = selectFrom((raw) => blocked.has(raw) || isSuspect(raw)); + if (fresh !== null || suspectTried) return fresh; + for (const failure of chunkFailures.values()) { + if (failure.suspect !== true) continue; + const work = selectFrom( + (raw) => blocked.has(raw) || (isSuspect(raw) && keys.get(raw) !== failure.key), + ); + if (work !== null) return work; + } + return null; }; const blocked = new Set(); - const failed: Array<{ readonly raw: string; readonly reason: string }> = []; + const failed: Array<{ + readonly raw: string; + readonly reason: string; + readonly countable: boolean; + }> = []; + let stoppedBy: string | undefined; let attempts = 0; while (generated < MAX_SUMMARIES_PER_PASS && attempts < MAX_SUMMARIES_PER_PASS) { const work = selectWork(blocked); @@ -1245,9 +1298,17 @@ const make = Effect.gen(function* () { const published = work.kind === "leaf" ? yield* summarizeLeaf(work.chunk) : yield* condense(work.group); if (!published.ok) { - if (!published.unusableReply) return yield* failPass(published.reason); - failed.push({ raw: work.key, reason: published.reason }); + failed.push({ + raw: work.key, + reason: published.reason, + countable: published.unusableReply, + }); blocked.add(work.key); + // An outage or a rejected request fails the pass so it retries, but its work goes last. + if (!published.unusableReply) { + stoppedBy = published.reason; + break; + } continue; } const key = keys.get(work.key); @@ -1269,14 +1330,21 @@ const make = Effect.gen(function* () { reason: reason.slice(0, 300), }); }; - for (const { raw, reason } of failed) charge(yield* keyOf(raw), reason, generated === 0); + for (const { raw, reason, countable } of failed) + charge(yield* keyOf(raw), reason, !countable || generated === 0); + if (stoppedBy !== undefined) + return yield* finish("failed", stoppedBy.slice(0, 300), generated, waiting()).pipe( + Effect.andThen( + Effect.fail(new ConversationSummaryPassError({ runId, cause: stoppedBy })), + ), + ); if (generated === 0 && failed.length > 0) return yield* finish("failed", failed[0]!.reason.slice(0, 300), 0, waiting()); const skipped = [...chunkFailures.values()].filter((failure) => failure.skipped); const skipReason = skipped.length === 0 ? null - : `Skipped ${skipped.length === 1 ? "a stretch" : `${skipped.length} stretches`} after ${CHUNK_FAILURES_BEFORE_SKIP} empty or invalid summaries. ${skipped[0]!.reason}`.slice( + : `Skipped ${skipped.length === 1 ? "a stretch" : `${skipped.length} stretches`} after ${CHUNK_FAILURES_BEFORE_SKIP} unusable summaries. ${skipped[0]!.reason}`.slice( 0, 300, ); diff --git a/apps/server/src/project/conversationSummaries/conversationSummaryTree.ts b/apps/server/src/project/conversationSummaries/conversationSummaryTree.ts index b46a665dd2a9e..71a579623f1bb 100644 --- a/apps/server/src/project/conversationSummaries/conversationSummaryTree.ts +++ b/apps/server/src/project/conversationSummaries/conversationSummaryTree.ts @@ -8,7 +8,7 @@ import { import { sourcesCoverWholeItems } from "./conversationSummarySources.ts"; /** One roll-up call absorbs exactly this many adjacent summaries. */ -const CONDENSE_FAN_IN = 4; +export const CONDENSE_FAN_IN = 4; /** What the tree needs from a stored row. Statements are not loaded. */ export interface StoredSummary { diff --git a/apps/server/src/textGeneration/textGeneratorDrivers.ts b/apps/server/src/textGeneration/textGeneratorDrivers.ts index 419d614516412..f8a6660e787bf 100644 --- a/apps/server/src/textGeneration/textGeneratorDrivers.ts +++ b/apps/server/src/textGeneration/textGeneratorDrivers.ts @@ -158,7 +158,10 @@ const openAICompatible: TextGeneratorDriver = { const text = choice?.message.content?.trim(); if (choice?.finish_reason === "length") { return Effect.fail( - new TextGeneratorRequestError({ detail: `${label} reached its output limit.` }), + new TextGeneratorRequestError({ + detail: `${label} reached its output limit.`, + kind: "output-limit", + }), ); } return text @@ -223,7 +226,10 @@ const anthropic: TextGeneratorDriver = { Effect.flatMap((message) => { if (message.stop_reason === "max_tokens") { return Effect.fail( - new TextGeneratorRequestError({ detail: `${label} reached its output limit.` }), + new TextGeneratorRequestError({ + detail: `${label} reached its output limit.`, + kind: "output-limit", + }), ); } const text = message.content diff --git a/packages/client-runtime/src/conversationSummaries/index.ts b/packages/client-runtime/src/conversationSummaries/index.ts index 75599b3ef7587..50570d5ae6efc 100644 --- a/packages/client-runtime/src/conversationSummaries/index.ts +++ b/packages/client-runtime/src/conversationSummaries/index.ts @@ -36,7 +36,7 @@ export function conversationSummaryPassLabel(pass: ConversationSummaryPass): str : ` ${pass.waitingMessages} older ${pass.waitingMessages === 1 ? "source waits" : "sources wait"} for a summary.`; switch (pass.result) { case "ran": - return `Last pass wrote ${pass.generated} ${pass.generated === 1 ? "summary" : "summaries"}.${waiting}`; + return `Last pass wrote ${pass.generated} ${pass.generated === 1 ? "summary" : "summaries"}.${pass.reason ? ` ${pass.reason}` : ""}${waiting}`; case "skipped": return `Last pass wrote nothing. ${pass.reason ?? ""}${waiting}`.trim(); case "failed": diff --git a/packages/contracts/src/git.ts b/packages/contracts/src/git.ts index 81524dea82143..0c48c99052551 100644 --- a/packages/contracts/src/git.ts +++ b/packages/contracts/src/git.ts @@ -394,10 +394,14 @@ export class GitCommandError extends Schema.TaggedError()("GitC } /** - * A reply the model produced but that held no text or no readable result. Unlike an outage or a - * timeout, the same input may keep producing it. + * A reply the model produced but that held no text, no readable result, or was cut off at its + * output limit. Unlike an outage or a timeout, the same input may keep producing it. */ -export const TextGenerationFailureKind = Schema.Literals(["empty", "invalid-output"]); +export const TextGenerationFailureKind = Schema.Literals([ + "empty", + "invalid-output", + "output-limit", +]); export type TextGenerationFailureKind = typeof TextGenerationFailureKind.Type; export class TextGenerationError extends Schema.TaggedError()( From 7224a93e638e17d07327368d05652054ef93c1f6 Mon Sep 17 00:00:00 2001 From: ScriptedAlchemy Date: Mon, 16 Nov 2026 08:13:45 -0800 Subject: [PATCH 33/37] docs: shorten the summary skip paragraph to when a failure counts, what a skip means, and how to undo it Co-Authored-By: Claude Opus 5.5 --- docs/internals/context-handoffs.md | 17 ++++------------- 1 file changed, 4 insertions(+), 13 deletions(-) diff --git a/docs/internals/context-handoffs.md b/docs/internals/context-handoffs.md index 1df2eccfab92f..81aa32f8c2819 100644 --- a/docs/internals/context-handoffs.md +++ b/docs/internals/context-handoffs.md @@ -47,19 +47,10 @@ again. The pass rolls up a run of four current roots when that run ends before t gap, and makes a new leaf only after those runs. A gap keeps the roots on its far side out of that run, so the neighbours of a replaced leaf never roll up without the replacement. Rolling them up early would summarize more than the broken path, which could then not be rebuilt alone. -A stretch is skipped after its summary comes back empty or unreadable twice, and a failure counts -only when another summary succeeds in the same pass. A pass where nothing succeeds may be a model -outage, so none of its failures count, and the stretches it tried become suspects. Until a pass has -a success, suspects go after other work and only one is tried, so stretches that fail together -cannot hold the front of every pass, and an outage that has made every stretch a suspect costs one -call a pass. After a success, suspects are tried like other work. A suspect counts only a failure -of its own beside a success, so a suspect the pass never reaches counts nothing. An outage neither -adds to a stretch's count nor clears it: a stretch that failed once before the outage is skipped by -its next failure beside a success. A skipped stretch gets no leaf, so it is not a gap: roll-ups -proceed past it. Its items stay uncovered, and delivery replays them verbatim. Skips are keyed by -the summary model, so choosing another model tries the stretch again. The per-thread failure record -is bounded and keeps fewer skips than entries, so a failure still being counted always has room. -When skips overflow, the oldest fall out and those stretches are tried again. +A stretch is skipped after two unusable summaries, and a failure counts only when another summary +succeeds in the same pass, so an outage skips nothing. A skipped stretch gets no leaf, so it is not +a gap and roll-ups proceed past it; delivery replays its items in full. Skips are keyed by the +summary model, and turning summaries back on for the project clears them. A roll-up offer carries no delivered-knowledge evidence, unlike a leaf offer: the evidence of a few hundred items would never fit beside it. Roll-ups are capped by rendered bytes, as delivery measures them, so several fit beside the verbatim tail of a 16 KB handoff. From 70217d4b11388f8c881cdddeb29b784f4ff28c7d Mon Sep 17 00:00:00 2001 From: ScriptedAlchemy Date: Mon, 16 Nov 2026 08:50:52 -0800 Subject: [PATCH 34/37] test(server): summary passes that fail beside a success, or race a re-enable A stretch that always fails without a label (a 400 or a timeout) is never skipped and fails every pass after a success. A pass running while summaries are turned off and on writes the cleared failure ledger back. Co-Authored-By: Claude Opus 5.5 --- .../ConversationSummaries.test.ts | 125 ++++++++++++------ 1 file changed, 84 insertions(+), 41 deletions(-) diff --git a/apps/server/src/project/conversationSummaries/ConversationSummaries.test.ts b/apps/server/src/project/conversationSummaries/ConversationSummaries.test.ts index 32f30c5c5a239..89afbca4d105c 100644 --- a/apps/server/src/project/conversationSummaries/ConversationSummaries.test.ts +++ b/apps/server/src/project/conversationSummaries/ConversationSummaries.test.ts @@ -43,6 +43,7 @@ import { historyCost } from "@t3tools/provider-core/server/handoffBudget"; import * as Digest from "effect/crypto/Digest"; import * as DateTime from "effect/DateTime"; import * as Deferred from "effect/Deferred"; +import * as Fiber from "effect/Fiber"; import * as Effect from "effect/Effect"; import * as Hex from "effect/encoding/Hex"; import * as Layer from "effect/Layer"; @@ -196,6 +197,7 @@ const isRollup = (call: Parameters[0]) => call.messages.some((message) => message.role === "summary"); // An update returns once the service has pulled the next change, so its reaction has finished. +// With no subscriber pulling, an update waits forever. const settingsLayer = (overrides: Parameters[0]) => Layer.effect( ServerSettings.ServerSettingsService, @@ -709,19 +711,29 @@ it.effect("records an unavailable model as a failed pass without publishing a su }).pipe(Effect.provide(makeLayer(model.generate, optedIn))); }); -const failingStretch = (kind: "empty" | "invalid-output") => - new TextGenerationError({ - operation: "generateConversationSummary", - detail: - kind === "empty" - ? "Router returned no text." - : "Router returned a reply T3 Code couldn't read.", - kind, - }); +const failingStretch = (kind: "empty" | "invalid-output" | "unlabelled") => + kind === "unlabelled" + ? new TextGenerationError({ + operation: "generateConversationSummary", + detail: "Router rejected the request: the prompt is too long.", + }) + : new TextGenerationError({ + operation: "generateConversationSummary", + detail: + kind === "empty" + ? "Router returned no text." + : "Router returned a reply T3 Code couldn't read.", + kind, + }); -it.effect.each(["empty", "invalid-output"] as const)( - "skips a stretch whose summary is always %s while other stretches summarize, and rolls up past it", - (kind) => { +// An unlabelled failure fails the pass before any success, so it takes two more passes to skip. +it.effect.each([ + { kind: "empty", results: ["ran", "ran"] }, + { kind: "invalid-output", results: ["ran", "ran"] }, + { kind: "unlabelled", results: ["failed", "ran", "failed", "ran"] }, +] as const)( + "skips a stretch whose summary is always $kind while other stretches summarize, and rolls up past it", + ({ kind, results }) => { const model = scripted((input) => input.messages[0]?.text === rawText(0) ? Effect.fail(failingStretch(kind)) @@ -734,16 +746,20 @@ it.effect.each(["empty", "invalid-output"] as const)( return Effect.gen(function* () { // Five full leaves of 24 settled messages. yield* seedThread(5 * 24 + 6); - yield* summarize; - yield* summarize; - assert.equal(firstStretchCalls(), 2); + const passes: Array = []; + for (let pass = 0; pass < results.length; pass++) { + yield* Effect.exit(summarize); + passes.push((yield* list).lastPass?.result); + } + assert.deepEqual(passes, [...results]); + assert.equal(firstStretchCalls(), results.length); const skipped = (yield* list).lastPass; assert.include(skipped?.reason ?? "", "Skipped a stretch"); assert.equal(skipped?.waitingMessages, 0); assert.notProperty(skipped, "chunkFailures"); yield* summarize; - assert.equal(firstStretchCalls(), 2); + assert.equal(firstStretchCalls(), results.length); assert.isTrue(isRollup(model.calls.at(-1)!)); const service = yield* ConversationSummaries.ConversationSummaries; const offered = yield* service.forHandoff({ @@ -761,14 +777,14 @@ it.effect.each(["empty", "invalid-output"] as const)( }); yield* summarize; yield* settings.updateSettings(optedIn); - yield* summarize; - assert.equal(firstStretchCalls(), 3); + yield* Effect.exit(summarize); + assert.equal(firstStretchCalls(), results.length + 1); yield* settings.updateSettings({ textGenerationModelSelection: { instanceId, model: "gpt-5-mini" }, }); - yield* summarize; - assert.equal(firstStretchCalls(), 4); + yield* Effect.exit(summarize); + assert.equal(firstStretchCalls(), results.length + 2); }).pipe(Effect.provide(makeLayer(model.generate, optedIn))); }, ); @@ -1006,9 +1022,10 @@ it.effect("summarizes the next stretch when the model cites none of the chunk", }).pipe(Effect.provide(makeLayer(model.generate, optedIn))); }); -it.effect("works around a chunk that always times out, without skipping it", () => { +it.effect("retries every pass and skips nothing while every summary times out", () => { + let down = true; const model = scripted((input) => - input.messages[0]?.text === rawText(0) + down ? Effect.fail( new TextGenerationError({ operation: "generateConversationSummary", @@ -1016,30 +1033,56 @@ it.effect("works around a chunk that always times out, without skipping it", () }), ) : Effect.succeed({ - statements: [{ text: "The later stretch.", citations: [input.messages[0]!.ref] }], + statements: [{ text: "Recovered.", citations: [input.messages[0]!.ref] }], }), ); - const firstChunkCalls = () => - model.calls.filter((call) => call.messages[0]?.text === rawText(0)).length; return Effect.gen(function* () { - yield* seedThread(38); - assert.instanceOf(yield* summarize.pipe(Effect.flip), ConversationSummaryPassError); - assert.equal(model.calls.length, 1); + yield* seedThread(5 * 24 + 6); + for (let pass = 0; pass < 4; pass++) + assert.instanceOf(yield* summarize.pipe(Effect.flip), ConversationSummaryPassError); assert.deepEqual((yield* list).summaries, []); - for (let pass = 0; pass < 3; pass++) - assert.instanceOf(yield* summarize.pipe(Effect.flip), ConversationSummaryPassError); - assert.equal(firstChunkCalls(), 4); - assert.include( - (yield* list).summaries.flatMap((read) => - read.state === "available" - ? read.summary.sources.flatMap((source) => - source.kind === "message" ? [source.messageId] : [], - ) - : [], - ), - messageId(24), - ); + down = false; + for (let pass = 0; pass < 3; pass++) yield* summarize; + assert.equal((yield* list).lastPass?.waitingMessages, 0); + assert.notInclude((yield* list).lastPass?.reason ?? "", "Skipped"); + }).pipe(Effect.provide(makeLayer(model.generate, optedIn))); +}); + +it.effect("turning summaries back on during a pass still retries skipped stretches", () => { + let gate: { entered: Deferred.Deferred; release: Deferred.Deferred } | undefined; + const model = scripted((input) => + Effect.gen(function* () { + if (gate !== undefined) { + yield* Deferred.succeed(gate.entered, undefined); + yield* Deferred.await(gate.release); + } + if (input.messages[0]?.text === rawText(0)) return yield* failingStretch("empty"); + return { statements: [{ text: "Summarized.", citations: [input.messages[0]!.ref] }] }; + }), + ); + const firstStretchCalls = () => + model.calls.filter((call) => call.messages[0]?.text === rawText(0)).length; + return Effect.gen(function* () { + yield* seedThread(5 * 24 + 6); + yield* summarize; + yield* summarize; + assert.include((yield* list).lastPass?.reason ?? "", "Skipped a stretch"); + + gate = { entered: yield* Deferred.make(), release: yield* Deferred.make() }; + const pass = yield* summarize.pipe(Effect.forkChild); + yield* Deferred.await(gate.entered); + const settings = yield* ServerSettings.ServerSettingsService; + yield* settings.updateSettings({ + projectSettingsOverrides: { [projectId]: { enableConversationSummaries: false } }, + }); + yield* settings.updateSettings(optedIn); + yield* Deferred.succeed(gate.release, undefined); + yield* Fiber.join(pass); + gate = undefined; + + yield* summarize; + assert.equal(firstStretchCalls(), 3); }).pipe(Effect.provide(makeLayer(model.generate, optedIn))); }); From 69ba7070bd5a313757677bb0a233f9fa629fab2f Mon Sep 17 00:00:00 2001 From: ScriptedAlchemy Date: Mon, 16 Nov 2026 08:51:40 -0800 Subject: [PATCH 35/37] fix(server): unlabelled summary failures can be skipped, and a re-enable reset survives a running pass A failure that is not an unusable reply fails the pass only when nothing was generated in it; beside a success it counts toward a skip like any other failure, and the pass finishes normally. The pass writes its failure ledger in a transaction that keeps a reset made while it ran, so only its own failures survive the reset. Co-Authored-By: Claude Opus 5.5 --- .../ConversationSummaries.ts | 68 ++++++++++++------- docs/internals/context-handoffs.md | 2 +- 2 files changed, 43 insertions(+), 27 deletions(-) diff --git a/apps/server/src/project/conversationSummaries/ConversationSummaries.ts b/apps/server/src/project/conversationSummaries/ConversationSummaries.ts index b79fc0cbb13c9..bbb3a9b5410bb 100644 --- a/apps/server/src/project/conversationSummaries/ConversationSummaries.ts +++ b/apps/server/src/project/conversationSummaries/ConversationSummaries.ts @@ -929,6 +929,34 @@ const make = Effect.gen(function* () { const chunkFailures = new Map( (prior?.chunkFailures ?? []).map((failure) => [failure.key, failure]), ); + const charges: Array<{ + readonly key: string; + readonly reason: string; + readonly suspect: boolean; + }> = []; + const charge = ({ key, reason, suspect }: (typeof charges)[number]) => { + const failures = (chunkFailures.get(key)?.failures ?? 0) + (suspect ? 0 : 1); + chunkFailures.delete(key); + chunkFailures.set(key, { + key, + failures, + ...(failures >= CHUNK_FAILURES_BEFORE_SKIP ? { skipped: true } : {}), + ...(suspect ? { suspect: true } : {}), + reason: reason.slice(0, 300), + }); + }; + // Re-enabling summaries may clear the ledger while this pass runs. The reset wins, so only + // this pass's own failures survive it. + const keepReset = Effect.fnUntraced(function* () { + if (prior?.chunkFailures === undefined) return; + const cleared = yield* sql<{ readonly cleared: number }>` + SELECT json_extract(payload_json, '$.chunkFailures') IS NULL AS cleared + FROM conversation_summary_passes WHERE thread_id = ${threadId} + `; + if (cleared[0]?.cleared !== 1) return; + chunkFailures.clear(); + for (const failure of charges) charge(failure); + }); const finish = ( result: ConversationSummaryPass["result"], reason: string | null, @@ -938,6 +966,7 @@ const make = Effect.gen(function* () { ) => cleanupSuperseded(superseded()).pipe( Effect.andThen(DateTime.now), + Effect.tap(keepReset), Effect.flatMap((now) => { const failures = [...chunkFailures.values()]; const open = failures.filter((failure) => failure.skipped !== true); @@ -956,6 +985,7 @@ const make = Effect.gen(function* () { ...(stored.length === 0 ? {} : { chunkFailures: stored }), }); }), + sql.withTransaction, Effect.as({ hasMore }), ); if (records.thread.deletedAt !== null) @@ -1283,11 +1313,7 @@ const make = Effect.gen(function* () { return null; }; const blocked = new Set(); - const failed: Array<{ - readonly raw: string; - readonly reason: string; - readonly countable: boolean; - }> = []; + const failed: Array<{ readonly raw: string; readonly reason: string }> = []; let stoppedBy: string | undefined; let attempts = 0; while (generated < MAX_SUMMARIES_PER_PASS && attempts < MAX_SUMMARIES_PER_PASS) { @@ -1298,14 +1324,11 @@ const make = Effect.gen(function* () { const published = work.kind === "leaf" ? yield* summarizeLeaf(work.chunk) : yield* condense(work.group); if (!published.ok) { - failed.push({ - raw: work.key, - reason: published.reason, - countable: published.unusableReply, - }); + failed.push({ raw: work.key, reason: published.reason }); blocked.add(work.key); - // An outage or a rejected request fails the pass so it retries, but its work goes last. - if (!published.unusableReply) { + // Before any success, an outage or a rejected request fails the pass so it retries, but + // its work goes last. + if (!published.unusableReply && generated === 0) { stoppedBy = published.reason; break; } @@ -1319,19 +1342,11 @@ const make = Effect.gen(function* () { } // With nothing succeeding, the model may be down or unable to answer at all. Blaming the // chunk would skip the thread's whole history, so that failure is not counted. - const charge = (key: string, reason: string, suspect: boolean) => { - const failures = (chunkFailures.get(key)?.failures ?? 0) + (suspect ? 0 : 1); - chunkFailures.delete(key); - chunkFailures.set(key, { - key, - failures, - ...(failures >= CHUNK_FAILURES_BEFORE_SKIP ? { skipped: true } : {}), - ...(suspect ? { suspect: true } : {}), - reason: reason.slice(0, 300), - }); - }; - for (const { raw, reason, countable } of failed) - charge(yield* keyOf(raw), reason, !countable || generated === 0); + for (const { raw, reason } of failed) { + const failure = { key: yield* keyOf(raw), reason, suspect: generated === 0 }; + charges.push(failure); + charge(failure); + } if (stoppedBy !== undefined) return yield* finish("failed", stoppedBy.slice(0, 300), generated, waiting()).pipe( Effect.andThen( @@ -1344,13 +1359,14 @@ const make = Effect.gen(function* () { const skipReason = skipped.length === 0 ? null - : `Skipped ${skipped.length === 1 ? "a stretch" : `${skipped.length} stretches`} after ${CHUNK_FAILURES_BEFORE_SKIP} unusable summaries. ${skipped[0]!.reason}`.slice( + : `Skipped ${skipped.length === 1 ? "a stretch" : `${skipped.length} stretches`} after ${CHUNK_FAILURES_BEFORE_SKIP} failed summaries. ${skipped[0]!.reason}`.slice( 0, 300, ); return yield* finish( generated > 0 ? "ran" : "skipped", skipReason ?? + failed[0]?.reason.slice(0, 300) ?? (generated > 0 ? null : "No settled stretch is long enough to summarize yet."), generated, waiting(), diff --git a/docs/internals/context-handoffs.md b/docs/internals/context-handoffs.md index 81aa32f8c2819..862ca7c52483c 100644 --- a/docs/internals/context-handoffs.md +++ b/docs/internals/context-handoffs.md @@ -47,7 +47,7 @@ again. The pass rolls up a run of four current roots when that run ends before t gap, and makes a new leaf only after those runs. A gap keeps the roots on its far side out of that run, so the neighbours of a replaced leaf never roll up without the replacement. Rolling them up early would summarize more than the broken path, which could then not be rebuilt alone. -A stretch is skipped after two unusable summaries, and a failure counts only when another summary +A stretch is skipped after two failed summaries, and a failure counts only when another summary succeeds in the same pass, so an outage skips nothing. A skipped stretch gets no leaf, so it is not a gap and roll-ups proceed past it; delivery replays its items in full. Skips are keyed by the summary model, and turning summaries back on for the project clears them. From 237c21f24f8f3a26d9554c34d93dc09abd72e465 Mon Sep 17 00:00:00 2001 From: ScriptedAlchemy Date: Mon, 16 Nov 2026 08:59:39 -0800 Subject: [PATCH 36/37] test(server): a pass whose first summary succeeds and the rest time out skips nothing Co-Authored-By: Claude Fable 5.2 --- .../ConversationSummaries.test.ts | 57 +++++++++++-------- 1 file changed, 33 insertions(+), 24 deletions(-) diff --git a/apps/server/src/project/conversationSummaries/ConversationSummaries.test.ts b/apps/server/src/project/conversationSummaries/ConversationSummaries.test.ts index 89afbca4d105c..fd61a6a34f64b 100644 --- a/apps/server/src/project/conversationSummaries/ConversationSummaries.test.ts +++ b/apps/server/src/project/conversationSummaries/ConversationSummaries.test.ts @@ -43,6 +43,7 @@ import { historyCost } from "@t3tools/provider-core/server/handoffBudget"; import * as Digest from "effect/crypto/Digest"; import * as DateTime from "effect/DateTime"; import * as Deferred from "effect/Deferred"; +import * as Exit from "effect/Exit"; import * as Fiber from "effect/Fiber"; import * as Effect from "effect/Effect"; import * as Hex from "effect/encoding/Hex"; @@ -1022,32 +1023,40 @@ it.effect("summarizes the next stretch when the model cites none of the chunk", }).pipe(Effect.provide(makeLayer(model.generate, optedIn))); }); -it.effect("retries every pass and skips nothing while every summary times out", () => { - let down = true; - const model = scripted((input) => - down - ? Effect.fail( - new TextGenerationError({ - operation: "generateConversationSummary", - detail: "OpenCode did not finish generating in time.", +it.effect.each([0, 1])( + "skips nothing while every summary after the first %i of a pass times out", + (healthy) => { + let down = true; + let callsThisPass = 0; + const model = scripted((input) => + down && callsThisPass++ >= healthy + ? Effect.fail( + new TextGenerationError({ + operation: "generateConversationSummary", + detail: "OpenCode did not finish generating in time.", + }), + ) + : Effect.succeed({ + statements: [{ text: "Recovered.", citations: [input.messages[0]!.ref] }], }), - ) - : Effect.succeed({ - statements: [{ text: "Recovered.", citations: [input.messages[0]!.ref] }], - }), - ); - return Effect.gen(function* () { - yield* seedThread(5 * 24 + 6); - for (let pass = 0; pass < 4; pass++) - assert.instanceOf(yield* summarize.pipe(Effect.flip), ConversationSummaryPassError); - assert.deepEqual((yield* list).summaries, []); + ); + return Effect.gen(function* () { + yield* seedThread(5 * 24 + 6); + for (let pass = 0; pass < 4; pass++) { + callsThisPass = 0; + const exit = yield* Effect.exit(summarize); + if (healthy === 0) assert.isTrue(Exit.isFailure(exit)); + assert.notInclude((yield* list).lastPass?.reason ?? "", "Skipped"); + } + if (healthy === 0) assert.deepEqual((yield* list).summaries, []); - down = false; - for (let pass = 0; pass < 3; pass++) yield* summarize; - assert.equal((yield* list).lastPass?.waitingMessages, 0); - assert.notInclude((yield* list).lastPass?.reason ?? "", "Skipped"); - }).pipe(Effect.provide(makeLayer(model.generate, optedIn))); -}); + down = false; + for (let pass = 0; pass < 3; pass++) yield* summarize; + assert.equal((yield* list).lastPass?.waitingMessages, 0); + assert.notInclude((yield* list).lastPass?.reason ?? "", "Skipped"); + }).pipe(Effect.provide(makeLayer(model.generate, optedIn))); + }, +); it.effect("turning summaries back on during a pass still retries skipped stretches", () => { let gate: { entered: Deferred.Deferred; release: Deferred.Deferred } | undefined; From a67d7695f97f3830a827903604ecc1aceacc7229 Mon Sep 17 00:00:00 2001 From: ScriptedAlchemy Date: Mon, 16 Nov 2026 09:01:18 -0800 Subject: [PATCH 37/37] fix(server): a timeout counts toward a summary skip only when a later summary succeeds Co-Authored-By: Claude Fable 5.2 --- .../ConversationSummaries.ts | 23 +++++++++++++++---- docs/internals/context-handoffs.md | 4 +++- 2 files changed, 21 insertions(+), 6 deletions(-) diff --git a/apps/server/src/project/conversationSummaries/ConversationSummaries.ts b/apps/server/src/project/conversationSummaries/ConversationSummaries.ts index bbb3a9b5410bb..e59c1788107ed 100644 --- a/apps/server/src/project/conversationSummaries/ConversationSummaries.ts +++ b/apps/server/src/project/conversationSummaries/ConversationSummaries.ts @@ -1313,7 +1313,12 @@ const make = Effect.gen(function* () { return null; }; const blocked = new Set(); - const failed: Array<{ readonly raw: string; readonly reason: string }> = []; + const failed: Array<{ + readonly raw: string; + readonly reason: string; + readonly unusableReply: boolean; + readonly generatedBefore: number; + }> = []; let stoppedBy: string | undefined; let attempts = 0; while (generated < MAX_SUMMARIES_PER_PASS && attempts < MAX_SUMMARIES_PER_PASS) { @@ -1324,7 +1329,12 @@ const make = Effect.gen(function* () { const published = work.kind === "leaf" ? yield* summarizeLeaf(work.chunk) : yield* condense(work.group); if (!published.ok) { - failed.push({ raw: work.key, reason: published.reason }); + failed.push({ + raw: work.key, + reason: published.reason, + unusableReply: published.unusableReply, + generatedBefore: generated, + }); blocked.add(work.key); // Before any success, an outage or a rejected request fails the pass so it retries, but // its work goes last. @@ -1341,9 +1351,12 @@ const make = Effect.gen(function* () { generated += 1; } // With nothing succeeding, the model may be down or unable to answer at all. Blaming the - // chunk would skip the thread's whole history, so that failure is not counted. - for (const { raw, reason } of failed) { - const failure = { key: yield* keyOf(raw), reason, suspect: generated === 0 }; + // chunk would skip the thread's whole history, so that failure is not counted. A timeout or + // rejection counts only when a summary succeeded after it: a provider that answers once and + // then stalls is still an outage. + for (const { raw, reason, unusableReply, generatedBefore } of failed) { + const counted = unusableReply ? generated > 0 : generated > generatedBefore; + const failure = { key: yield* keyOf(raw), reason, suspect: !counted }; charges.push(failure); charge(failure); } diff --git a/docs/internals/context-handoffs.md b/docs/internals/context-handoffs.md index 862ca7c52483c..b4013fb678ac8 100644 --- a/docs/internals/context-handoffs.md +++ b/docs/internals/context-handoffs.md @@ -48,7 +48,9 @@ gap, and makes a new leaf only after those runs. A gap keeps the roots on its fa that run, so the neighbours of a replaced leaf never roll up without the replacement. Rolling them up early would summarize more than the broken path, which could then not be rebuilt alone. A stretch is skipped after two failed summaries, and a failure counts only when another summary -succeeds in the same pass, so an outage skips nothing. A skipped stretch gets no leaf, so it is not +succeeds in the same pass, so an outage skips nothing. A timeout or rejected request counts only +when a summary succeeds after it, so a provider that answers once and then stalls skips nothing +either. A skipped stretch gets no leaf, so it is not a gap and roll-ups proceed past it; delivery replays its items in full. Skips are keyed by the summary model, and turning summaries back on for the project clears them. A roll-up offer carries no delivered-knowledge evidence, unlike a leaf offer: the evidence of a few