TypeScript
feat(server): export how long runs take and how they end (#22094)
Julius Marmingef8e4834861d2
diff --git a/apps/server/src/observability/Metrics.ts b/apps/server/src/observability/Metrics.tsindex 6ba17819cea..9d3b3e13c0f 100644--- a/apps/server/src/observability/Metrics.ts+++ b/apps/server/src/observability/Metrics.ts@@ -63,6 +63,18 @@ export const serverEventLoopDelayMax = Metric.gauge("t3_server_event_loop_delay_attributes: { unit: "ms" },});+export const runsTotal = Metric.counter("t3_runs_total", {+ description: "Runs that finished, by outcome. A later rollback does not count again.",+});++export const runDuration = Metric.timer("t3_run_duration", {+ description: "Wall time of a run, from when it started to its terminal status.",+});++export const runQueueWait = Metric.timer("t3_run_queue_wait", {+ description: "Time a run waited between being requested and starting.",+});+export const gitCommandsTotal = Metric.counter("t3_git_commands_total", {description: "Total git commands executed by the server runtime.",});diff --git a/apps/server/src/orchestration-v2/EventSink.ts b/apps/server/src/orchestration-v2/EventSink.tsindex d2bd8a7ac03..bf50bbc8395 100644--- a/apps/server/src/orchestration-v2/EventSink.ts+++ b/apps/server/src/orchestration-v2/EventSink.ts@@ -26,6 +26,7 @@ import * as SqlClient from "effect/sql/SqlClient";import { replayAndBufferProjectedLiveEvents } from "./LiveStreamBudget.ts";import type { UnsequencedProjectEvent } from "../persistence/OrchestrationEventStore.ts";import { projectDomainEventForWire } from "./WireProjection.ts";+import { makeRunOutcomeRecorder, type RunOutcome } from "./RunMetrics.ts";import * as CommandReceiptStore from "./CommandReceiptStore.ts";import * as EffectOutbox from "./EffectOutbox.ts";@@ -243,8 +244,23 @@ const layerBase: Layer.Layer<);}});- const publishStoredEvents = (events: ReadonlyArray<OrchestrationV2StoredEvent>) =>- eventStore.publishCommitted(events).pipe(Effect.andThen(publishLiveEvents(events)));+ const runOutcomes = makeRunOutcomeRecorder((threadId) =>+ // One payload row; unlike the shell, it still resolves a deleted child thread.+ projectionStore+ .getThread(threadId)+ .pipe(Effect.map((thread) => thread.lineage.relationshipToParent === "subagent")),+ );+ // Recorded before publication, so an interrupted publish cannot lose a committed outcome.+ const publishStoredEvents = (+ events: ReadonlyArray<OrchestrationV2StoredEvent>,+ outcomes: ReadonlyArray<RunOutcome>,+ ) =>+ runOutcomes+ .record(outcomes)+ .pipe(+ Effect.andThen(eventStore.publishCommitted(events)),+ Effect.andThen(publishLiveEvents(events)),+ );// Transactions commit one at a time, but each writer publishes after its// commit. If a writer is descheduled in between, a later commit reaches@@ -373,6 +389,8 @@ const layerBase: Layer.Layer<updated_at = excluded.updated_at`;}+ // Read lineage here, on the connection this transaction holds; see makeRunOutcomeRecorder.+ return yield* runOutcomes.prepare(storedEvents);});const writeEffect = Effect.fn("orchestrationV2.EventSink.write")(function* (@@ -384,7 +402,7 @@ const layerBase: Layer.Layer<"orchestration_v2.thread_id": input.events[0]?.threadId ?? null,});- return yield* commitThenPublish(+ const { committed } = yield* commitThenPublish(Effect.gen(function* () {// Check ownership in the same transaction that claims the native session.const imported = input.unlessNativeThreadOwned;@@ -398,7 +416,7 @@ const layerBase: Layer.Layer<AND json_extract(payload_json, '$.nativeThreadRef.nativeId') = ${imported.nativeThreadRef.nativeId}LIMIT 1`;- if (owners.length > 0) return [];+ if (owners.length > 0) return { committed: [], outcomes: [] };}// Checkpoint capture can finish after a cohort writer reads its parent run.// Merge in this transaction so the event log and projection keep that completion.@@ -433,18 +451,19 @@ const layerBase: Layer.Layer<...(input.commandId === undefined ? {} : { commandId: input.commandId }),events: normalized,});- yield* applyStoredEvents(committed);+ const outcomes = yield* applyStoredEvents(committed);yield* effectOutbox.enqueue(input.effects);- return committed;+ return { committed, outcomes };}).pipe(Effect.withTracerEnabled(false)),- (storedEvents) =>+ ({ committed, outcomes }) =>Effect.gen(function* () {if (input.effects.length > 0) {yield* effectOutbox.notifyAvailable(input.effects.length);}- yield* publishStoredEvents(storedEvents);+ yield* publishStoredEvents(committed, outcomes);}),);+ return committed;});const writeIfRunCurrentEffect = Effect.fn("orchestrationV2.EventSink.writeIfRunCurrent")(@@ -491,9 +510,9 @@ const layerBase: Layer.Layer<...(input.commandId === undefined ? {} : { commandId: input.commandId }),events: normalized,});- yield* applyStoredEvents(storedEvents);+ const outcomes = yield* applyStoredEvents(storedEvents);yield* effectOutbox.enqueue(input.effects ?? []);- return { committed: true as const, storedEvents };+ return { committed: true as const, storedEvents, outcomes };}),(result) =>Effect.gen(function* () {@@ -501,7 +520,7 @@ const layerBase: Layer.Layer<if (input.effects !== undefined && input.effects.length > 0) {yield* effectOutbox.notifyAvailable(input.effects.length);}- yield* publishStoredEvents(result.storedEvents);+ yield* publishStoredEvents(result.storedEvents, result.outcomes);}),);},@@ -556,10 +575,13 @@ const layerBase: Layer.Layer<...(input.commandId === undefined ? {} : { commandId: input.commandId }),events: normalized,});- yield* applyStoredEvents(storedEvents);- return { committed: true as const, storedEvents };+ const outcomes = yield* applyStoredEvents(storedEvents);+ return { committed: true as const, storedEvents, outcomes };}),- (result) => (result.committed ? publishStoredEvents(result.storedEvents) : Effect.void),+ (result) =>+ result.committed+ ? publishStoredEvents(result.storedEvents, result.outcomes)+ : Effect.void,);});@@ -589,10 +611,13 @@ const layerBase: Layer.Layer<const normalized = yield* normalizeEvents(input.events);const storedEvents = yield* eventStore.append({ events: normalized });- yield* applyStoredEvents(storedEvents);- return { committed: true as const, storedEvents };+ const outcomes = yield* applyStoredEvents(storedEvents);+ return { committed: true as const, storedEvents, outcomes };}),- (result) => (result.committed ? publishStoredEvents(result.storedEvents) : Effect.void),+ (result) =>+ result.committed+ ? publishStoredEvents(result.storedEvents, result.outcomes)+ : Effect.void,);});@@ -642,7 +667,7 @@ const layerBase: Layer.Layer<new Error(`Command ${input.commandId} produced no orchestration events.`),);}- yield* applyStoredEvents(storedEvents);+ const outcomes = yield* applyStoredEvents(storedEvents);yield* effectOutbox.enqueue(input.effects);const receipt: CommandReceiptStore.CommandReceiptV2 = {commandId: input.commandId,@@ -661,7 +686,7 @@ const layerBase: Layer.Layer<threadId: input.threadId,...input.cancelUnsettledEffects,});- return { receipt, storedEvents, committed: true as const, cancelledEffectIds };+ return { receipt, storedEvents, outcomes, committed: true as const, cancelledEffectIds };}),(result) =>Effect.gen(function* () {@@ -669,7 +694,7 @@ const layerBase: Layer.Layer<if (result.committed && input.effects.length > 0) {yield* effectOutbox.notifyAvailable(input.effects.length);}- if (result.committed) yield* publishStoredEvents(result.storedEvents);+ if (result.committed) yield* publishStoredEvents(result.storedEvents, result.outcomes);}),);return {diff --git a/apps/server/src/orchestration-v2/RunMetrics.test.ts b/apps/server/src/orchestration-v2/RunMetrics.test.tsnew file mode 100644index 00000000000..fead1c29a96--- /dev/null+++ b/apps/server/src/orchestration-v2/RunMetrics.test.ts@@ -0,0 +1,284 @@+import { assert, describe, it } from "@effect/vitest";+import {+ EventId,+ MessageId,+ ProjectId,+ ProviderInstanceId,+ RunId,+ ThreadId,+ type OrchestrationV2AppThread,+ type OrchestrationV2DomainEvent,+ type OrchestrationV2Run,+ type OrchestrationV2StoredEvent,+} from "@t3tools/contracts";+import * as DateTime from "effect/DateTime";+import * as Deferred from "effect/Deferred";+import * as Effect from "effect/Effect";+import * as Fiber from "effect/Fiber";+import * as Layer from "effect/Layer";+import * as Metric from "effect/Metric";+import * as Option from "effect/Option";+import * as SqlClient from "effect/sql/SqlClient";++import * as SqlitePersistence from "../persistence/Sqlite.ts";+import * as EventSink from "./EventSink.ts";+import * as EventStore from "./EventStore.ts";+import * as ProjectionStore from "./ProjectionStore.ts";+import { makeRunOutcomeRecorder } from "./RunMetrics.ts";++const at = (iso: string) => DateTime.makeUnsafe(iso);+const threadId = ThreadId.make("thread:metrics");++// Each test labels its runs with its own provider, since the metric registry is shared.+const runUpdated = (+ sequence: number,+ provider: string,+ run: Pick<OrchestrationV2Run, "id" | "status" | "startedAt" | "completedAt"> &+ Partial<OrchestrationV2Run>,+): OrchestrationV2StoredEvent => ({+ sequence,+ commandId: null,+ event: {+ type: "run.updated",+ id: EventId.make(`event:${provider}:${sequence}`),+ threadId,+ occurredAt: at("2026-10-19T12:00:00.000Z"),+ payload: {+ threadId,+ ordinal: 1,+ providerInstanceId: ProviderInstanceId.make(provider),+ modelSelection: { instanceId: ProviderInstanceId.make(provider), model: "claude-opus-5-5" },+ requestedAt: at("2026-10-19T12:00:00.000Z"),+ ...run,+ } as OrchestrationV2Run,+ },+});++// Prepare inside the transaction, record after its commit, as the EventSink does.+const commitWith =+ (recorder: ReturnType<typeof makeRunOutcomeRecorder<unknown>>) =>+ (events: ReadonlyArray<OrchestrationV2StoredEvent>) =>+ recorder.prepare(events).pipe(Effect.flatMap(recorder.record));++const runSnapshots = (provider: string) =>+ Metric.snapshot.pipe(+ Effect.map((snapshots) =>+ snapshots.filter(+ (snapshot) =>+ snapshot.id.startsWith("t3_run") && snapshot.attributes?.["provider"] === provider,+ ),+ ),+ );++describe("makeRunOutcomeRecorder", () => {+ it.effect("records a finished run once, labelled, with its queue wait and duration", () =>+ Effect.gen(function* () {+ // A subagent thread's first run carries no delegatedTaskId; only its lineage says delegated.+ const recorder = makeRunOutcomeRecorder(() => Effect.succeed(true));+ const record = commitWith(recorder);+ const finished = {+ id: RunId.make("run:metrics:once"),+ status: "completed" as const,+ startedAt: at("2026-10-19T12:00:30.000Z"),+ completedAt: at("2026-10-19T12:10:30.000Z"),+ };++ yield* record([runUpdated(1, "p1", { ...finished, status: "running", completedAt: null })]);+ // A transaction that rolls back prepares and never records; it must not reserve the run.+ yield* recorder.prepare([runUpdated(2, "p1", finished)]);+ yield* record([runUpdated(2, "p1", finished)]);+ // Later updates to a finished run, such as its checkpoint, are not another run.+ yield* record([runUpdated(3, "p1", finished)]);++ const snapshots = yield* runSnapshots("p1");+ const byId = (id: string) => snapshots.find((snapshot) => snapshot.id === id);+ const counter = byId("t3_runs_total");+ assert.strictEqual(counter?.type === "Counter" ? counter.state.count : undefined, 1);+ assert.deepStrictEqual(counter?.attributes, {+ provider: "p1",+ modelFamily: "claude",+ outcome: "completed",+ delegated: "true",+ });+ const histogramSum = (id: string) => {+ const snapshot = byId(id);+ return snapshot?.type === "Histogram" ? snapshot.state.sum : undefined;+ };+ assert.strictEqual(histogramSum("t3_run_queue_wait"), 30_000);+ assert.strictEqual(histogramSum("t3_run_duration"), 600_000);+ }),+ );++ it.effect("does not count a rollback of a run that already finished", () =>+ Effect.gen(function* () {+ // A fresh recorder stands in for a restart, which forgets the runs already counted.+ const record = commitWith(makeRunOutcomeRecorder(() => Effect.succeed(false)));+ yield* record([+ runUpdated(1, "p2", {+ id: RunId.make("run:metrics:rolled-back"),+ status: "rolled_back",+ startedAt: at("2026-10-19T12:00:30.000Z"),+ completedAt: at("2026-10-20T09:00:00.000Z"),+ }),+ ]);++ assert.deepStrictEqual(yield* runSnapshots("p2"), []);+ }),+ );+});++describe("EventSink run outcomes", () => {+ const parentId = ThreadId.make("thread:metrics:sink:parent");+ const childId = ThreadId.make("thread:metrics:sink:child");+ const provider = ProviderInstanceId.make("p-sink");+ const now = at("2026-10-19T12:00:00.000Z");+ const thread = (id: ThreadId, lineage: OrchestrationV2AppThread["lineage"]) =>+ ({+ type: "thread.created",+ id: EventId.make(`event:${id}:created`),+ threadId: id,+ occurredAt: now,+ payload: {+ createdBy: "user",+ creationSource: "web",+ id,+ projectId: ProjectId.make("project:metrics"),+ title: id,+ providerInstanceId: provider,+ modelSelection: { instanceId: provider, model: "gpt-6.1" },+ runtimeMode: "full-access",+ interactionMode: "default",+ branch: null,+ worktreePath: null,+ activeProviderThreadId: null,+ lineage,+ forkedFrom: null,+ createdAt: now,+ updatedAt: now,+ archivedAt: null,+ settledOverride: null,+ settledAt: null,+ lastVisitedAt: null,+ deletedAt: null,+ },+ }) satisfies OrchestrationV2DomainEvent;+ const runId = RunId.make("run:metrics:sink:child");+ const run = (status: OrchestrationV2Run["status"]): OrchestrationV2Run => ({+ id: runId,+ threadId: childId,+ ordinal: 1,+ providerInstanceId: provider,+ modelSelection: { instanceId: provider, model: "gpt-6.1" },+ providerThreadId: null,+ userMessageId: MessageId.make("message:metrics:sink"),+ rootNodeId: null,+ activeAttemptId: null,+ status,+ queuePosition: null,+ requestedAt: now,+ startedAt: at("2026-10-19T12:00:10.000Z"),+ completedAt: status === "running" ? null : at("2026-10-19T12:01:10.000Z"),+ checkpointId: null,+ contextHandoffId: null,+ });+ const runEvent = (type: "run.created" | "run.updated", status: OrchestrationV2Run["status"]) =>+ ({+ type,+ id: EventId.make(`event:${runId}:${status}`),+ threadId: childId,+ runId,+ occurredAt: now,+ payload: run(status),+ }) satisfies OrchestrationV2DomainEvent;++ it.effect("reads lineage inside the transaction, so a concurrent writer cannot deadlock it", () =>+ Effect.gen(function* () {+ const lookupEntered = yield* Deferred.make<boolean>();+ const releaseLookup = yield* Deferred.make<void>();+ const writerStarted = yield* Deferred.make<void>();+ const pausedLookup = Layer.effect(+ ProjectionStore.ProjectionStoreV2,+ Effect.gen(function* () {+ const store = yield* ProjectionStore.ProjectionStoreV2;+ const sql = yield* SqlClient.SqlClient;+ let paused = false;+ return {+ ...store,+ getThread: (id) =>+ Effect.gen(function* () {+ if (id === childId && !paused) {+ paused = true;+ const inTransaction = Option.isSome(+ yield* Effect.serviceOption(sql.transactionService),+ );+ yield* Deferred.succeed(lookupEntered, inTransaction);+ // Outside the transaction this read would wait on the writer it is racing.+ if (inTransaction) yield* Deferred.await(releaseLookup);+ }+ return yield* store.getThread(id);+ }),+ };+ }),+ );+ const layer = EventSink.layer.pipe(+ Layer.provideMerge(pausedLookup),+ Layer.provideMerge(+ Layer.mergeAll(EventStore.layer, ProjectionStore.layer).pipe(+ Layer.provideMerge(SqlitePersistence.layerMemory),+ ),+ ),+ );++ yield* Effect.gen(function* () {+ const sink = yield* EventSink.EventSinkV2;+ yield* sink.write({+ events: [+ thread(parentId, {+ parentThreadId: null,+ relationshipToParent: null,+ rootThreadId: parentId,+ }),+ thread(childId, {+ parentThreadId: parentId,+ relationshipToParent: "subagent",+ rootThreadId: parentId,+ }),+ runEvent("run.created", "running"),+ ],+ });+ const terminal = yield* sink+ .write({ events: [runEvent("run.updated", "completed")] })+ .pipe(Effect.forkScoped);+ assert.isTrue(yield* Deferred.await(lookupEntered), "lineage read outside the transaction");+ const unrelated = yield* Deferred.succeed(writerStarted, undefined).pipe(+ Effect.andThen(+ sink.write({+ events: [+ thread(ThreadId.make("thread:metrics:sink:other"), {+ parentThreadId: null,+ relationshipToParent: null,+ rootThreadId: ThreadId.make("thread:metrics:sink:other"),+ }),+ ],+ }),+ ),+ Effect.forkScoped,+ );+ yield* Deferred.await(writerStarted);+ yield* Deferred.succeed(releaseLookup, undefined);++ const [terminalEvents, unrelatedEvents] = [+ yield* Fiber.join(terminal),+ yield* Fiber.join(unrelated),+ ];+ assert.strictEqual(terminalEvents.length, 1);+ assert.strictEqual(unrelatedEvents.length, 1);+ const counter = (yield* runSnapshots("p-sink")).find(+ (snapshot) => snapshot.id === "t3_runs_total",+ );+ assert.strictEqual(counter?.type === "Counter" ? counter.state.count : undefined, 1);+ assert.strictEqual(counter?.attributes?.["delegated"], "true");+ }).pipe(Effect.provide(layer));+ }),+ );+});diff --git a/apps/server/src/orchestration-v2/RunMetrics.ts b/apps/server/src/orchestration-v2/RunMetrics.tsnew file mode 100644index 00000000000..17b90d25441--- /dev/null+++ b/apps/server/src/orchestration-v2/RunMetrics.ts@@ -0,0 +1,113 @@+import type {+ OrchestrationV2Run,+ OrchestrationV2StoredEvent,+ RunId,+ ThreadId,+} from "@t3tools/contracts";+import * as DateTime from "effect/DateTime";+import type * as Duration from "effect/Duration";+import * as Effect from "effect/Effect";+import * as Metric from "effect/Metric";++import { normalizeModelMetricLabel } from "../observability/Attributes.ts";+import {+ metricAttributes,+ runDuration,+ runQueueWait,+ runsTotal,+} from "../observability/Metrics.ts";++const REMEMBERED_RUNS = 4096;+// A rollback rewrites runs that already finished, stamping the rollback time as their completion,+// so it is not counted as an outcome. Declared here because ThreadManagementService imports+// EventSink.+const OUTCOMES: ReadonlySet<OrchestrationV2Run["status"]> = new Set([+ "completed",+ "failed",+ "cancelled",+ "interrupted",+]);++export interface RunOutcome {+ readonly runId: RunId;+ readonly attributes: ReturnType<typeof metricAttributes>;+ readonly queueWait: Duration.Duration | undefined;+ readonly duration: Duration.Duration | undefined;+}++/**+ * Records each run once, when a committed event first shows it finished. A finished run's row is+ * updated again later (its checkpoint, a settlement), so recently counted runs are remembered.+ *+ * A run carries `delegatedTaskId` only when a follow-up is associated with a task, so a subagent+ * thread's first run is recognized by its thread's lineage instead. A failed lookup only costs the+ * label: the events still commit and publish.+ *+ * `prepare` reads lineage, so the EventSink runs it inside the write transaction, on the+ * connection that transaction already holds. `record` runs after the commit, under the publish+ * lane, and must stay free of I/O: a read there waits for the writer connection while holding the+ * lane, and the next writer holds that connection while it waits for the lane.+ */+export const makeRunOutcomeRecorder = <E>(+ isSubagentThread: (threadId: ThreadId) => Effect.Effect<boolean, E>,+) => {+ const counted = new Set<string>();+ // Untraced: both run for every committed batch inside the EventSink operation's span.+ // Never reads or writes `counted`, so a transaction that rolls back reserves nothing.+ const prepare = Effect.fnUntraced(function* (events: ReadonlyArray<OrchestrationV2StoredEvent>) {+ const outcomes: Array<RunOutcome> = [];+ // Every finished run is prepared, in order, even one already counted: an earlier outcome in+ // this batch may evict it before `record` reaches it, so only `record` decides what counts.+ // Only the lineage read is shared.+ const delegatedThreads = new Map<ThreadId, boolean>();+ for (const { event } of events) {+ if (event.type !== "run.updated") continue;+ const run = event.payload;+ if (!OUTCOMES.has(run.status)) continue;+ let delegated = run.delegatedTaskId !== undefined || delegatedThreads.get(run.threadId);+ if (delegated === undefined) {+ delegated = yield* isSubagentThread(run.threadId).pipe(Effect.orElseSucceed(() => false));+ delegatedThreads.set(run.threadId, delegated);+ }+ outcomes.push({+ runId: run.id,+ attributes: metricAttributes({+ provider: run.providerInstanceId,+ modelFamily: normalizeModelMetricLabel(run.modelSelection.model),+ outcome: run.status,+ delegated,+ }),+ queueWait:+ run.startedAt === null ? undefined : DateTime.distance(run.requestedAt, run.startedAt),+ duration:+ run.startedAt === null || run.completedAt === null+ ? undefined+ : DateTime.distance(run.startedAt, run.completedAt),+ });+ }+ return outcomes;+ });+ // Uninterruptible so a run is never marked counted with only part of its measurements.+ const record = Effect.fnUntraced(function* (outcomes: ReadonlyArray<RunOutcome>) {+ for (const outcome of outcomes) {+ // Concurrent writers can prepare the same run; the first to publish counts it.+ if (counted.has(outcome.runId)) continue;+ counted.add(outcome.runId);+ if (counted.size > REMEMBERED_RUNS) counted.delete(counted.values().next().value!);+ yield* Metric.update(Metric.withAttributes(runsTotal, outcome.attributes), 1);+ if (outcome.queueWait !== undefined) {+ yield* Metric.update(+ Metric.withAttributes(runQueueWait, outcome.attributes),+ outcome.queueWait,+ );+ }+ if (outcome.duration !== undefined) {+ yield* Metric.update(+ Metric.withAttributes(runDuration, outcome.attributes),+ outcome.duration,+ );+ }+ }+ }, Effect.uninterruptible);+ return { prepare, record };+};