From ad971dbdd30a9a3c3f8343c23a64aadcd03f2e31 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Thu, 2 Apr 2026 18:15:27 -0700 Subject: [PATCH] Track orchestration command outcomes in metrics - Record success, failure, and interrupt outcomes from command dispatch - Normalize invalid dates and group GPT models under a shared label - Add coverage for failed dispatch metric accounting --- .../src/observability/Attributes.test.ts | 19 +- apps/server/src/observability/Attributes.ts | 6 +- apps/server/src/observability/Metrics.ts | 10 +- .../Layers/OrchestrationEngine.test.ts | 38 +++ .../Layers/OrchestrationEngine.ts | 280 ++++++++++-------- 5 files changed, 216 insertions(+), 137 deletions(-) diff --git a/apps/server/src/observability/Attributes.test.ts b/apps/server/src/observability/Attributes.test.ts index de08bac225..4b495598ea 100644 --- a/apps/server/src/observability/Attributes.test.ts +++ b/apps/server/src/observability/Attributes.test.ts @@ -1,6 +1,6 @@ import { assert, describe, it } from "@effect/vitest"; -import { compactTraceAttributes } from "./Attributes.ts"; +import { compactTraceAttributes, normalizeModelMetricLabel } from "./Attributes.ts"; describe("Attributes", () => { it("normalizes circular arrays, maps, and sets without recursing forever", () => { @@ -26,4 +26,21 @@ describe("Attributes", () => { }, ); }); + + it("normalizes invalid dates without throwing", () => { + assert.deepStrictEqual( + compactTraceAttributes({ + invalidDate: new Date("not-a-real-date"), + }), + { + invalidDate: "Invalid Date", + }, + ); + }); + + it("groups GPT-family models under a shared metric label", () => { + assert.strictEqual(normalizeModelMetricLabel("gpt-4o"), "gpt"); + assert.strictEqual(normalizeModelMetricLabel("gpt-5.4"), "gpt"); + assert.strictEqual(normalizeModelMetricLabel("claude-sonnet-4"), "claude"); + }); }); diff --git a/apps/server/src/observability/Attributes.ts b/apps/server/src/observability/Attributes.ts index ab003f6ebd..2251fcfea6 100644 --- a/apps/server/src/observability/Attributes.ts +++ b/apps/server/src/observability/Attributes.ts @@ -31,7 +31,7 @@ function normalizeJsonValue(value: unknown, seen: WeakSet = new WeakSet( return value.toString(); } if (value instanceof Date) { - return value.toISOString(); + return Number.isNaN(value.getTime()) ? "Invalid Date" : value.toISOString(); } if (value instanceof Error) { return { @@ -115,8 +115,8 @@ export function normalizeModelMetricLabel(model: string | null | undefined): str if (!normalized) { return undefined; } - if (normalized.includes("gpt-5")) { - return "gpt-5"; + if (normalized.includes("gpt")) { + return "gpt"; } if (normalized.includes("claude")) { return "claude"; diff --git a/apps/server/src/observability/Metrics.ts b/apps/server/src/observability/Metrics.ts index a9530ad2c8..115859fe15 100644 --- a/apps/server/src/observability/Metrics.ts +++ b/apps/server/src/observability/Metrics.ts @@ -155,11 +155,11 @@ export const providerTurnMetricAttributes = (input: { readonly provider: string; readonly model: string | null | undefined; readonly extra?: Readonly>; -}) => - compactMetricAttributes({ +}) => { + const modelFamily = normalizeModelMetricLabel(input.model); + return compactMetricAttributes({ provider: input.provider, - ...(normalizeModelMetricLabel(input.model) - ? { modelFamily: normalizeModelMetricLabel(input.model) } - : {}), + ...(modelFamily ? { modelFamily } : {}), ...input.extra, }); +}; diff --git a/apps/server/src/orchestration/Layers/OrchestrationEngine.test.ts b/apps/server/src/orchestration/Layers/OrchestrationEngine.test.ts index dd945cc9e7..5a0a6113f0 100644 --- a/apps/server/src/orchestration/Layers/OrchestrationEngine.test.ts +++ b/apps/server/src/orchestration/Layers/OrchestrationEngine.test.ts @@ -470,6 +470,44 @@ describe("OrchestrationEngine", () => { await system.dispose(); }); + it("records failed command dispatches as metric failures", async () => { + const system = await createOrchestrationSystem(); + const { engine } = system; + const createdAt = now(); + + await expect( + system.run( + engine.dispatch({ + type: "thread.create", + commandId: CommandId.makeUnsafe("cmd-thread-missing-project"), + threadId: ThreadId.makeUnsafe("thread-missing-project"), + projectId: asProjectId("project-missing"), + title: "Missing Project Thread", + modelSelection: { + provider: "codex", + model: "gpt-5-codex", + }, + interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, + runtimeMode: "full-access", + branch: null, + worktreePath: null, + createdAt, + }), + ), + ).rejects.toThrow("does not exist"); + + const snapshots = await system.run(Metric.snapshot); + expect( + hasMetricSnapshot(snapshots, "t3_orchestration_commands_total", { + commandType: "thread.create", + aggregateKind: "thread", + outcome: "failure", + }), + ).toBe(true); + + await system.dispose(); + }); + it("stores completed checkpoint summaries even when no files changed", async () => { const system = await createOrchestrationSystem(); const { engine } = system; diff --git a/apps/server/src/orchestration/Layers/OrchestrationEngine.ts b/apps/server/src/orchestration/Layers/OrchestrationEngine.ts index 15e3b45ad0..ddd1718faf 100644 --- a/apps/server/src/orchestration/Layers/OrchestrationEngine.ts +++ b/apps/server/src/orchestration/Layers/OrchestrationEngine.ts @@ -6,9 +6,11 @@ import type { } from "@t3tools/contracts"; import { OrchestrationCommand } from "@t3tools/contracts"; import { + Cause, Deferred, Duration, Effect, + Exit, Layer, Metric, Option, @@ -24,7 +26,6 @@ import { orchestrationCommandAckDuration, orchestrationCommandsTotal, orchestrationCommandDuration, - withMetrics, } from "../../observability/Metrics.ts"; import { toPersistenceSqlError } from "../../persistence/Errors.ts"; import { OrchestrationEventStore } from "../../persistence/Services/OrchestrationEventStore.ts"; @@ -83,7 +84,12 @@ const makeOrchestrationEngine = Effect.gen(function* () { const processEnvelope = (envelope: CommandEnvelope): Effect.Effect => { const dispatchStartSequence = readModel.snapshotSequence; + const processingStartedAtMs = Date.now(); const aggregateRef = commandToAggregateRef(envelope.command); + const baseMetricAttributes = { + commandType: envelope.command.type, + aggregateKind: aggregateRef.aggregateKind, + } as const; const reconcileReadModelAfterDispatchFailure = Effect.gen(function* () { const persistedEvents = yield* Stream.runCollect( eventStore.readFromSequence(dispatchStartSequence), @@ -103,145 +109,163 @@ const makeOrchestrationEngine = Effect.gen(function* () { } }); - return Effect.gen(function* () { - yield* Effect.annotateCurrentSpan({ - "orchestration.command_id": envelope.command.commandId, - "orchestration.command_type": envelope.command.type, - "orchestration.aggregate_kind": aggregateRef.aggregateKind, - "orchestration.aggregate_id": aggregateRef.aggregateId, - }); + return Effect.exit( + Effect.gen(function* () { + yield* Effect.annotateCurrentSpan({ + "orchestration.command_id": envelope.command.commandId, + "orchestration.command_type": envelope.command.type, + "orchestration.aggregate_kind": aggregateRef.aggregateKind, + "orchestration.aggregate_id": aggregateRef.aggregateId, + }); - const existingReceipt = yield* commandReceiptRepository.getByCommandId({ - commandId: envelope.command.commandId, - }); - if (Option.isSome(existingReceipt)) { - if (existingReceipt.value.status === "accepted") { - yield* Deferred.succeed(envelope.result, { - sequence: existingReceipt.value.resultSequence, - }); - return; - } - yield* Deferred.fail( - envelope.result, - new OrchestrationCommandPreviouslyRejectedError({ + const existingReceipt = yield* commandReceiptRepository.getByCommandId({ + commandId: envelope.command.commandId, + }); + if (Option.isSome(existingReceipt)) { + if (existingReceipt.value.status === "accepted") { + return { + sequence: existingReceipt.value.resultSequence, + }; + } + return yield* new OrchestrationCommandPreviouslyRejectedError({ commandId: envelope.command.commandId, detail: existingReceipt.value.error ?? "Previously rejected.", - }), - ); - return; - } - - const eventBase = yield* decideOrchestrationCommand({ - command: envelope.command, - readModel, - }); - const eventBases = Array.isArray(eventBase) ? eventBase : [eventBase]; - const committedCommand = yield* sql - .withTransaction( - Effect.gen(function* () { - const committedEvents: OrchestrationEvent[] = []; - let nextReadModel = readModel; - - for (const nextEvent of eventBases) { - const savedEvent = yield* eventStore.append(nextEvent); - nextReadModel = yield* projectEvent(nextReadModel, savedEvent); - yield* projectionPipeline.projectEvent(savedEvent); - committedEvents.push(savedEvent); - } - - const lastSavedEvent = committedEvents.at(-1) ?? null; - if (lastSavedEvent === null) { - return yield* new OrchestrationCommandInvariantError({ - commandType: envelope.command.type, - detail: "Command produced no events.", - }); - } - - yield* commandReceiptRepository.upsert({ - commandId: envelope.command.commandId, - aggregateKind: lastSavedEvent.aggregateKind, - aggregateId: lastSavedEvent.aggregateId, - acceptedAt: lastSavedEvent.occurredAt, - resultSequence: lastSavedEvent.sequence, - status: "accepted", - error: null, - }); - - return { - committedEvents, - lastSequence: lastSavedEvent.sequence, - nextReadModel, - } as const; - }), - ) - .pipe( - Effect.catchTag("SqlError", (sqlError) => - Effect.fail( - toPersistenceSqlError("OrchestrationEngine.processEnvelope:transaction")(sqlError), - ), - ), - ); - - readModel = committedCommand.nextReadModel; - for (const [index, event] of committedCommand.committedEvents.entries()) { - yield* PubSub.publish(eventPubSub, event); - if (index === 0) { - yield* Metric.update( - Metric.withAttributes( - orchestrationCommandAckDuration, - metricAttributes({ - commandType: envelope.command.type, - aggregateKind: aggregateRef.aggregateKind, - ackEventType: event.type, - }), - ), - Duration.millis(Math.max(0, Date.now() - envelope.startedAtMs)), - ); + }); } - } - yield* Deferred.succeed(envelope.result, { sequence: committedCommand.lastSequence }); - }).pipe( - Effect.catch((error) => - Effect.gen(function* () { - yield* reconcileReadModelAfterDispatchFailure.pipe( - Effect.catch(() => - Effect.logWarning( - "failed to reconcile orchestration read model after dispatch failure", - ).pipe( - Effect.annotateLogs({ - commandId: envelope.command.commandId, - snapshotSequence: readModel.snapshotSequence, - }), + + const eventBase = yield* decideOrchestrationCommand({ + command: envelope.command, + readModel, + }); + const eventBases = Array.isArray(eventBase) ? eventBase : [eventBase]; + const committedCommand = yield* sql + .withTransaction( + Effect.gen(function* () { + const committedEvents: OrchestrationEvent[] = []; + let nextReadModel = readModel; + + for (const nextEvent of eventBases) { + const savedEvent = yield* eventStore.append(nextEvent); + nextReadModel = yield* projectEvent(nextReadModel, savedEvent); + yield* projectionPipeline.projectEvent(savedEvent); + committedEvents.push(savedEvent); + } + + const lastSavedEvent = committedEvents.at(-1) ?? null; + if (lastSavedEvent === null) { + return yield* new OrchestrationCommandInvariantError({ + commandType: envelope.command.type, + detail: "Command produced no events.", + }); + } + + yield* commandReceiptRepository.upsert({ + commandId: envelope.command.commandId, + aggregateKind: lastSavedEvent.aggregateKind, + aggregateId: lastSavedEvent.aggregateId, + acceptedAt: lastSavedEvent.occurredAt, + resultSequence: lastSavedEvent.sequence, + status: "accepted", + error: null, + }); + + return { + committedEvents, + lastSequence: lastSavedEvent.sequence, + nextReadModel, + } as const; + }), + ) + .pipe( + Effect.catchTag("SqlError", (sqlError) => + Effect.fail( + toPersistenceSqlError("OrchestrationEngine.processEnvelope:transaction")(sqlError), ), ), ); - if (Schema.is(OrchestrationCommandInvariantError)(error)) { - yield* commandReceiptRepository - .upsert({ - commandId: envelope.command.commandId, - aggregateKind: aggregateRef.aggregateKind, - aggregateId: aggregateRef.aggregateId, - acceptedAt: new Date().toISOString(), - resultSequence: readModel.snapshotSequence, - status: "rejected", - error: error.message, - }) - .pipe(Effect.catch(() => Effect.void)); + readModel = committedCommand.nextReadModel; + for (const [index, event] of committedCommand.committedEvents.entries()) { + yield* PubSub.publish(eventPubSub, event); + if (index === 0) { + yield* Metric.update( + Metric.withAttributes( + orchestrationCommandAckDuration, + metricAttributes({ + ...baseMetricAttributes, + ackEventType: event.type, + }), + ), + Duration.millis(Math.max(0, Date.now() - envelope.startedAtMs)), + ); } + } + return { sequence: committedCommand.lastSequence }; + }).pipe(Effect.withSpan(`orchestration.command.${envelope.command.type}`)), + ).pipe( + Effect.flatMap((exit) => + Effect.gen(function* () { + const outcome = Exit.isSuccess(exit) + ? "success" + : Cause.hasInterruptsOnly(exit.cause) + ? "interrupt" + : "failure"; + yield* Metric.update( + Metric.withAttributes( + orchestrationCommandDuration, + metricAttributes(baseMetricAttributes), + ), + Duration.millis(Math.max(0, Date.now() - processingStartedAtMs)), + ); + yield* Metric.update( + Metric.withAttributes( + orchestrationCommandsTotal, + metricAttributes({ + ...baseMetricAttributes, + outcome, + }), + ), + 1, + ); + + if (Exit.isSuccess(exit)) { + yield* Deferred.succeed(envelope.result, exit.value); + return; + } + + const error = Cause.squash(exit.cause) as OrchestrationDispatchError; + if (!Schema.is(OrchestrationCommandPreviouslyRejectedError)(error)) { + yield* reconcileReadModelAfterDispatchFailure.pipe( + Effect.catch(() => + Effect.logWarning( + "failed to reconcile orchestration read model after dispatch failure", + ).pipe( + Effect.annotateLogs({ + commandId: envelope.command.commandId, + snapshotSequence: readModel.snapshotSequence, + }), + ), + ), + ); + + if (Schema.is(OrchestrationCommandInvariantError)(error)) { + yield* commandReceiptRepository + .upsert({ + commandId: envelope.command.commandId, + aggregateKind: aggregateRef.aggregateKind, + aggregateId: aggregateRef.aggregateId, + acceptedAt: new Date().toISOString(), + resultSequence: readModel.snapshotSequence, + status: "rejected", + error: error.message, + }) + .pipe(Effect.catch(() => Effect.void)); + } + } + yield* Deferred.fail(envelope.result, error); }), ), - Effect.withSpan(`orchestration.command.${envelope.command.type}`), - Effect.asVoid, - withMetrics({ - counter: orchestrationCommandsTotal, - timer: orchestrationCommandDuration, - attributes: { - commandType: envelope.command.type, - aggregateKind: aggregateRef.aggregateKind, - }, - }), ); };