diff --git a/apps/server/src/modelEvaluations/ModelEvaluationSubagentRefresh.test.ts b/apps/server/src/modelEvaluations/ModelEvaluationSubagentRefresh.test.ts new file mode 100644 index 0000000000000..a0c6f44d9939d --- /dev/null +++ b/apps/server/src/modelEvaluations/ModelEvaluationSubagentRefresh.test.ts @@ -0,0 +1,57 @@ +import { assert, it } from "@effect/vitest"; +import { RunId, ThreadId, type OrchestrationV2DomainEvent } from "@t3tools/contracts"; +import * as Deferred from "effect/Deferred"; +import * as Effect from "effect/Effect"; +import * as Fiber from "effect/Fiber"; +import * as Queue from "effect/Queue"; +import * as Stream from "effect/Stream"; +import * as TestClock from "effect/testing/TestClock"; + +import * as Orchestrator from "../orchestration-v2/Orchestrator.ts"; +import { followSettledSubagentRefreshes } from "./ModelEvaluationSubagentRefresh.ts"; + +const runId = RunId.make("parent-run"); + +const settledChild = { + type: "turn-item.updated", + threadId: ThreadId.make("parent-thread"), + runId, + payload: { type: "subagent", status: "completed", runId }, +} as OrchestrationV2DomainEvent; + +it.effect("keeps refreshing after the event stream fails", () => + Effect.gen(function* () { + const events = yield* Queue.unbounded(); + const started = yield* Deferred.make(); + const refreshed = yield* Deferred.make(); + let subscriptions = 0; + const fiber = yield* Effect.forkChild( + followSettledSubagentRefreshes({ + evaluations: { + enqueueSettledSubagentRefreshes: (input) => + input?.runId === undefined + ? Effect.void + : Deferred.succeed(refreshed, input.runId).pipe(Effect.asVoid), + }, + orchestrator: { + getLatestEventSequence: () => Deferred.succeed(started, undefined).pipe(Effect.as(0)), + streamDomainEventsAfter: () => { + subscriptions += 1; + return subscriptions === 1 + ? Stream.fail( + new Orchestrator.OrchestratorDomainEventStreamError({ + cause: new Error("subscription dropped"), + }), + ) + : Stream.fromQueue(events); + }, + }, + }), + ); + yield* Deferred.await(started); + yield* TestClock.adjust("1 second"); + yield* Queue.offer(events, settledChild); + assert.equal(yield* Deferred.await(refreshed), runId); + yield* Fiber.interrupt(fiber); + }), +); diff --git a/apps/server/src/modelEvaluations/ModelEvaluationSubagentRefresh.ts b/apps/server/src/modelEvaluations/ModelEvaluationSubagentRefresh.ts new file mode 100644 index 0000000000000..80fce01dee722 --- /dev/null +++ b/apps/server/src/modelEvaluations/ModelEvaluationSubagentRefresh.ts @@ -0,0 +1,94 @@ +import { + isOrchestrationV2WorkActive, + type OrchestrationV2DomainEvent, + type RunId, + type ThreadId, +} from "@t3tools/contracts"; +import * as Context from "effect/Context"; +import * as Duration from "effect/Duration"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as Schedule from "effect/Schedule"; +import type * as Scope from "effect/Scope"; +import * as Stream from "effect/Stream"; + +import * as Orchestrator from "../orchestration-v2/Orchestrator.ts"; +import { forkParked } from "../serverActivation.ts"; +import * as ModelEvaluations from "./ModelEvaluations.ts"; + +export class ModelEvaluationSubagentRefresh extends Context.Service< + ModelEvaluationSubagentRefresh, + { + readonly start: () => Effect.Effect; + } +>()("t3/modelEvaluations/ModelEvaluationSubagentRefresh") {} + +const subscriptionBackoff = Schedule.exponential("1 second").pipe( + Schedule.modifyDelay(({ duration }) => + Effect.succeed(Duration.min(duration, Duration.minutes(1))), + ), +); + +function settledSubagentRun( + event: OrchestrationV2DomainEvent, +): { readonly threadId: ThreadId; readonly runId: RunId } | undefined { + if (event.type !== "turn-item.updated" || event.payload.type !== "subagent") return undefined; + if (isOrchestrationV2WorkActive(event.payload.status)) return undefined; + const runId = event.runId ?? event.payload.runId; + if (runId === undefined || runId === null) return undefined; + return { threadId: event.threadId, runId }; +} + +export const followSettledSubagentRefreshes = Effect.fn("ModelEvaluationSubagentRefresh.follow")( + function* (input: { + readonly evaluations: Pick< + ModelEvaluations.ModelEvaluations["Service"], + "enqueueSettledSubagentRefreshes" + >; + readonly orchestrator: Pick< + Orchestrator.OrchestratorV2["Service"], + "getLatestEventSequence" | "streamDomainEventsAfter" + >; + }) { + yield* Effect.gen(function* () { + const after = yield* input.orchestrator.getLatestEventSequence(); + yield* input.evaluations + .enqueueSettledSubagentRefreshes() + .pipe( + Effect.catchCause((cause) => + Effect.logWarning("Could not refresh settled subagent evaluations", { cause }), + ), + ); + yield* Stream.runForEach(input.orchestrator.streamDomainEventsAfter(after), (event) => { + const run = settledSubagentRun(event); + if (run === undefined) return Effect.void; + return input.evaluations.enqueueSettledSubagentRefreshes({ runId: run.runId }).pipe( + Effect.catchCause((cause) => + Effect.logWarning("Could not refresh a settled subagent evaluation", { + threadId: run.threadId, + runId: run.runId, + cause, + }), + ), + ); + }); + }).pipe( + Effect.tapCause((cause) => + Effect.logWarning("settled subagent evaluation refresh stopped", { cause }), + ), + Effect.retry(subscriptionBackoff), + ); + }, +); + +const make = Effect.gen(function* () { + const evaluations = yield* ModelEvaluations.ModelEvaluations; + const orchestrator = yield* Orchestrator.OrchestratorV2; + + const start: ModelEvaluationSubagentRefresh["Service"]["start"] = () => + forkParked(followSettledSubagentRefreshes({ evaluations, orchestrator })); + + return { start } satisfies ModelEvaluationSubagentRefresh["Service"]; +}); + +export const layer = Layer.effect(ModelEvaluationSubagentRefresh, make); diff --git a/apps/server/src/modelEvaluations/ModelEvaluations.test.ts b/apps/server/src/modelEvaluations/ModelEvaluations.test.ts index 9aa12555fa57c..12eed453cd4ed 100644 --- a/apps/server/src/modelEvaluations/ModelEvaluations.test.ts +++ b/apps/server/src/modelEvaluations/ModelEvaluations.test.ts @@ -3,7 +3,9 @@ import * as NodeServices from "@effect/platform-node/NodeServices"; import { EventId, MessageId, + NodeId, ProjectId, + ProviderDriverKind, ProviderInstanceId, ServerProvider, RunId, @@ -53,12 +55,13 @@ const makeLayer = ( generate: Generate, enabled = true, published: ReadonlyArray = [], + readProviders: Effect.Effect> = Effect.succeed(published), ) => ModelEvaluations.layer.pipe( Layer.provide(Layer.mock(TextGeneration.TextGeneration)({ generateModelEvaluation: generate })), Layer.provide( Layer.mock(ProviderRegistry.ProviderRegistry)({ - getProviders: Effect.succeed(published), + getProviders: readProviders, }), ), Layer.provideMerge( @@ -112,6 +115,7 @@ const seed = Effect.fn("test.seedEvaluationRun")(function* ( readonly subagent?: boolean; readonly existingThread?: OrchestrationV2AppThread; readonly requestedAt?: DateTime.Utc; + readonly notification?: OrchestrationV2ConversationMessage["notification"]; } = {}, ) { const project = options.project ?? projectId; @@ -217,6 +221,9 @@ const seed = Effect.fn("test.seedEvaluationRun")(function* ( : "I am DeepSeek on OpenCode. Added the named export; existing callers remain compatible.", streaming: false, attachments: [], + ...(role === "user" && options.notification !== undefined + ? { notification: options.notification } + : {}), createdAt: role === "user" ? (options.requestedAt ?? at) @@ -345,63 +352,94 @@ it.effect( }, ); -it.effect.each(["provider-error", "unsupported-citation", "abstention", "missing-reply"] as const)( - "keeps %s separate from a low task score", - (kind) => - Effect.gen(function* () { - yield* seed({ missingReply: kind === "missing-reply" }); - const service = yield* ModelEvaluations.ModelEvaluations; - yield* service.evaluateRun(input); - const report = yield* service.list(scope); - const record = report.records[0]!; - assert.equal( - record.status, - kind === "missing-reply" - ? "skipped" - : kind === "abstention" - ? "insufficient_evidence" - : "failed", - ); - assert.equal( - report.guidance.reduce((sum, group) => sum + group.sampleCount, 0), - 0, - ); - if (kind !== "abstention") assert.isNull(record.verdict); - }).pipe( - Effect.provide( - makeLayer((request) => { - if (kind === "provider-error") - return Effect.fail( - new TextGenerationError({ - operation: "generateModelEvaluation", - detail: "Do not persist this provider payload.", - }), - ); - const output = verdict(request.packet); - if (kind === "unsupported-citation") - return Effect.succeed({ - ...output, - rationale: { text: "Unfounded claim", citations: ["E999"] }, - }); - if (kind === "abstention") - return Effect.succeed({ - ...output, - outcome: "insufficient_evidence", - confidence: "low", - scores: { - taskCompletion: null, - correctness: null, - instructionFollowing: null, - verification: null, - }, - strengths: [], - weaknesses: [], - promptAdvice: [], - }); - return Effect.succeed(output); - }), - ), +it.effect.each([ + "provider-error", + "provider-stderr", + "provider-unavailable", + "unsupported-citation", + "abstention", + "missing-reply", +] as const)("keeps %s separate from a low task score", (kind) => + Effect.gen(function* () { + yield* seed({ missingReply: kind === "missing-reply" }); + const service = yield* ModelEvaluations.ModelEvaluations; + yield* service.evaluateRun(input); + const report = yield* service.list(scope); + const record = report.records[0]!; + assert.equal( + record.status, + kind === "missing-reply" + ? "skipped" + : kind === "abstention" + ? "insufficient_evidence" + : "failed", + ); + assert.equal( + report.guidance.reduce((sum, group) => sum + group.sampleCount, 0), + 0, + ); + if (kind !== "abstention") assert.isNull(record.verdict); + if ( + kind === "provider-error" || + kind === "provider-stderr" || + kind === "provider-unavailable" + ) { + assert.include(record.reason ?? "", "TextGenerationError"); + assert.notInclude(record.reason ?? "", "Codex CLI request timed out"); + assert.notInclude(record.reason ?? "", "Claude CLI command failed"); + assert.notInclude(record.reason ?? "", "TAIL_SECRET"); + assert.notInclude(record.reason ?? "", "sk-live-SECRET"); + assert.notInclude(record.reason ?? "", "FULL_MODEL_RESPONSE"); + assert.notInclude(record.reason ?? "", "x".repeat(200)); + } + if (kind === "provider-error") assert.match(record.reason ?? "", /timed out/); + if (kind === "provider-stderr") assert.match(record.reason ?? "", /provider command failed/); + if (kind === "provider-unavailable") assert.match(record.reason ?? "", /provider unavailable/); + }).pipe( + Effect.provide( + makeLayer((request) => { + if ( + kind === "provider-error" || + kind === "provider-stderr" || + kind === "provider-unavailable" + ) + return Effect.fail( + new TextGenerationError({ + operation: "generateModelEvaluation", + detail: + kind === "provider-stderr" + ? "Claude CLI command failed: Error: leaked sk-live-SECRET from provider stderr" + : kind === "provider-unavailable" + ? "The selected evaluator is unavailable. Choose an enabled, installed, authenticated provider that supports blind evaluation." + : `Codex CLI request timed out.${"x".repeat(500)}TAIL_SECRET`, + cause: "FULL_MODEL_RESPONSE", + }), + ); + const output = verdict(request.packet); + if (kind === "unsupported-citation") + return Effect.succeed({ + ...output, + rationale: { text: "Unfounded claim", citations: ["E999"] }, + }); + if (kind === "abstention") + return Effect.succeed({ + ...output, + outcome: "insufficient_evidence", + confidence: "low", + scores: { + taskCompletion: null, + correctness: null, + instructionFollowing: null, + verification: null, + }, + strengths: [], + weaknesses: [], + promptAdvice: [], + }); + return Effect.succeed(output); + }), ), + ), ); it.effect.each(["clear", "disable", "edit", "move"] as const)( @@ -444,6 +482,11 @@ it.effect.each(["clear", "disable", "edit", "move"] as const)( yield* (yield* SqlClient.SqlClient)`SELECT run_id FROM model_evaluations`, [], ); + assert.deepEqual( + yield* (yield* SqlClient.SqlClient)`SELECT effect_id FROM orchestration_v2_effect_outbox + WHERE effect_id LIKE ${`effect:model-evaluation.generate:${runId}:subagents:%`}`, + [], + ); if (action === "clear") { yield* service.evaluateRun(input); assert.deepEqual((yield* service.list(scope)).records, []); @@ -520,15 +563,38 @@ it.effect( ); it.effect( - "keeps model options and judges separate, counts observed scores, and expires old guidance", + "pools latency and capacity options, and keeps behavior, effort, judges, scope, and observed scores separate", () => Effect.gen(function* () { const service = yield* ModelEvaluations.ModelEvaluations; const settings = yield* ServerSettings.ServerSettingsService; - for (let index = 0; index < 8; index++) { + const cases: ReadonlyArray<{ + readonly options: NonNullable; + readonly subagent?: boolean; + readonly switchJudge?: boolean; + }> = [ + { options: [] }, + { options: [{ id: "fastMode", value: true }] }, + { options: [{ id: "fastMode", value: false }] }, + { options: [{ id: "serviceTier", value: "priority" }] }, + { options: [{ id: "contextWindow", value: "1m" }] }, + { options: [{ id: "ultracode", value: true }] }, + { options: [{ id: "effort", value: "high" }] }, + { options: [{ id: "effort", value: "low" }] }, + { options: [{ id: "reasoningEffort", value: "high" }] }, + { options: [{ id: "reasoning_effort", value: "medium" }] }, + { options: [{ id: "thinking", value: true }] }, + { options: [{ id: "thinking", value: false }] }, + { options: [{ id: "thinking_level", value: "high" }] }, + { options: [{ id: "agent", value: "plan" }] }, + { options: [{ id: "mode", value: "architect" }] }, + { options: [], switchJudge: true }, + { options: [], subagent: true }, + ]; + for (const [index, entry] of cases.entries()) { const id = RunId.make(`group-run-${index}`); const thread = ThreadId.make(`group-thread-${index}`); - if (index === 6) + if (entry.switchJudge) yield* settings.updateSettings({ modelEvaluationModelSelection: { instanceId: ProviderInstanceId.make("codex"), @@ -538,25 +604,36 @@ it.effect( yield* seed({ thread, run: id, - subagent: index === 7, - model: { - ...modelSelection, - options: index === 5 ? [{ id: "effort", value: "high" }] : [], - }, + ...(entry.subagent ? { subagent: true } : {}), + model: { ...modelSelection, options: entry.options }, }); yield* service.evaluateRun({ threadId: thread, runId: id, runOutcome: "completed" }); } const report = yield* service.list(scope); - assert.equal(report.guidance.length, 4); - const learned = report.guidance.find((group) => group.sampleCount === 5)!; + const groupsWith = (id: string) => + report.guidance.filter((group) => + (group.modelSelection.options ?? []).some((option) => option.id === id), + ); + assert.equal(report.guidance.length, 12); + const learned = report.guidance.find((group) => group.sampleCount === 6)!; + assert.deepEqual(learned.modelSelection, modelSelection); assert.equal(learned.confidence, "observed"); assert.equal(learned.meanScores.taskCompletion, 3); - assert.equal(learned.scoreCounts.taskCompletion, 5); + assert.equal(learned.scoreCounts.taskCompletion, 6); assert.equal(learned.scoreCounts.verification, 0); assert.equal(learned.strengths.length, 1); + assert.equal(learned.scope, "turn"); + assert.equal(groupsWith("effort").length, 2); + assert.equal(groupsWith("reasoningEffort").length, 1); + assert.equal(groupsWith("reasoning_effort").length, 1); + assert.equal(groupsWith("thinking").length, 2); + assert.equal(groupsWith("thinking_level").length, 1); + assert.equal(groupsWith("agent").length, 1); + assert.equal(groupsWith("mode").length, 1); + assert.equal(report.guidance.filter((group) => group.scope === "subagent").length, 1); yield* settings.updateSettings({ enableModelEvaluations: false }); assert.deepEqual(yield* service.guidance(scope), []); - assert.equal((yield* service.list(scope)).records.length, 8); + assert.equal((yield* service.list(scope)).records.length, cases.length); yield* TestClock.adjust("91 days"); assert.deepEqual((yield* service.list(scope)).guidance, []); }).pipe(Effect.provide(makeLayer((request) => Effect.succeed(verdict(request.packet))))), @@ -806,3 +883,380 @@ it.effect( ); }, ); + +it.effect("ranks scored guidance ahead of newer single samples and drops unscored groups", () => { + let calls = 0; + return Effect.gen(function* () { + const service = yield* ModelEvaluations.ModelEvaluations; + const rich = { instanceId, model: "rich-model" }; + for (let index = 0; index < 5; index++) { + const thread = ThreadId.make(`rich-thread-${index}`); + const id = RunId.make(`rich-run-${index}`); + yield* seed({ thread, run: id, model: rich }); + yield* service.evaluateRun({ threadId: thread, runId: id, runOutcome: "completed" }); + yield* TestClock.adjust("1 second"); + } + for (let index = 0; index < 20; index++) { + const thread = ThreadId.make(`thin-thread-${index}`); + const id = RunId.make(`thin-run-${index}`); + yield* seed({ + thread, + run: id, + model: { instanceId, model: `thin-model-${index}` }, + }); + yield* service.evaluateRun({ threadId: thread, runId: id, runOutcome: "completed" }); + yield* TestClock.adjust("1 second"); + } + const emptyRun = RunId.make("empty-run"); + yield* seed({ + thread: ThreadId.make("empty-thread"), + run: emptyRun, + model: { instanceId, model: "empty-model" }, + }); + yield* service.evaluateRun({ + threadId: ThreadId.make("empty-thread"), + runId: emptyRun, + runOutcome: "completed", + }); + const report = yield* service.list(scope); + assert.equal( + report.records.find((record) => record.runId === emptyRun)?.status, + "insufficient_evidence", + ); + assert.equal(report.guidance[0]?.modelSelection.model, "rich-model"); + assert.equal(report.guidance[0]?.sampleCount, 5); + assert.equal(report.guidance[1]?.modelSelection.model, "thin-model-19"); + assert.equal(report.guidance.length, 20); + assert.isFalse(report.guidance.some((group) => group.sampleCount === 0)); + assert.isFalse(report.guidance.some((group) => group.modelSelection.model === "empty-model")); + assert.isFalse(report.guidance.some((group) => group.modelSelection.model === "thin-model-0")); + }).pipe( + Effect.provide( + makeLayer((request) => { + calls += 1; + if (calls < 26) return Effect.succeed(verdict(request.packet)); + const output = verdict(request.packet); + return Effect.succeed({ + ...output, + outcome: "insufficient_evidence", + confidence: "low", + scores: { + taskCompletion: null, + correctness: null, + instructionFollowing: null, + verification: null, + }, + strengths: [], + weaknesses: [], + promptAdvice: [], + }); + }), + ), + ); +}); + +it.effect("leaves an already scored automated wake out of guidance", () => + Effect.gen(function* () { + yield* seed(); + const service = yield* ModelEvaluations.ModelEvaluations; + yield* service.evaluateRun(input); + assert.equal((yield* service.list(scope)).guidance[0]?.sampleCount, 1); + const sql = yield* SqlClient.SqlClient; + yield* sql` + UPDATE orchestration_v2_projection_messages + SET payload_json = json_set( + payload_json, + '$.notification', + json('{"source":{"kind":"command"},"outcome":"completed","summary":"Background work finished"}') + ) + WHERE message_id = ${`${runId}:user`} + `; + const report = yield* service.list(scope); + assert.deepEqual(report.guidance, []); + assert.deepEqual(report.records, []); + }).pipe(Effect.provide(makeLayer((request) => Effect.succeed(verdict(request.packet))))), +); + +it.effect.each(["command", "monitor", "group", "delegated_task"] as const)( + "records a %s wake as skipped and does not judge it", + (kind) => { + const calls: string[] = []; + return Effect.gen(function* () { + yield* seed({ + notification: { + source: + kind === "delegated_task" ? { kind, taskIds: [NodeId.make("wake-task")] } : { kind }, + outcome: "completed", + summary: "Background work finished", + }, + }); + const service = yield* ModelEvaluations.ModelEvaluations; + yield* service.evaluateRun(input); + assert.deepEqual(calls, []); + const record = (yield* service.list(scope)).records[0]!; + assert.equal(record.status, "skipped"); + assert.match(record.reason ?? "", /automated wake/); + assert.deepEqual((yield* service.list(scope)).guidance, []); + }).pipe( + Effect.provide( + makeLayer((request) => { + calls.push("judge"); + return Effect.succeed(verdict(request.packet)); + }), + ), + ); + }, +); + +const childDriver = ProviderDriverKind.make("claude"); + +function delegatedChild( + id: string, + status: OrchestrationV2TurnItem["status"], + result: string | null, + ordinal: number, +): Extract { + return { + id: TurnItemId.make(id), + threadId, + runId, + nodeId: null, + providerThreadId: null, + providerTurnId: null, + nativeItemRef: null, + parentItemId: null, + ordinal, + status, + title: "Delegated child", + startedAt: at, + completedAt: status === "pending" || status === "running" || status === "waiting" ? null : at, + updatedAt: at, + type: "subagent", + subagentId: NodeId.make(id), + origin: "app_owned", + driver: childDriver, + providerInstanceId: instanceId, + childThreadId: null, + prompt: "Check the export.", + result, + }; +} + +const recordChild = ( + id: string, + status: OrchestrationV2TurnItem["status"], + result: string | null, + ordinal: number, +) => + persist({ + id: EventId.make(`child:${id}:${status}:${ordinal}`), + type: "turn-item.updated", + threadId, + runId, + occurredAt: at, + payload: delegatedChild(id, status, result, ordinal), + }); + +const packetsWith = (calls: ReadonlyArray[0]>, token: string) => + calls.filter((call) => JSON.stringify(call.packet).includes(token)); + +it.effect("scores a delegated child once that child settles", () => { + const calls: Array[0]> = []; + return Effect.gen(function* () { + yield* seed(); + yield* recordChild("running-child", "running", null, 2); + const service = yield* ModelEvaluations.ModelEvaluations; + yield* service.evaluateRun(input); + assert.equal(packetsWith(calls, "child-result-token").length, 0); + yield* recordChild("running-child", "completed", "child-result-token", 2); + assert.deepEqual((yield* service.list(scope)).records, []); + yield* service.evaluateRun(input); + assert.equal(packetsWith(calls, "child-result-token").length, 1); + const report = yield* service.list(scope); + assert.equal(report.records.length, 1); + assert.equal(report.records[0]?.status, "scored"); + assert.equal(report.guidance[0]?.sampleCount, 1); + yield* service.evaluateRun(input); + assert.equal(packetsWith(calls, "child-result-token").length, 1); + }).pipe( + Effect.provide( + makeLayer((request) => { + calls.push(request); + return Effect.succeed(verdict(request.packet)); + }), + ), + ); +}); + +it.effect("waits to rescore until every delegated child has settled", () => { + const calls: Array[0]> = []; + return Effect.gen(function* () { + yield* seed(); + yield* recordChild("child-a", "running", null, 2); + yield* recordChild("child-b", "running", null, 3); + const service = yield* ModelEvaluations.ModelEvaluations; + yield* service.evaluateRun(input); + yield* recordChild("child-a", "completed", "alpha-result", 2); + yield* service.evaluateRun(input); + assert.equal(packetsWith(calls, "alpha-result").length, 0); + assert.deepEqual((yield* service.list(scope)).records, []); + yield* recordChild("child-b", "completed", "beta-result", 3); + yield* service.evaluateRun(input); + assert.equal(packetsWith(calls, "alpha-result").length, 1); + assert.equal(packetsWith(calls, "beta-result").length, 1); + assert.equal((yield* service.list(scope)).guidance[0]?.sampleCount, 1); + }).pipe( + Effect.provide( + makeLayer((request) => { + calls.push(request); + return Effect.succeed(verdict(request.packet)); + }), + ), + ); +}); + +it.effect("does not rescore a settled child when the exchange itself changed", () => { + const calls: Array[0]> = []; + return Effect.gen(function* () { + const seeded = yield* seed(); + yield* recordChild("edited-child", "running", null, 2); + const service = yield* ModelEvaluations.ModelEvaluations; + yield* service.evaluateRun(input); + yield* recordChild("edited-child", "completed", "child-edit-token", 2); + yield* persist({ + id: EventId.make("edited-final-answer"), + type: "message.updated", + threadId, + runId, + occurredAt: at, + payload: { ...seeded.messages[1]!, text: "The export was removed after review." }, + }); + yield* service.evaluateRun(input); + assert.equal(packetsWith(calls, "child-edit-token").length, 0); + assert.deepEqual((yield* service.list(scope)).records, []); + }).pipe( + Effect.provide( + makeLayer((request) => { + calls.push(request); + return Effect.succeed(verdict(request.packet)); + }), + ), + ); +}); + +it.effect("scores a turn whose delegated child already ended cancelled", () => { + const calls: Array[0]> = []; + return Effect.gen(function* () { + yield* seed(); + yield* recordChild("cancelled-child", "cancelled", null, 2); + const service = yield* ModelEvaluations.ModelEvaluations; + yield* service.evaluateRun(input); + assert.equal(calls.length, 1); + assert.equal((yield* service.list(scope)).guidance[0]?.sampleCount, 1); + }).pipe( + Effect.provide( + makeLayer((request) => { + calls.push(request); + return Effect.succeed(verdict(request.packet)); + }), + ), + ); +}); + +it.effect("enqueues one refresh after every delegated child settles", () => + Effect.gen(function* () { + yield* seed(); + yield* recordChild("queued-a", "running", null, 2); + yield* recordChild("queued-b", "running", null, 3); + const service = yield* ModelEvaluations.ModelEvaluations; + const sql = yield* SqlClient.SqlClient; + const refreshIds = () => + sql<{ effect_id: string }>` + SELECT effect_id FROM orchestration_v2_effect_outbox + WHERE effect_id LIKE ${`effect:model-evaluation.generate:${runId}:subagents:%`} + ORDER BY effect_id + `; + yield* service.evaluateRun(input); + yield* recordChild("queued-a", "completed", "queued-a-token", 2); + yield* service.enqueueSettledSubagentRefreshes({ runId }); + assert.deepEqual(yield* refreshIds(), []); + yield* recordChild("queued-b", "completed", "queued-b-token", 3); + yield* service.enqueueSettledSubagentRefreshes(); + yield* service.enqueueSettledSubagentRefreshes({ runId }); + const ids = yield* refreshIds(); + assert.equal(ids.length, 1); + assert.match(ids[0]!.effect_id, /:subagents:\d+$/); + }).pipe(Effect.provide(makeLayer((request) => Effect.succeed(verdict(request.packet))))), +); + +it.effect.each(["completed", "cancelled", "idle"] as const)( + "scores a turn whose child ends %s before the evaluation is stored", + (settledStatus) => + Effect.gen(function* () { + const reached = yield* Deferred.make(); + const release = yield* Deferred.make(); + const calls: Array[0]> = []; + const readProviders = Effect.gen(function* () { + yield* Deferred.succeed(reached, undefined); + yield* Deferred.await(release); + return []; + }); + return yield* Effect.gen(function* () { + yield* seed(); + yield* recordChild("racing-child", "running", null, 2); + const service = yield* ModelEvaluations.ModelEvaluations; + const sql = yield* SqlClient.SqlClient; + const fiber = yield* Effect.forkChild(service.evaluateRun(input)); + yield* Deferred.await(reached); + yield* recordChild( + "racing-child", + settledStatus, + settledStatus === "completed" ? "settled-result-token" : null, + 2, + ); + yield* Deferred.succeed(release, undefined); + yield* Fiber.join(fiber); + const ids = yield* sql<{ effect_id: string }>` + SELECT effect_id FROM orchestration_v2_effect_outbox + WHERE effect_id LIKE ${`effect:model-evaluation.generate:${runId}:subagents:%`} + ORDER BY effect_id + `; + assert.equal(calls.length, 0); + assert.equal(ids.length, 1); + yield* service.evaluateRun(input); + assert.equal(calls.length, 1); + if (settledStatus === "completed") + assert.equal(packetsWith(calls, "settled-result-token").length, 1); + assert.equal((yield* service.list(scope)).guidance[0]?.sampleCount, 1); + }).pipe( + Effect.provide( + makeLayer( + (request) => { + calls.push(request); + return Effect.succeed(verdict(request.packet)); + }, + true, + [], + readProviders, + ), + ), + ); + }), +); + +it.effect("checks every revised source message through the message-revision index", () => + Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + const plan = yield* sql<{ detail: string }>`EXPLAIN QUERY PLAN + SELECT evaluation.run_id FROM model_evaluations AS evaluation + WHERE ${ModelEvaluations.sourceMessageRevised(sql)}`; + assert.isTrue( + plan.some((row) => + row.detail.includes( + "model_evaluation_message_revision (stream_id=? AND =? AND sequence>?)", + ), + ), + JSON.stringify(plan), + ); + }).pipe(Effect.provide(makeLayer((request) => Effect.succeed(verdict(request.packet))))), +); diff --git a/apps/server/src/modelEvaluations/ModelEvaluations.ts b/apps/server/src/modelEvaluations/ModelEvaluations.ts index 14576aa3c6a39..7b064cb1ca802 100644 --- a/apps/server/src/modelEvaluations/ModelEvaluations.ts +++ b/apps/server/src/modelEvaluations/ModelEvaluations.ts @@ -4,15 +4,17 @@ import { ModelEvaluationError, ModelEvaluationRecord, ModelSelection, + RunId, + ThreadId, type ModelEvaluationGuidance, type ModelEvaluationReport, + type ModelEvaluationRunOutcome, type ProjectId, - type RunId, - type ThreadId, } from "@t3tools/contracts"; import { MODEL_EVALUATION_RUBRIC_VERSION, buildModelEvaluationEvidence, + modelEvaluationAwaitsSubagents, validateModelEvaluationVerdict, } from "@t3tools/provider-core/server/modelEvaluation"; import * as Context from "effect/Context"; @@ -51,14 +53,85 @@ const encodeIds = Schema.encodeSync(Schema.fromJsonString(Schema.Array(MessageId const decodeSelection = Schema.decodeUnknownEffect(Schema.fromJsonString(ModelSelection)); const isModelEvaluationError = Schema.is(ModelEvaluationError); +// These change latency, billing, or capacity, not output quality. +const QUALITY_NEUTRAL_OPTION_IDS = new Set([ + "fastMode", + "serviceTier", + "contextWindow", + "ultracode", +]); + +function evaluatorFailureCause(detail: string): string { + const text = detail.toLowerCase(); + if (text.includes("timed out")) return "timed out"; + if (text.includes("command failed")) return "provider command failed"; + if ( + text.includes("invalid structured output") || + text.includes("invalid evaluation events") || + text.includes("unexpected output") + ) + return "invalid output"; + if (text.includes("tool activity") || text.includes("tool work")) return "tool activity"; + if ( + /unavailable|not available|not installed|no provider instance|does not support|enoent/.test( + text, + ) + ) + return "provider unavailable"; + return "provider request failed"; +} + +function evaluatorFailureReason(error: { readonly _tag: string; readonly detail: string }) { + return `The evaluator could not complete this evaluation (${error._tag}: ${evaluatorFailureCause(error.detail)}). No model score was recorded.`; +} + +function settledRunOutcome(status: string): ModelEvaluationRunOutcome | undefined { + switch (status) { + case "completed": + case "failed": + case "interrupted": + case "cancelled": + return status; + default: + return undefined; + } +} + +function qualitySelection(selection: ModelSelection): ModelSelection { + const options = (selection.options ?? []) + .filter((option) => !QUALITY_NEUTRAL_OPTION_IDS.has(option.id)) + .toSorted((left, right) => left.id.localeCompare(right.id)); + const base = { instanceId: selection.instanceId, model: selection.model }; + return options.length === 0 ? base : { ...base, options }; +} + function selectionKey(selection: ModelSelection) { - return JSON.stringify({ - instanceId: selection.instanceId, - model: selection.model, - options: (selection.options ?? []).toSorted((a, b) => a.id.localeCompare(b.id)), - }); + return JSON.stringify(qualitySelection(selection)); } +export const sourceMessageRevised = (sql: SqlClient.SqlClient) => sql`EXISTS ( + SELECT 1 FROM json_each(evaluation.source_message_ids) AS message + CROSS JOIN orchestration_events AS source INDEXED BY model_evaluation_message_revision + ON json_extract(source.payload_json, '$.id') = +message.value + WHERE source.application_event_version = 2 AND source.aggregate_kind = 'thread' + AND source.stream_id = evaluation.thread_id AND source.event_type = 'message.updated' + AND source.sequence > evaluation.source_sequence +)`; + +const nonSubagentSourceRevised = (sql: SqlClient.SqlClient) => sql`EXISTS ( + SELECT 1 FROM orchestration_events AS source INDEXED BY model_evaluation_source_revision + WHERE source.application_event_version = 2 AND source.aggregate_kind = 'thread' + AND source.stream_id = evaluation.thread_id AND source.sequence > evaluation.source_sequence + AND source.event_type IN ('message.updated', 'turn-item.updated') + AND json_extract(source.payload_json, '$.runId') = +evaluation.run_id + AND ( + source.event_type = 'message.updated' + OR json_extract(source.payload_json, '$.type') IN ( + 'user_message', 'assistant_message', 'command_execution', 'file_change', 'dynamic_tool' + ) + ) +)`; + function summarize( records: ReadonlyArray, ): ReadonlyArray { @@ -77,73 +150,85 @@ function summarize( group.push(record); groups.set(key, group); } - return [...groups.values()].slice(0, GUIDANCE_LIMIT).map((group) => { - const first = group[0]!; - const scored = group.filter((record) => record.status === "scored"); - const meanScores = { - taskCompletion: null, - correctness: null, - instructionFollowing: null, - verification: null, - } as ModelEvaluationGuidance["meanScores"]; - const scoreCounts = { - taskCompletion: 0, - correctness: 0, - instructionFollowing: 0, - verification: 0, - }; - for (const dimension of DIMENSIONS) { - const values = scored.flatMap((record) => record.verdict?.scores[dimension] ?? []); - scoreCounts[dimension] = values.length; - Object.assign(meanScores, { - [dimension]: - values.length === 0 - ? null - : values.reduce((sum, value) => sum + value, 0) / values.length, - }); - } - const prompts = scored.map((record) => record.promptChars).toSorted((a, b) => a - b); - const observations = (field: "strengths" | "weaknesses" | "promptAdvice") => - [ - ...new Set( - scored.flatMap( - (record) => - record.verdict?.[field].map((observation) => - observation.text.replace(/\s+/g, " ").trim().slice(0, 240), - ) ?? [], + return [...groups.values()] + .map((group) => { + const first = group[0]!; + const scored = group.filter((record) => record.status === "scored"); + const meanScores = { + taskCompletion: null, + correctness: null, + instructionFollowing: null, + verification: null, + } as ModelEvaluationGuidance["meanScores"]; + const scoreCounts = { + taskCompletion: 0, + correctness: 0, + instructionFollowing: 0, + verification: 0, + }; + for (const dimension of DIMENSIONS) { + const values = scored.flatMap((record) => record.verdict?.scores[dimension] ?? []); + scoreCounts[dimension] = values.length; + Object.assign(meanScores, { + [dimension]: + values.length === 0 + ? null + : values.reduce((sum, value) => sum + value, 0) / values.length, + }); + } + const prompts = scored.map((record) => record.promptChars).toSorted((a, b) => a - b); + const observations = (field: "strengths" | "weaknesses" | "promptAdvice") => + [ + ...new Set( + scored.flatMap( + (record) => + record.verdict?.[field].map((observation) => + observation.text.replace(/\s+/g, " ").trim().slice(0, 240), + ) ?? [], + ), ), - ), - ].slice(0, 3); - return { - scope: first.scope, - modelSelection: first.modelSelection, - evaluatorSelection: first.evaluatorSelection, - rubricVersion: first.rubricVersion, - taskCategory: first.verdict!.taskCategory, - sampleCount: scored.length, - insufficientEvidenceCount: group.length - scored.length, - meanScores, - scoreCounts, - confidence: + ].slice(0, 3); + const confidence: ModelEvaluationGuidance["confidence"] = scored.filter((record) => record.verdict?.confidence !== "low").length >= 5 ? "observed" - : "provisional", - promptChars: { - min: prompts[0] ?? 0, - median: - prompts.length === 0 - ? 0 - : ((prompts[Math.floor((prompts.length - 1) / 2)] ?? 0) + - (prompts[Math.floor(prompts.length / 2)] ?? 0)) / - 2, - max: prompts.at(-1) ?? 0, - }, - strengths: observations("strengths"), - weaknesses: observations("weaknesses"), - promptAdvice: observations("promptAdvice"), - latestAt: first.at, - }; - }); + : "provisional"; + return { + scope: first.scope, + modelSelection: qualitySelection(first.modelSelection), + evaluatorSelection: qualitySelection(first.evaluatorSelection), + rubricVersion: first.rubricVersion, + taskCategory: first.verdict!.taskCategory, + sampleCount: scored.length, + insufficientEvidenceCount: group.length - scored.length, + meanScores, + scoreCounts, + confidence, + promptChars: { + min: prompts[0] ?? 0, + median: + prompts.length === 0 + ? 0 + : ((prompts[Math.floor((prompts.length - 1) / 2)] ?? 0) + + (prompts[Math.floor(prompts.length / 2)] ?? 0)) / + 2, + max: prompts.at(-1) ?? 0, + }, + strengths: observations("strengths"), + weaknesses: observations("weaknesses"), + promptAdvice: observations("promptAdvice"), + latestAt: group.reduce( + (latest, record) => (record.at > latest ? record.at : latest), + group[0]!.at, + ), + }; + }) + .filter((group) => group.sampleCount > 0) + .toSorted( + (left, right) => + right.sampleCount - left.sampleCount || + (left.latestAt < right.latestAt ? 1 : left.latestAt > right.latestAt ? -1 : 0), + ) + .slice(0, GUIDANCE_LIMIT); } export class ModelEvaluationPassError extends Schema.TaggedError()( @@ -157,6 +242,9 @@ export class ModelEvaluations extends Context.Service< ModelEvaluations, { readonly enqueueRun: (input: RunInput) => Effect.Effect; + readonly enqueueSettledSubagentRefreshes: (input?: { + readonly runId: RunId; + }) => Effect.Effect; readonly evaluateRun: (input: RunInput) => Effect.Effect; readonly list: (input: { readonly projectId: ProjectId; @@ -292,22 +380,23 @@ const make = Effect.gen(function* () { WHERE evaluation.project_id = ${projectId} AND thread.project_id = ${projectId} AND thread.deleted_at IS NULL AND thread.archived_at IS NULL AND run.status <> 'rolled_back' AND evaluation.evaluated_at >= ${after} + AND ( + json_extract(evaluation.payload_json, '$.status') NOT IN ('scored', 'insufficient_evidence') + OR NOT EXISTS ( + SELECT 1 FROM orchestration_v2_projection_messages AS request + WHERE request.message_id = json_extract(run.payload_json, '$.userMessageId') + AND json_extract(request.payload_json, '$.notification') IS NOT NULL + ) + ) AND NOT EXISTS ( SELECT 1 FROM orchestration_events AS source WHERE source.application_event_version = 2 AND source.aggregate_kind = 'thread' AND source.stream_id = evaluation.thread_id AND source.sequence > evaluation.source_sequence AND source.event_type IN ('message.updated', 'turn-item.updated') - AND json_extract(source.payload_json, '$.runId') = evaluation.run_id + AND json_extract(source.payload_json, '$.runId') = +evaluation.run_id AND (source.event_type = 'message.updated' OR json_extract(source.payload_json, '$.type') IN ('user_message', 'assistant_message', 'command_execution', 'file_change', 'dynamic_tool', 'subagent')) ) - AND NOT EXISTS ( - SELECT 1 FROM json_each(evaluation.source_message_ids) AS message - JOIN orchestration_events AS source - ON json_extract(source.payload_json, '$.id') = message.value - WHERE source.application_event_version = 2 AND source.aggregate_kind = 'thread' - AND source.stream_id = evaluation.thread_id AND source.event_type = 'message.updated' - AND source.sequence > evaluation.source_sequence - ) + AND NOT ${sourceMessageRevised(sql)} AND NOT EXISTS ( SELECT 1 FROM json_each(evaluation.source_message_ids) AS reference LEFT JOIN orchestration_v2_projection_messages AS message ON message.message_id = reference.value @@ -321,6 +410,54 @@ const make = Effect.gen(function* () { `; return yield* Effect.forEach(rows, (row) => decodeRecord(row.payload_json)); }); + const settledSubagentRevisions = Effect.fn("ModelEvaluations.settledSubagentRevisions")( + function* (runId?: RunId) { + const after = DateTime.formatIso(DateTime.subtract(yield* DateTime.now, { days: 90 })); + return yield* sql<{ + thread_id: string; + run_id: string; + run_status: string; + subagent_revision: number | null; + }>` + SELECT candidate.thread_id, candidate.run_id, candidate.run_status, candidate.subagent_revision + FROM ( + SELECT + evaluation.thread_id AS thread_id, + evaluation.run_id AS run_id, + run.status AS run_status, + ( + SELECT MAX(source.sequence) + FROM orchestration_events AS source INDEXED BY model_evaluation_source_revision + WHERE source.application_event_version = 2 AND source.aggregate_kind = 'thread' + AND source.stream_id = evaluation.thread_id AND source.sequence > evaluation.source_sequence + -- Matches the partial index's predicate; INDEXED BY fails without it. + AND source.event_type IN ('message.updated', 'turn-item.updated') + AND source.event_type = 'turn-item.updated' + AND json_extract(source.payload_json, '$.runId') = +evaluation.run_id + AND json_extract(source.payload_json, '$.type') = 'subagent' + ) AS subagent_revision + FROM model_evaluations AS evaluation + JOIN orchestration_v2_projection_threads AS thread ON thread.thread_id = evaluation.thread_id + JOIN orchestration_v2_projection_runs AS run ON run.run_id = evaluation.run_id + WHERE thread.deleted_at IS NULL AND thread.archived_at IS NULL AND run.status <> 'rolled_back' + AND evaluation.evaluated_at >= ${after} + AND ${runId === undefined ? sql`1 = 1` : sql`evaluation.run_id = ${runId}`} + AND NOT ${nonSubagentSourceRevised(sql)} + AND NOT ${sourceMessageRevised(sql)} + AND NOT EXISTS ( + SELECT 1 FROM json_each(evaluation.source_message_ids) AS reference + LEFT JOIN orchestration_v2_projection_messages AS message ON message.message_id = reference.value + LEFT JOIN orchestration_v2_projection_runs AS source_run ON source_run.run_id = message.run_id + WHERE message.message_id IS NULL OR message.thread_id <> evaluation.thread_id + OR source_run.status = 'rolled_back' + OR (source_run.status = 'cancelled' AND json_extract(source_run.payload_json, '$.startedAt') IS NULL) + OR (${discardedRequest}) + ) + ) AS candidate + WHERE candidate.subagent_revision IS NOT NULL + `; + }, + ); const list: ModelEvaluations["Service"]["list"] = Effect.fn("ModelEvaluations.list")( function* ({ projectId }) { @@ -400,19 +537,19 @@ const make = Effect.gen(function* () { const records = source.records; if (records === null) return; const projectId = records.thread.projectId; - const runOutcome = - records.run.status === "completed" || - records.run.status === "failed" || - records.run.status === "interrupted" || - records.run.status === "cancelled" - ? records.run.status - : requestedOutcome; - const settled = ["completed", "failed", "interrupted", "cancelled"].includes( - records.run.status, - ); + const settledOutcome = settledRunOutcome(records.run.status); + const runOutcome = settledOutcome ?? requestedOutcome; + const settled = settledOutcome !== undefined; yield* requireProject(projectId); const previous = yield* sql`SELECT run_id FROM model_evaluations WHERE run_id = ${runId}`; - if (previous.length > 0) return; + const awaitsSubagents = modelEvaluationAwaitsSubagents(records.turnItems, runId); + let replacing = false; + if (previous.length > 0) { + if (awaitsSubagents) return; + const [revision] = yield* settledSubagentRevisions(runId); + if (revision === undefined) return; + replacing = true; + } const generation = yield* reset(projectId); if (DateTime.formatIso(records.run.requestedAt) <= generation.reset_at) return; const evaluatorSelection = @@ -450,17 +587,23 @@ const make = Effect.gen(function* () { runOutcome, }); const evidence = build(records); + const automatedWake = records.messages.some( + (message) => message.id === records.run.userMessageId && message.notification !== undefined, + ); const attributed = records.run.providerInstanceId === records.run.modelSelection.instanceId && (yield* attributionKnown(threadId, runId, records.run.modelSelection)); let status: ModelEvaluationRecord["status"] = "skipped"; - let reason: string | null = "The run has no complete request and final response to evaluate."; + let reason: string | null = automatedWake + ? "The request was an automated wake, not a user prompt. No model score was recorded." + : "The run has no complete request and final response to evaluate."; let verdict: ModelEvaluationRecord["verdict"] = null; - if (!attributed) + if (!automatedWake && !attributed) reason = "The executed model could not be attributed to one stable model selection."; - if (!settled) + if (!automatedWake && !settled) reason = "The run could not finish checkpoint finalization. No model score was recorded."; - if (evidence !== null && attributed && settled) { + if (!automatedWake && awaitsSubagents) reason = "Delegated work from this run is still open."; + if (!automatedWake && evidence !== null && attributed && settled && !awaitsSubagents) { const generated = yield* Effect.gen(function* () { const cwd = yield* fs.makeTempDirectoryScoped({ prefix: "t3-model-evaluation-" }); return yield* textGeneration.generateModelEvaluation({ @@ -470,22 +613,26 @@ const make = Effect.gen(function* () { }); }).pipe( Effect.scoped, - Effect.catchTags({ TextGenerationError: () => Effect.succeed(null) }), + Effect.map((verdict) => ({ verdict, failure: null })), + Effect.catchTags({ + TextGenerationError: (error) => + Effect.succeed({ verdict: null, failure: evaluatorFailureReason(error) }), + }), ); - if (generated === null) { + if (generated.failure !== null) { status = "failed"; - reason = "The evaluator could not complete this evaluation. No model score was recorded."; - } else if (!validateModelEvaluationVerdict(generated, evidence.packet)) { + reason = generated.failure; + } else if (!validateModelEvaluationVerdict(generated.verdict, evidence.packet)) { status = "failed"; reason = "The evaluator returned unsupported scores or evidence references. No model score was recorded."; } else { - verdict = generated; + verdict = generated.verdict; status = verdict.outcome; reason = null; } } - yield* settings.withSettingsSnapshot((current) => + const retry = yield* settings.withSettingsSnapshot((current) => sql.withTransaction( Effect.gen(function* () { if ( @@ -494,9 +641,9 @@ const make = Effect.gen(function* () { current.modelEvaluationModelSelection ?? current.textGenerationModelSelection, ) !== selectionKey(evaluatorSelection) ) - return; + return false; const latestGeneration = yield* reset(projectId); - if (latestGeneration.generation !== generation.generation) return; + if (latestGeneration.generation !== generation.generation) return false; const latest = yield* loadSource(threadId, runId); if ( latest === null || @@ -504,13 +651,37 @@ const make = Effect.gen(function* () { latest.run.status !== records.run.status || selectionKey(latest.run.modelSelection) !== selectionKey(records.run.modelSelection) ) - return; + return false; const latestEvidence = build(latest); if ( encodePacket(latestEvidence?.packet ?? null) !== - encodePacket(evidence?.packet ?? null) - ) - return; + encodePacket(evidence?.packet ?? null) || + modelEvaluationAwaitsSubagents(latest.turnItems, runId) !== awaitsSubagents + ) { + if ( + encodeIds(latestEvidence?.sourceMessageIds ?? []) !== + encodeIds(evidence?.sourceMessageIds ?? []) + ) + return false; + const [changes] = yield* sql<{ revised: number }>` + WITH evaluation(thread_id, run_id, source_sequence, source_message_ids) AS ( + VALUES (${threadId}, ${runId}, ${source.sourceSequence}, ${encodeIds(evidence?.sourceMessageIds ?? [])}) + ) + SELECT ${nonSubagentSourceRevised(sql)} OR ${sourceMessageRevised(sql)} AS revised + FROM evaluation`; + if (changes!.revised !== 0) return false; + const revision = yield* sequence(threadId); + const effects = modelEvaluationEffects({ + settings: current, + threadId, + runId, + runOutcome, + subagentRevision: revision, + }); + if (effects.length === 0) return false; + yield* outbox.enqueue(effects); + return true; + } yield* requireProject(projectId); const record: ModelEvaluationRecord = { projectId, @@ -530,10 +701,19 @@ const make = Effect.gen(function* () { }; yield* sql`INSERT INTO model_evaluations (run_id, project_id, thread_id, evaluated_at, source_sequence, source_message_ids, payload_json) VALUES (${runId}, ${projectId}, ${threadId}, ${record.at}, ${source.sourceSequence}, ${encodeIds(evidence?.sourceMessageIds ?? [])}, ${encodeRecord(record)}) - ON CONFLICT (run_id) DO NOTHING`; + ON CONFLICT (run_id) DO UPDATE SET + project_id = excluded.project_id, + thread_id = excluded.thread_id, + evaluated_at = excluded.evaluated_at, + source_sequence = excluded.source_sequence, + source_message_ids = excluded.source_message_ids, + payload_json = excluded.payload_json + WHERE ${replacing ? sql`1 = 1` : sql`0 = 1`}`; + return false; }), ), ); + if (retry) yield* outbox.notifyAvailable(1); }, (effect, { runId }) => effect.pipe( @@ -541,7 +721,65 @@ const make = Effect.gen(function* () { Effect.mapError((cause) => new ModelEvaluationPassError({ runId, cause })), ), ); - return ModelEvaluations.of({ enqueueRun, evaluateRun, list, clear, guidance }); + const enqueueSettledSubagentRefreshes: ModelEvaluations["Service"]["enqueueSettledSubagentRefreshes"] = + Effect.fn("ModelEvaluations.enqueueSettledSubagentRefreshes")( + function* (input) { + const current = yield* settings.getSettings; + if (!current.enableModelEvaluations) return; + const candidates = yield* settledSubagentRevisions(input?.runId); + const effects = yield* Effect.forEach(candidates, (candidate) => + Effect.gen(function* () { + const runOutcome = settledRunOutcome(candidate.run_status); + if (runOutcome === undefined || candidate.subagent_revision === null) return []; + const runId = RunId.make(candidate.run_id); + const loaded = yield* projections + .getThreadRecords(ThreadId.make(candidate.thread_id), ["turnItems"], { + turnItemRunIds: [runId], + turnItemTypes: ["subagent"], + }) + .pipe( + Effect.catchCause((cause) => + Effect.logWarning( + "Could not read subagent items for a model evaluation refresh", + { runId, cause }, + ).pipe(Effect.as(null)), + ), + ); + if (loaded === null || modelEvaluationAwaitsSubagents(loaded.turnItems, runId)) + return []; + return modelEvaluationEffects({ + settings: current, + threadId: ThreadId.make(candidate.thread_id), + runId, + runOutcome, + subagentRevision: candidate.subagent_revision, + }); + }), + ); + const pending = effects.flat(); + if (pending.length === 0) return; + yield* outbox.enqueue(pending); + yield* outbox.notifyAvailable(pending.length); + }, + (effect, input) => + effect.pipe( + Effect.mapError( + (cause) => + new ModelEvaluationPassError({ + runId: input?.runId ?? "subagent-refresh", + cause, + }), + ), + ), + ); + return ModelEvaluations.of({ + enqueueRun, + enqueueSettledSubagentRefreshes, + evaluateRun, + list, + clear, + guidance, + }); }); export const layer = Layer.effect(ModelEvaluations, make); diff --git a/apps/server/src/modelEvaluations/modelEvaluationSchedule.ts b/apps/server/src/modelEvaluations/modelEvaluationSchedule.ts index 675f560a16ce4..353d246965e47 100644 --- a/apps/server/src/modelEvaluations/modelEvaluationSchedule.ts +++ b/apps/server/src/modelEvaluations/modelEvaluationSchedule.ts @@ -12,12 +12,17 @@ export function modelEvaluationEffects(input: { readonly threadId: ThreadId; readonly runId: RunId; readonly runOutcome: ModelEvaluationRunOutcome; + readonly subagentRevision?: number; }): ReadonlyArray { if (!input.settings.enableModelEvaluations) return []; + const id = + input.subagentRevision === undefined + ? `effect:model-evaluation.generate:${input.runId}` + : `effect:model-evaluation.generate:${input.runId}:subagents:${input.subagentRevision}`; return [ { - id: `effect:model-evaluation.generate:${input.runId}`, - commandId: CommandId.make(`command:effect:model-evaluation.generate:${input.runId}`), + id, + commandId: CommandId.make(`command:${id}`), threadId: input.threadId, request: { type: "model-evaluation.generate", diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts index 1bc1265d18c61..7b5edfd711463 100644 --- a/apps/server/src/server.ts +++ b/apps/server/src/server.ts @@ -6,6 +6,7 @@ import * as HolographicMemory from "./project/knowledge/HolographicMemory.ts"; import * as ProjectKnowledge from "./project/knowledge/ProjectKnowledge.ts"; import * as AssistedLearning from "./project/knowledge/AssistedLearning.ts"; import * as ConversationSummaries from "./project/conversationSummaries/ConversationSummaries.ts"; +import * as ModelEvaluationSubagentRefresh from "./modelEvaluations/ModelEvaluationSubagentRefresh.ts"; import * as ModelEvaluations from "./modelEvaluations/ModelEvaluations.ts"; import * as ExternalHistory from "./project/externalHistory/ExternalHistory.ts"; import * as CodeIndexReactor from "./project/knowledge/CodeIndexReactor.ts"; @@ -748,6 +749,12 @@ const layerRuntimeCoreDependenciesBase = Layer.mergeAll( yield* service.start(); }), ).pipe(Layer.provide(DelegatedTaskQuestionReactor.layer), Layer.provide(ProjectionStoreV2.layer)), + Layer.effectDiscard( + Effect.gen(function* () { + const service = yield* ModelEvaluationSubagentRefresh.ModelEvaluationSubagentRefresh; + yield* service.start(); + }), + ).pipe(Layer.provide(ModelEvaluationSubagentRefresh.layer)), Layer.effectDiscard( Effect.gen(function* () { const service = yield* GroupReactor.GroupReactor; diff --git a/docs/user/model-evaluations.md b/docs/user/model-evaluations.md index 319c350f7d512..86b96ad44ed65 100644 --- a/docs/user/model-evaluations.md +++ b/docs/user/model-evaluations.md @@ -18,29 +18,35 @@ which keeps account authentication while disabling custom instructions and exten After a task ends, T3 Code gives the judge the request, relevant conversation context, and available outcome evidence with model and provider labels removed. The same process covers subagent threads -run through T3's orchestration. Model names mentioned inside free-form text may be harder to remove -completely, and tool output keeps its structure and any token, cost, or timing figures a tool -reports. Those can hint at which harness ran the task, so blind evaluation reduces identity cues -without guaranteeing anonymity. +run through T3's orchestration. A task that delegated work is evaluated once that delegated work +finishes, so its result counts. A turn started by an automated wake, such as a finished background +command, is recorded as skipped rather than scored, because it was not a request you wrote. Model +names mentioned inside free-form text may be harder to remove completely, and tool output keeps its +structure and any token, cost, or timing figures a tool reports. Those can hint at which harness ran +the task, so blind evaluation reduces identity cues without guaranteeing anonymity. The judge scores task completion, correctness, instruction following, and verification from 0 to 4. When the evidence cannot establish a score, that dimension stays unscored. A claim that tests passed is not the same as a recorded test result. Failed evaluation calls and insufficient evidence remain -visible in recent evaluations, instead of becoming poor performance scores for the evaluated model. +visible in recent evaluations with a short cause, such as a timeout or an unavailable judge, instead +of becoming poor performance scores for the evaluated model. ## Inspect and use guidance Choose a project under **Learned guidance** to see its recent evaluations and accumulated strengths, limitations, and prompting advice. Results stay within that project and environment. T3 keeps -separate groups for different model options, task categories, top-level versus subagent tasks, -judges, and scoring rubrics, so a change of judge does not silently mix two scales. +separate groups for different task categories, top-level versus subagent tasks, judges, scoring +rubrics, and model options that can change the answer, such as reasoning effort or agent mode. A +change of judge or rubric starts a new group, so two scoring scales are never mixed. Options that only +change speed, cost, or context size, such as fast mode, share one group. Guidance reflects up to 200 observations from the past 90 days. The displayed sample counts show how much evidence supports each score. Small samples remain provisional, and all guidance is an aid to judgment rather than a guarantee about future tasks. Observed prompt lengths describe past requests; they do not measure a model's maximum context window or establish an ideal prompt length. -Agents using T3's orchestration can retrieve this guidance when choosing models and framing delegated -tasks. Your explicit model choice still wins. Turning evaluations off stops new evaluation calls -and use of the guidance while leaving saved history available to inspect. **Clear project history** -removes that project's scores and learned guidance; later tasks can collect new observations. +Agents using T3's orchestration can retrieve this guidance when choosing models and framing +delegated tasks. Groups backed by more scored tasks come first. Your explicit model choice still +wins. Turning evaluations off stops new evaluation calls and use of the guidance while leaving saved +history available to inspect. **Clear project history** removes that project's scores and learned +guidance; later tasks can collect new observations. diff --git a/packages/provider-core/src/server/modelEvaluation.test.ts b/packages/provider-core/src/server/modelEvaluation.test.ts index 0b7f6d0260857..07cb6db031cdd 100644 --- a/packages/provider-core/src/server/modelEvaluation.test.ts +++ b/packages/provider-core/src/server/modelEvaluation.test.ts @@ -19,6 +19,7 @@ import * as DateTime from "effect/DateTime"; import { buildModelEvaluationEvidence, buildModelEvaluationPrompt, + modelEvaluationAwaitsSubagents, validateModelEvaluationVerdict, } from "./modelEvaluation.ts"; @@ -427,3 +428,41 @@ it.each([ scenario === "empty-context", ); }); + +it("waits only while a delegated child is still active", () => { + const child = ( + status: + | "pending" + | "running" + | "waiting" + | "idle" + | "completed" + | "failed" + | "cancelled" + | "interrupted", + ) => ({ runId, type: "subagent" as const, status }); + expect(modelEvaluationAwaitsSubagents([child("running")], runId)).toBe(true); + expect(modelEvaluationAwaitsSubagents([child("pending"), child("waiting")], runId)).toBe(true); + expect( + modelEvaluationAwaitsSubagents( + [ + child("idle"), + child("completed"), + child("failed"), + child("cancelled"), + child("interrupted"), + ], + runId, + ), + ).toBe(false); + expect( + modelEvaluationAwaitsSubagents( + [ + child("completed"), + { runId, type: "command_execution" as const, status: "running" as const }, + ], + runId, + ), + ).toBe(false); + expect(modelEvaluationAwaitsSubagents([child("running")], RunId.make("other-run"))).toBe(false); +}); diff --git a/packages/provider-core/src/server/modelEvaluation.ts b/packages/provider-core/src/server/modelEvaluation.ts index 1722d292ea839..3a7bc1e8f280e 100644 --- a/packages/provider-core/src/server/modelEvaluation.ts +++ b/packages/provider-core/src/server/modelEvaluation.ts @@ -1,5 +1,6 @@ import { type BlindModelEvaluationPacket, + isOrchestrationV2WorkActive, ModelEvaluationVerdict, type ModelEvaluationRunOutcome, type OrchestrationV2ConversationMessage, @@ -171,6 +172,16 @@ function evidenceText(item: OrchestrationV2TurnItem, redact: (text: string) => s } } +export function modelEvaluationAwaitsSubagents( + turnItems: ReadonlyArray>, + runId: OrchestrationV2Run["id"], +): boolean { + return turnItems.some( + (item) => + item.runId === runId && item.type === "subagent" && isOrchestrationV2WorkActive(item.status), + ); +} + export function buildModelEvaluationEvidence(input: { readonly run: Pick< OrchestrationV2Run,