Open History to see the last commit
1import { assert, describe, it } from "@effect/vitest";
2import {
3 EventId,
4 MessageId,
5 ProjectId,
6 ProviderInstanceId,
7 RunId,
8 ThreadId,
9 type OrchestrationV2AppThread,
10 type OrchestrationV2DomainEvent,
11 type OrchestrationV2Run,
12 type OrchestrationV2StoredEvent,
13} from "@t3tools/contracts";
14import * as DateTime from "effect/DateTime";
15import * as Deferred from "effect/Deferred";
16import * as Effect from "effect/Effect";
17import * as Fiber from "effect/Fiber";
18import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
19import * as Layer from "effect/Layer";
20import * as Metric from "effect/Metric";
21import * as Option from "effect/Option";
22import * as SqlClient from "effect/sql/SqlClient";
23
24import * as SqlitePersistence from "../persistence/Sqlite.ts";
25import * as EventSink from "./EventSink.ts";
26import * as EventStore from "./EventStore.ts";
27import * as ProjectionStore from "./ProjectionStore.ts";
28import { makeRunOutcomeRecorder } from "./RunMetrics.ts";
29
30const at = (iso: string) => DateTime.makeUnsafe(iso);
31const threadId = ThreadId.make("thread:metrics");
32
33// Each test labels its runs with its own provider, since the metric registry is shared.
34const runUpdated = (
35 sequence: number,
36 provider: string,
37 run: Pick<OrchestrationV2Run, "id" | "status" | "startedAt" | "completedAt"> &
38 Partial<OrchestrationV2Run>,
39): OrchestrationV2StoredEvent => ({
40 sequence,
41 commandId: null,
42 event: {
43 type: "run.updated",
44 id: EventId.make(`event:${provider}:${sequence}`),
45 threadId,
46 occurredAt: at("2026-10-19T12:00:00.000Z"),
47 payload: {
48 threadId,
49 ordinal: 1,
50 providerInstanceId: ProviderInstanceId.make(provider),
51 modelSelection: { instanceId: ProviderInstanceId.make(provider), model: "claude-opus-5-5" },
52 requestedAt: at("2026-10-19T12:00:00.000Z"),
53 ...run,
54 } as OrchestrationV2Run,
55 },
56});
57
58// Prepare inside the transaction, record after its commit, as the EventSink does.
59const commitWith =
60 (recorder: ReturnType<typeof makeRunOutcomeRecorder<unknown>>) =>
61 (events: ReadonlyArray<OrchestrationV2StoredEvent>) =>
62 recorder.prepare(events).pipe(Effect.flatMap(recorder.record));
63
64const runSnapshots = (provider: string) =>
65 Metric.snapshot.pipe(
66 Effect.map((snapshots) =>
67 snapshots.filter(
68 (snapshot) =>
69 snapshot.id.startsWith("t3_run") && snapshot.attributes?.["provider"] === provider,
70 ),
71 ),
72 );
73
74describe("makeRunOutcomeRecorder", () => {
75 it.effect("records a finished run once, labelled, with its queue wait and duration", () =>
76 Effect.gen(function* () {
77 // A subagent thread's first run carries no delegatedTaskId; only its lineage says delegated.
78 const recorder = makeRunOutcomeRecorder(() => Effect.succeed(true));
79 const record = commitWith(recorder);
80 const finished = {
81 id: RunId.make("run:metrics:once"),
82 status: "completed" as const,
83 startedAt: at("2026-10-19T12:00:30.000Z"),
84 completedAt: at("2026-10-19T12:10:30.000Z"),
85 };
86
87 yield* record([runUpdated(1, "p1", { ...finished, status: "running", completedAt: null })]);
88 // A transaction that rolls back prepares and never records; it must not reserve the run.
89 yield* recorder.prepare([runUpdated(2, "p1", finished)]);
90 yield* record([runUpdated(2, "p1", finished)]);
91 // Later updates to a finished run, such as its checkpoint, are not another run.
92 yield* record([runUpdated(3, "p1", finished)]);
93
94 const snapshots = yield* runSnapshots("p1");
95 const byId = (id: string) => snapshots.find((snapshot) => snapshot.id === id);
96 const counter = byId("t3_runs_total");
97 assert.strictEqual(counter?.type === "Counter" ? counter.state.count : undefined, 1);
98 assert.deepStrictEqual(counter?.attributes, {
99 provider: "p1",
100 modelFamily: "claude",
101 outcome: "completed",
102 delegated: "true",
103 });
104 const histogramSum = (id: string) => {
105 const snapshot = byId(id);
106 return snapshot?.type === "Histogram" ? snapshot.state.sum : undefined;
107 };
108 assert.strictEqual(histogramSum("t3_run_queue_wait"), 30_000);
109 assert.strictEqual(histogramSum("t3_run_duration"), 600_000);
110 }),
111 );
112
113 it.effect("labels a run on Antigravity's default model with the default's family", () =>
114 Effect.gen(function* () {
115 const record = commitWith(makeRunOutcomeRecorder(() => Effect.succeed(false)));
116 // `antigravity-default` is what a thread stores when it stays on Antigravity's default, Gemini 4 Neon.
117 yield* record([
118 runUpdated(1, "antigravity", {
119 id: RunId.make("run:metrics:antigravity-default"),
120 status: "completed",
121 startedAt: at("2026-10-19T12:00:30.000Z"),
122 completedAt: at("2026-10-19T12:01:30.000Z"),
123 modelSelection: {
124 instanceId: ProviderInstanceId.make("antigravity"),
125 model: "antigravity-default",
126 },
127 }),
128 ]);
129
130 const counter = (yield* runSnapshots("antigravity")).find(
131 (snapshot) => snapshot.id === "t3_runs_total",
132 );
133 assert.strictEqual(counter?.attributes?.["modelFamily"], "gemini");
134 }),
135 );
136
137 it.effect("does not count a rollback of a run that already finished", () =>
138 Effect.gen(function* () {
139 // A fresh recorder stands in for a restart, which forgets the runs already counted.
140 const record = commitWith(makeRunOutcomeRecorder(() => Effect.succeed(false)));
141 yield* record([
142 runUpdated(1, "p2", {
143 id: RunId.make("run:metrics:rolled-back"),
144 status: "rolled_back",
145 startedAt: at("2026-10-19T12:00:30.000Z"),
146 completedAt: at("2026-10-20T09:00:00.000Z"),
147 }),
148 ]);
149
150 assert.deepStrictEqual(yield* runSnapshots("p2"), []);
151 }),
152 );
153});
154
155describe("EventSink run outcomes", () => {
156 const parentId = ThreadId.make("thread:metrics:sink:parent");
157 const childId = ThreadId.make("thread:metrics:sink:child");
158 const provider = ProviderInstanceId.make("p-sink");
159 const now = at("2026-10-19T12:00:00.000Z");
160 const thread = (id: ThreadId, lineage: OrchestrationV2AppThread["lineage"]) =>
161 ({
162 type: "thread.created",
163 id: EventId.make(`event:${id}:created`),
164 threadId: id,
165 occurredAt: now,
166 payload: {
167 createdBy: "user",
168 creationSource: "web",
169 id,
170 projectId: ProjectId.make("project:metrics"),
171 title: id,
172 providerInstanceId: provider,
173 modelSelection: { instanceId: provider, model: "gpt-6.1" },
174 runtimeMode: "full-access",
175 interactionMode: "default",
176 branch: null,
177 worktreePath: null,
178 activeProviderThreadId: null,
179 lineage,
180 forkedFrom: null,
181 createdAt: now,
182 updatedAt: now,
183 archivedAt: null,
184 settledOverride: null,
185 settledAt: null,
186 lastVisitedAt: null,
187 deletedAt: null,
188 },
189 }) satisfies OrchestrationV2DomainEvent;
190 const runId = RunId.make("run:metrics:sink:child");
191 const run = (status: OrchestrationV2Run["status"]): OrchestrationV2Run => ({
192 id: runId,
193 threadId: childId,
194 ordinal: 1,
195 providerInstanceId: provider,
196 modelSelection: { instanceId: provider, model: "gpt-6.1" },
197 providerThreadId: null,
198 userMessageId: MessageId.make("message:metrics:sink"),
199 rootNodeId: null,
200 activeAttemptId: null,
201 status,
202 queuePosition: null,
203 requestedAt: now,
204 startedAt: at("2026-10-19T12:00:10.000Z"),
205 completedAt: status === "running" ? null : at("2026-10-19T12:01:10.000Z"),
206 checkpointId: null,
207 contextHandoffId: null,
208 });
209 const runEvent = (type: "run.created" | "run.updated", status: OrchestrationV2Run["status"]) =>
210 ({
211 type,
212 id: EventId.make(`event:${runId}:${status}`),
213 threadId: childId,
214 runId,
215 occurredAt: now,
216 payload: run(status),
217 }) satisfies OrchestrationV2DomainEvent;
218
219 it.effect("reads lineage inside the transaction, so a concurrent writer cannot deadlock it", () =>
220 Effect.gen(function* () {
221 const lookupEntered = yield* Deferred.make<boolean>();
222 const releaseLookup = yield* Deferred.make<void>();
223 const writerStarted = yield* Deferred.make<void>();
224 const pausedLookup = Layer.effect(
225 ProjectionStore.ProjectionStoreV2,
226 Effect.gen(function* () {
227 const store = yield* ProjectionStore.ProjectionStoreV2;
228 const sql = yield* SqlClient.SqlClient;
229 let paused = false;
230 return {
231 ...store,
232 getThread: (id) =>
233 Effect.gen(function* () {
234 if (id === childId && !paused) {
235 paused = true;
236 const inTransaction = Option.isSome(
237 yield* Effect.serviceOption(sql.transactionService),
238 );
239 yield* Deferred.succeed(lookupEntered, inTransaction);
240 // Outside the transaction this read would wait on the writer it is racing.
241 if (inTransaction) yield* Deferred.await(releaseLookup);
242 }
243 return yield* store.getThread(id);
244 }),
245 };
246 }),
247 );
248 const layer = EventSink.layer.pipe(
249 Layer.provideMerge(pausedLookup),
250 Layer.provideMerge(
251 Layer.mergeAll(
252 EventStore.layer,
253 ProjectionStore.layer.pipe(Layer.provide(NodeCrypto.layerDigest)),
254 ).pipe(Layer.provideMerge(SqlitePersistence.layerMemory)),
255 ),
256 );
257
258 yield* Effect.gen(function* () {
259 const sink = yield* EventSink.EventSinkV2;
260 yield* sink.write({
261 events: [
262 thread(parentId, {
263 parentThreadId: null,
264 relationshipToParent: null,
265 rootThreadId: parentId,
266 }),
267 thread(childId, {
268 parentThreadId: parentId,
269 relationshipToParent: "subagent",
270 rootThreadId: parentId,
271 }),
272 runEvent("run.created", "running"),
273 ],
274 });
275 const terminal = yield* sink
276 .write({ events: [runEvent("run.updated", "completed")] })
277 .pipe(Effect.forkScoped);
278 assert.isTrue(yield* Deferred.await(lookupEntered), "lineage read outside the transaction");
279 const unrelated = yield* Deferred.succeed(writerStarted, undefined).pipe(
280 Effect.andThen(
281 sink.write({
282 events: [
283 thread(ThreadId.make("thread:metrics:sink:other"), {
284 parentThreadId: null,
285 relationshipToParent: null,
286 rootThreadId: ThreadId.make("thread:metrics:sink:other"),
287 }),
288 ],
289 }),
290 ),
291 Effect.forkScoped,
292 );
293 yield* Deferred.await(writerStarted);
294 yield* Deferred.succeed(releaseLookup, undefined);
295
296 const [terminalEvents, unrelatedEvents] = [
297 yield* Fiber.join(terminal),
298 yield* Fiber.join(unrelated),
299 ];
300 assert.strictEqual(terminalEvents.length, 1);
301 assert.strictEqual(unrelatedEvents.length, 1);
302 const counter = (yield* runSnapshots("p-sink")).find(
303 (snapshot) => snapshot.id === "t3_runs_total",
304 );
305 assert.strictEqual(counter?.type === "Counter" ? counter.state.count : undefined, 1);
306 assert.strictEqual(counter?.attributes?.["delegated"], "true");
307 }).pipe(Effect.provide(layer));
308 }),
309 );
310});