diff --git a/apps/server/src/orchestration-v2/EffectOutbox.ts b/apps/server/src/orchestration-v2/EffectOutbox.ts index b52ea74530d92..7c5ff1e9280c2 100644 --- a/apps/server/src/orchestration-v2/EffectOutbox.ts +++ b/apps/server/src/orchestration-v2/EffectOutbox.ts @@ -231,6 +231,7 @@ export const OrchestrationEffectStatusV2 = Schema.Literals([ ]); export type OrchestrationEffectStatusV2 = typeof OrchestrationEffectStatusV2.Type; +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; @@ -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, @@ -505,7 +517,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 +526,20 @@ 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. + -- 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 ( + 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' + AND pending_summary.attempt_count = 0 + )` + : sql`1 = 1` + } ON CONFLICT(effect_id) DO NOTHING `, { concurrency: 1, discard: true }, @@ -614,6 +641,19 @@ 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 = 'cancelled', + lease_owner = NULL, + completed_at = ${now}, + updated_at = ${now}, + last_error = ${SUMMARY_PASS_SUPERSEDED} + WHERE status = 'running' + AND ${summaryPassHasPendingSuccessor} + RETURNING effect_id + `; const requeuedRows = yield* sql<{ readonly effect_id: string }>` UPDATE orchestration_v2_effect_outbox SET @@ -626,8 +666,12 @@ 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); - return { requeued: requeuedRows.length, cancelled: cancelledRows.length }; + if (requeuedRows.length > 0 || coveredRows.length > 0) + yield* notifyAvailable(requeuedRows.length + coveredRows.length); + return { + requeued: requeuedRows.length, + cancelled: cancelledRows.length + coveredRows.length, + }; }).pipe( Effect.mapError( (cause) => new EffectOutboxError({ operation: "reconcile-process-loss", cause }), @@ -756,6 +800,26 @@ 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 = 'cancelled', + lease_owner = NULL, + completed_at = ${nowIso}, + updated_at = ${nowIso}, + last_error = ${SUMMARY_PASS_SUPERSEDED} + WHERE effect_id = ${effectId} + AND status = 'running' + AND lease_owner = ${workerId} + AND ${summaryPassHasPendingSuccessor} + 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/orchestration-v2/EffectWorker.test.ts b/apps/server/src/orchestration-v2/EffectWorker.test.ts index 53622ad0167c6..6cff65045ea90 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,144 @@ 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); + 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)) + 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: 1 }); + 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)); + }), +); + it.effect.each(["turn", "maintenance"] as const)( "wakes the %s lane when the other lane is waiting first", (lane) => diff --git a/apps/server/src/project/conversationSummaries/ConversationSummaries.test.ts b/apps/server/src/project/conversationSummaries/ConversationSummaries.test.ts index a286802f16670..fd61a6a34f64b 100644 --- a/apps/server/src/project/conversationSummaries/ConversationSummaries.test.ts +++ b/apps/server/src/project/conversationSummaries/ConversationSummaries.test.ts @@ -42,10 +42,15 @@ 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 Exit from "effect/Exit"; +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"; +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 +197,44 @@ 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. +// With no subscriber pulling, an update waits forever. +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 +254,7 @@ const makeLayer = (generate: Generate, settings: Parameters + 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, + }); + +// 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)) + : 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); + 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(), results.length); + 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* Effect.exit(summarize); + assert.equal(firstStretchCalls(), results.length + 1); + + yield* settings.updateSettings({ + textGenerationModelSelection: { instanceId, model: "gpt-5-mini" }, + }); + yield* Effect.exit(summarize); + assert.equal(firstStretchCalls(), results.length + 2); + }).pipe(Effect.provide(makeLayer(model.generate, optedIn))); + }, +); + +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] }], + }), + ); + 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; + 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) => + 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(8 * 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); + const settled = badCalls(); + yield* summarize; + assert.equal(badCalls(), settled); + }).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; + 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({ + 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.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] }], + }), + ); + 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))); + }, +); + +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))); +}); + it.effect( "covers every range of a long source and offers it only after all ranges are summarized", () => { @@ -1127,6 +1553,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* () { @@ -1140,11 +1603,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..e59c1788107ed 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,11 +69,13 @@ import { import { buildSummaryTree, childIds, + CONDENSE_FAN_IN, condensedPosition, handoffCover, isRangeRef, leafPosition, planCondensation, + rootsBeforeFirstGap, type StoredSummary, type SummaryNode, type SummaryTree, @@ -81,6 +86,14 @@ 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; +// 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; @@ -120,8 +133,26 @@ 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), + // Last failed in a pass where nothing succeeded, so that failure was not counted. + suspect: 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); @@ -761,11 +792,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 @@ -808,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", )( @@ -852,6 +917,46 @@ const make = Effect.gen(function* () { ) .map((row) => row.id); }; + 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 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, @@ -861,16 +966,26 @@ const make = Effect.gen(function* () { ) => cleanupSuperseded(superseded()).pipe( Effect.andThen(DateTime.now), - Effect.flatMap((now) => - recordPass(projectId, threadId, { + Effect.tap(keepReset), + Effect.flatMap((now) => { + const failures = [...chunkFailures.values()]; + const open = failures.filter((failure) => failure.skipped !== true); + const stored = [ + ...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, { runId, result, reason, generated, waitingMessages, at: DateTime.formatIso(now), - }), - ), + ...(stored.length === 0 ? {} : { chunkFailures: stored }), + }); + }), + sql.withTransaction, Effect.as({ hasMore }), ); if (records.thread.deletedAt !== null) @@ -973,17 +1088,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<{ @@ -1016,10 +1121,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(); @@ -1035,10 +1144,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( [ @@ -1116,30 +1230,160 @@ 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. - const nextWork = () => { - 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 }; + 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"); + for (const chunk of planLeafChunks({ settled, covered })) yield* keyOf(leafChunkKey(chunk)); + 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); + + const failureOf = (raw: string) => { + const key = keys.get(raw); + 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; }; - while (generated < MAX_SUMMARIES_PER_PASS) { - const work = nextWork(); + // 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 selectFrom = (avoid: (raw: string) => boolean) => { + const held = (raw: string) => avoid(raw) || isSkipped(raw); + const chunks = planLeafChunks({ settled, covered }); + const group = planCondensation( + rootsBeforeFirstGap({ + roots: tree.roots, + order: settled.map((source) => conversationSummarySourceKey(source.ref)), + covered, + skipped: skippedSources(chunks), + }), + (run) => !held(rollupKey(run)), + ); + if (group !== null) return { kind: "condense" as const, group, key: rollupKey(group) }; + const chunk = chunks.find((candidate) => !held(leafChunkKey(candidate))); + return chunk === undefined + ? 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, 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)); + 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; + readonly unusableReply: boolean; + readonly generatedBefore: number; + }> = []; + let stoppedBy: string | undefined; + let attempts = 0; + while (generated < MAX_SUMMARIES_PER_PASS && attempts < MAX_SUMMARIES_PER_PASS) { + 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) return yield* failPass(published.reason); + if (!published.ok) { + 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. + if (!published.unusableReply && generated === 0) { + stoppedBy = published.reason; + break; + } + continue; + } + const key = keys.get(work.key); + if (key !== undefined) chunkFailures.delete(key); rows.set(published.row.id, published.row); rebuild(); 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. 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); + } + 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} failed 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 ?? + failed[0]?.reason.slice(0, 300) ?? + (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/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; diff --git a/apps/server/src/project/conversationSummaries/conversationSummaryTree.ts b/apps/server/src/project/conversationSummaries/conversationSummaryTree.ts index 35be5d26e8980..71a579623f1bb 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"; @@ -7,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 { @@ -124,6 +125,35 @@ 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. 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) && !input.skipped.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 @@ -132,6 +162,7 @@ export function buildSummaryTree( */ 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++) { @@ -139,6 +170,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/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.test.ts b/apps/server/src/textGeneration/ClaudeTextGeneration.test.ts index 866fa072f834a..d7e51aae96409 100644 --- a/apps/server/src/textGeneration/ClaudeTextGeneration.test.ts +++ b/apps/server/src/textGeneration/ClaudeTextGeneration.test.ts @@ -493,6 +493,48 @@ 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, 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, exitCode, kind]) => + withFakeClaudeEnv( + { output: JSON.stringify([{ type: "system", subtype: "init" }, result]), exitCode }, + (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 }, diff --git a/apps/server/src/textGeneration/ClaudeTextGeneration.ts b/apps/server/src/textGeneration/ClaudeTextGeneration.ts index b5eef19186a77..6ce08be7929dd 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); @@ -76,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)), }); @@ -83,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 ?? @@ -321,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, @@ -331,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 } : {}), }), ); }), @@ -362,6 +377,11 @@ 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 !== undefined && + envelope.is_error !== true && + (envelope.subtype ?? "success") === "success"; const decodeOutput = Schema.decodeEffect( outputSchemaJson, @@ -374,6 +394,7 @@ export const makeClaudeTextGeneration = Effect.fn("makeClaudeTextGeneration")(fu new TextGenerationError({ operation, detail: "Claude returned invalid structured output.", + ...(modelAnswered ? { kind: "invalid-output" as const } : {}), 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.test.ts b/apps/server/src/textGeneration/TextGenerators.test.ts index 0806789b97fc9..a49440a243e99 100644 --- a/apps/server/src/textGeneration/TextGenerators.test.ts +++ b/apps/server/src/textGeneration/TextGenerators.test.ts @@ -48,12 +48,16 @@ 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: " " } }] }, + cutOff: { choices: [{ finish_reason: "length", message: { content: '{"title":' } }] }, }, { 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: [] }, + 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* () { @@ -84,6 +88,17 @@ 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"); + expect(yield* kindOf(api.cutOff)).toBe("output-limit"); }), ); 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..f8a6660e787bf 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, }), ), @@ -149,12 +158,20 @@ 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 ? 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), ); @@ -209,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 @@ -218,7 +238,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/docs/internals/context-handoffs.md b/docs/internals/context-handoffs.md index 1e8f4fe85d034..b4013fb678ac8 100644 --- a/docs/internals/context-handoffs.md +++ b/docs/internals/context-handoffs.md @@ -43,8 +43,16 @@ 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 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 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 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. 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 45d68c5e9ca44..0c48c99052551 100644 --- a/packages/contracts/src/git.ts +++ b/packages/contracts/src/git.ts @@ -393,11 +393,23 @@ export class GitCommandError extends Schema.TaggedError()("GitC } } +/** + * 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", + "output-limit", +]); +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.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-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.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-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.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)), ); 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); },