Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

RunMetrics.ts

113 lines4.6 KB

1import type {
2 OrchestrationV2Run,
3 OrchestrationV2StoredEvent,
4 RunId,
5 ThreadId,
6} from "@t3tools/contracts";
7import * as DateTime from "effect/DateTime";
8import type * as Duration from "effect/Duration";
9import * as Effect from "effect/Effect";
10import * as Metric from "effect/Metric";
11​
12import { normalizeModelMetricLabel } from "../observability/Attributes.ts";
13import {
14 metricAttributes,
15 runDuration,
16 runQueueWait,
17 runsTotal,
18} from "../observability/Metrics.ts";
19​
20const REMEMBERED_RUNS = 4096;
21// A rollback rewrites runs that already finished, stamping the rollback time as their completion,
22// so it is not counted as an outcome. Declared here because ThreadManagementService imports
23// EventSink.
24const OUTCOMES: ReadonlySet<OrchestrationV2Run["status"]> = new Set([
25 "completed",
26 "failed",
27 "cancelled",
28 "interrupted",
29]);
30​
31export interface RunOutcome {
32 readonly runId: RunId;
33 readonly attributes: ReturnType<typeof metricAttributes>;
34 readonly queueWait: Duration.Duration | undefined;
35 readonly duration: Duration.Duration | undefined;
37​
38/**
39 * Records each run once, when a committed event first shows it finished. A finished run's row is
40 * updated again later (its checkpoint, a settlement), so recently counted runs are remembered.
41 *
42 * A run carries `delegatedTaskId` only when a follow-up is associated with a task, so a subagent
43 * thread's first run is recognized by its thread's lineage instead. A failed lookup only costs the
44 * label: the events still commit and publish.
45 *
46 * `prepare` reads lineage, so the EventSink runs it inside the write transaction, on the
47 * connection that transaction already holds. `record` runs after the commit, under the publish
48 * lane, and must stay free of I/O: a read there waits for the writer connection while holding the
49 * lane, and the next writer holds that connection while it waits for the lane.
50 */
51export const makeRunOutcomeRecorder = <E>(
52 isSubagentThread: (threadId: ThreadId) => Effect.Effect<boolean, E>,
53) => {
54 const counted = new Set<string>();
55 // Untraced: both run for every committed batch inside the EventSink operation's span.
56 // Never reads or writes `counted`, so a transaction that rolls back reserves nothing.
57 const prepare = Effect.fnUntraced(function* (events: ReadonlyArray<OrchestrationV2StoredEvent>) {
58 const outcomes: Array<RunOutcome> = [];
59 // Every finished run is prepared, in order, even one already counted: an earlier outcome in
60 // this batch may evict it before `record` reaches it, so only `record` decides what counts.
61 // Only the lineage read is shared.
62 const delegatedThreads = new Map<ThreadId, boolean>();
63 for (const { event } of events) {
64 if (event.type !== "run.updated") continue;
65 const run = event.payload;
66 if (!OUTCOMES.has(run.status)) continue;
67 let delegated = run.delegatedTaskId !== undefined || delegatedThreads.get(run.threadId);
68 if (delegated === undefined) {
69 delegated = yield* isSubagentThread(run.threadId).pipe(Effect.orElseSucceed(() => false));
70 delegatedThreads.set(run.threadId, delegated);
71 }
72 outcomes.push({
73 runId: run.id,
74 attributes: metricAttributes({
75 provider: run.providerInstanceId,
76 modelFamily: normalizeModelMetricLabel(run.modelSelection.model),
77 outcome: run.status,
78 delegated,
79 }),
80 queueWait:
81 run.startedAt === null ? undefined : DateTime.distance(run.requestedAt, run.startedAt),
82 duration:
83 run.startedAt === null || run.completedAt === null
84 ? undefined
85 : DateTime.distance(run.startedAt, run.completedAt),
86 });
87 }
88 return outcomes;
89 });
90 // Uninterruptible so a run is never marked counted with only part of its measurements.
91 const record = Effect.fnUntraced(function* (outcomes: ReadonlyArray<RunOutcome>) {
92 for (const outcome of outcomes) {
93 // Concurrent writers can prepare the same run; the first to publish counts it.
94 if (counted.has(outcome.runId)) continue;
95 counted.add(outcome.runId);
96 if (counted.size > REMEMBERED_RUNS) counted.delete(counted.values().next().value!);
97 yield* Metric.update(Metric.withAttributes(runsTotal, outcome.attributes), 1);
98 if (outcome.queueWait !== undefined) {
99 yield* Metric.update(
100 Metric.withAttributes(runQueueWait, outcome.attributes),
101 outcome.queueWait,
102 );
103 }
104 if (outcome.duration !== undefined) {
105 yield* Metric.update(
106 Metric.withAttributes(runDuration, outcome.attributes),
107 outcome.duration,
108 );
109 }
110 }
111 }, Effect.uninterruptible);
112 return { prepare, record };
113};