Open History to see the last commit
1import { assert, it } from "@effect/vitest";
2import {
3 CheckpointScopeId,
4 CommandId,
5 EventId,
6 MessageId,
7 NodeId,
8 type OrchestrationV2AppThread,
9 type OrchestrationV2DomainEvent,
10 type OrchestrationV2Run,
11 ProjectId,
12 ProviderDriverKind,
13 ProviderInstanceId,
14 ProviderSessionId,
15 ProviderThreadId,
16 ProviderTurnId,
17 RunAttemptId,
18 RunId,
19 ThreadId,
20 TurnItemId,
21} from "@t3tools/contracts";
22import * as Console from "effect/Console";
23import * as DateTime from "effect/DateTime";
24import * as Effect from "effect/Effect";
25import * as Layer from "effect/Layer";
26import * as SqlClient from "effect/sql/SqlClient";
27
28import * as SqlitePersistence from "../persistence/Sqlite.ts";
29import * as ServerSettings from "../serverSettings.ts";
30import { CodexProviderCapabilitiesV2 } from "./Adapters/CodexAdapterV2.ts";
31import * as EffectOutbox from "./EffectOutbox.ts";
32import * as EventSink from "./EventSink.ts";
33import * as EventStore from "./EventStore.ts";
34import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
35import * as ProjectionStore from "./ProjectionStore.ts";
36import * as ProviderRuntimeRecovery from "./ProviderRuntimeRecoveryService.ts";
37
38// `it.live` keeps a real clock: each reconcile gets a fresh command id, so the
39// second recover cannot hide behind command receipt dedup.
40
41const layerStores = Layer.mergeAll(
42 EventStore.layer,
43 ProjectionStore.layer,
44 EffectOutbox.layer,
45 IdAllocator.layer,
46).pipe(Layer.provideMerge(SqlitePersistence.layerMemory));
47const layerTest = ProviderRuntimeRecovery.layer.pipe(
48 Layer.provideMerge(EventSink.layer.pipe(Layer.provideMerge(layerStores))),
49 Layer.provideMerge(ServerSettings.layerTest({ continueThreadsAfterServerUpdate: true })),
50);
51
52const providerInstanceId = ProviderInstanceId.make("codex");
53const driver = ProviderDriverKind.make("codex");
54const modelSelection = { instanceId: providerInstanceId, model: "gpt-5.4" };
55const projectId = ProjectId.make("project:recovery-bench");
56const ITEMS_PER_SETTLED_THREAD = 10;
57const OPEN_ITEMS_PER_ACTIVE_THREAD = 3;
58const WAITING_THREADS = 3;
59const SEED_BATCH = 500;
60
61type UnstampedEvent = OrchestrationV2DomainEvent extends infer Event
62 ? Event extends OrchestrationV2DomainEvent
63 ? Omit<Event, "id" | "occurredAt">
64 : never
65 : never;
66
67interface Scenario {
68 readonly settled: number;
69 readonly active: number;
70}
71
72interface Seeded {
73 readonly unheldQueuedThreads: number;
74 readonly waitingThreads: number;
75}
76
77const seedScenario = Effect.fn(function* (scenario: Scenario) {
78 const projections = yield* ProjectionStore.ProjectionStoreV2;
79 const outbox = yield* EffectOutbox.EffectOutboxV2;
80 const sql = yield* SqlClient.SqlClient;
81 const now = yield* DateTime.now;
82 let eventIndex = 0;
83 const apply = (event: UnstampedEvent) =>
84 projections.apply({
85 ...event,
86 id: EventId.make(`event:bench:${eventIndex++}`),
87 occurredAt: now,
88 } as OrchestrationV2DomainEvent);
89
90 const thread = (id: ThreadId, overrides: Partial<OrchestrationV2AppThread> = {}) =>
91 apply({
92 type: "thread.created",
93 threadId: id,
94 payload: {
95 createdBy: "user",
96 creationSource: "web",
97 id,
98 projectId,
99 title: id,
100 providerInstanceId,
101 modelSelection,
102 runtimeMode: "full-access",
103 interactionMode: "default",
104 branch: null,
105 worktreePath: null,
106 activeProviderThreadId: null,
107 lineage: { parentThreadId: null, relationshipToParent: null, rootThreadId: id },
108 forkedFrom: null,
109 createdAt: now,
110 updatedAt: now,
111 archivedAt: null,
112 settledOverride: null,
113 settledAt: null,
114 lastVisitedAt: null,
115 deletedAt: null,
116 ...overrides,
117 },
118 });
119
120 const run = (
121 threadId: ThreadId,
122 ordinal: number,
123 status: OrchestrationV2Run["status"],
124 overrides: Partial<OrchestrationV2Run> = {},
125 ) => {
126 const runId = RunId.make(`run:${threadId}:${ordinal}`);
127 return apply({
128 type: "run.created",
129 threadId,
130 runId,
131 payload: {
132 id: runId,
133 threadId,
134 ordinal,
135 providerInstanceId,
136 modelSelection,
137 providerThreadId: null,
138 userMessageId: MessageId.make(`message:${runId}`),
139 rootNodeId: null,
140 activeAttemptId: null,
141 status,
142 requestedAt: now,
143 startedAt: status === "queued" ? null : now,
144 completedAt: status === "completed" ? now : null,
145 checkpointId: null,
146 contextHandoffId: null,
147 ...overrides,
148 },
149 }).pipe(Effect.as(runId));
150 };
151
152 const commandItem = (input: {
153 readonly threadId: ThreadId;
154 readonly runId: RunId;
155 readonly ordinal: number;
156 readonly status: "running" | "completed";
157 readonly nodeId?: NodeId;
158 readonly providerThreadId?: ProviderThreadId;
159 readonly providerTurnId?: ProviderTurnId;
160 }) =>
161 apply({
162 type: "turn-item.updated",
163 threadId: input.threadId,
164 runId: input.runId,
165 payload: {
166 id: TurnItemId.make(`item:${input.runId}:${input.ordinal}`),
167 threadId: input.threadId,
168 runId: input.runId,
169 nodeId: input.nodeId ?? null,
170 providerThreadId: input.providerThreadId ?? null,
171 providerTurnId: input.providerTurnId ?? null,
172 nativeItemRef: null,
173 parentItemId: null,
174 ordinal: input.ordinal,
175 type: "command_execution",
176 status: input.status,
177 title: `Command ${input.ordinal}`,
178 input: `echo ${input.ordinal}`,
179 output: input.status === "completed" ? `${input.ordinal}\n` : "",
180 ...(input.status === "completed" ? { exitCode: 0 } : {}),
181 startedAt: now,
182 completedAt: input.status === "completed" ? now : null,
183 updatedAt: now,
184 },
185 });
186
187 const settledThread = Effect.fn(function* (index: number) {
188 const threadId = ThreadId.make(`thread:bench:settled:${index}`);
189 yield* thread(threadId);
190 const runId = yield* run(threadId, 1, "completed");
191 for (let ordinal = 1; ordinal <= ITEMS_PER_SETTLED_THREAD; ordinal += 1) {
192 yield* commandItem({ threadId, runId, ordinal, status: "completed" });
193 }
194 if (index % 20 === 0) {
195 const queueHeld = index % 40 === 0;
196 yield* run(threadId, 2, "queued", { queueHeld });
197 return !queueHeld;
198 }
199 return false;
200 });
201
202 const activeThread = Effect.fn(function* (index: number) {
203 const threadId = ThreadId.make(`thread:bench:active:${index}`);
204 const providerSessionId = ProviderSessionId.make(`session:bench:${index}`);
205 const providerThreadId = ProviderThreadId.make(`provider-thread:bench:${index}`);
206 const runId = RunId.make(`run:${threadId}:1`);
207 const attemptId = RunAttemptId.make(`attempt:bench:${index}`);
208 const nodeId = NodeId.make(`node:bench:${index}`);
209 const providerTurnId = ProviderTurnId.make(`provider-turn:bench:${index}`);
210 yield* thread(threadId, { activeProviderThreadId: providerThreadId });
211 yield* apply({
212 type: "provider-session.attached",
213 threadId,
214 driver,
215 providerInstanceId,
216 payload: {
217 id: providerSessionId,
218 driver,
219 providerInstanceId,
220 status: "ready",
221 cwd: "/workspace",
222 model: modelSelection.model,
223 capabilities: CodexProviderCapabilitiesV2,
224 createdAt: now,
225 updatedAt: now,
226 lastError: null,
227 },
228 });
229 yield* apply({
230 type: "provider-thread.updated",
231 threadId,
232 driver,
233 providerInstanceId,
234 payload: {
235 id: providerThreadId,
236 appThreadId: threadId,
237 ownerNodeId: null,
238 driver,
239 providerInstanceId,
240 providerSessionId,
241 nativeThreadRef: { driver, nativeId: `native:bench:${index}`, strength: "strong" },
242 nativeConversationHeadRef: null,
243 status: "active",
244 firstRunOrdinal: 1,
245 lastRunOrdinal: 1,
246 handoffIds: [],
247 forkedFrom: null,
248 createdAt: now,
249 updatedAt: now,
250 pendingBackgroundTasks: [],
251 },
252 });
253 yield* run(threadId, 1, "running", {
254 providerThreadId,
255 rootNodeId: nodeId,
256 activeAttemptId: attemptId,
257 });
258 yield* apply({
259 type: "run-attempt.created",
260 threadId,
261 runId,
262 payload: {
263 id: attemptId,
264 runId,
265 attemptOrdinal: 1,
266 rootNodeId: nodeId,
267 providerInstanceId,
268 providerThreadId,
269 providerTurnId,
270 reason: "initial",
271 status: "running",
272 startedAt: now,
273 completedAt: null,
274 },
275 });
276 yield* apply({
277 type: "node.updated",
278 threadId,
279 runId,
280 nodeId,
281 providerInstanceId,
282 payload: {
283 id: nodeId,
284 threadId,
285 runId,
286 parentNodeId: null,
287 rootNodeId: nodeId,
288 kind: "root_turn",
289 status: "running",
290 countsForRun: true,
291 providerThreadId,
292 providerTurnId,
293 nativeItemRef: null,
294 runtimeRequestId: null,
295 checkpointScopeId: null,
296 startedAt: now,
297 completedAt: null,
298 },
299 });
300 yield* apply({
301 type: "provider-turn.updated",
302 threadId,
303 runId,
304 nodeId,
305 providerInstanceId,
306 payload: {
307 id: providerTurnId,
308 providerThreadId,
309 nodeId,
310 runAttemptId: attemptId,
311 nativeTurnRef: { driver, nativeId: `native-turn:bench:${index}`, strength: "strong" },
312 ordinal: 1,
313 status: "running",
314 startedAt: now,
315 completedAt: null,
316 },
317 });
318 for (let ordinal = 1; ordinal <= OPEN_ITEMS_PER_ACTIVE_THREAD; ordinal += 1) {
319 yield* commandItem({
320 threadId,
321 runId,
322 ordinal,
323 status: "running",
324 nodeId,
325 providerThreadId,
326 providerTurnId,
327 });
328 }
329 });
330
331 const waitingThread = Effect.fn(function* (index: number) {
332 const threadId = ThreadId.make(`thread:bench:waiting:${index}`);
333 yield* thread(threadId);
334 yield* run(threadId, 1, "completed");
335 const runId = yield* run(threadId, 2, "waiting");
336 yield* outbox.enqueue([
337 {
338 id: `effect:bench:checkpoint:${runId}`,
339 commandId: CommandId.make(`command:effect:checkpoint.capture:${runId}`),
340 threadId,
341 request: {
342 type: "checkpoint.capture",
343 runId,
344 scopeId: CheckpointScopeId.make(`scope:bench:${index}`),
345 },
346 },
347 ]);
348 });
349
350 let unheldQueuedThreads = 0;
351 for (let start = 0; start < scenario.settled; start += SEED_BATCH) {
352 const end = Math.min(scenario.settled, start + SEED_BATCH);
353 yield* sql.withTransaction(
354 Effect.gen(function* () {
355 for (let index = start; index < end; index += 1) {
356 if (yield* settledThread(index)) unheldQueuedThreads += 1;
357 }
358 }),
359 );
360 }
361 yield* sql.withTransaction(
362 Effect.gen(function* () {
363 for (let index = 0; index < scenario.active; index += 1) yield* activeThread(index);
364 for (let index = 0; index < WAITING_THREADS; index += 1) yield* waitingThread(index);
365 }),
366 );
367 return { unheldQueuedThreads, waitingThreads: WAITING_THREADS } satisfies Seeded;
368});
369
370const timed = <A, E, R>(effect: Effect.Effect<A, E, R>) =>
371 Effect.gen(function* () {
372 const start = performance.now();
373 const value = yield* effect;
374 return [value, performance.now() - start] as const;
375 });
376
377const continuationEffectCount = Effect.gen(function* () {
378 const sql = yield* SqlClient.SqlClient;
379 const rows = yield* sql<{ readonly count: number }>`
380 SELECT COUNT(*) AS count FROM orchestration_v2_effect_outbox
381 WHERE effect_id LIKE 'effect:restart-continuation:%' AND status = 'pending'
382 `;
383 return Number(rows[0]?.count ?? 0);
384});
385
386interface Measurement {
387 readonly settled: number;
388 readonly active: number;
389 readonly seedMs: number;
390 readonly candidates: number;
391 readonly selectMs: number;
392 readonly prepareMs: number;
393 readonly shutdownMs: number;
394 readonly startupAfterShutdownMs: number;
395 readonly crashRecoverMs: number;
396 readonly secondRecoverMs: number;
397}
398
399const measureGraceful = Effect.fn(function* (scenario: Scenario) {
400 const [seeded, seedMs] = yield* timed(seedScenario(scenario));
401 const projections = yield* ProjectionStore.ProjectionStoreV2;
402 const recovery = yield* ProviderRuntimeRecovery.ProviderRuntimeRecoveryService;
403 const [candidates, selectMs] = yield* timed(projections.getRecoveryThreadIds("runtime"));
404 assert.equal(
405 candidates.length,
406 scenario.active + seeded.unheldQueuedThreads + seeded.waitingThreads,
407 "runtime recovery candidates",
408 );
409 const [, prepareMs] = yield* timed(recovery.prepareForShutdown);
410 assert.equal(yield* continuationEffectCount, scenario.active, "prepared continuations");
411 const [, shutdownMs] = yield* timed(recovery.reconcile("shutdown"));
412 const [, startupAfterShutdownMs] = yield* timed(recovery.recover);
413 assert.equal(yield* continuationEffectCount, scenario.active, "continuations after boot");
414 return {
415 seedMs,
416 candidates: candidates.length,
417 selectMs,
418 prepareMs,
419 shutdownMs,
420 startupAfterShutdownMs,
421 };
422});
423
424const measureCrash = Effect.fn(function* (scenario: Scenario) {
425 yield* seedScenario(scenario);
426 const recovery = yield* ProviderRuntimeRecovery.ProviderRuntimeRecoveryService;
427 const [summary, crashRecoverMs] = yield* timed(recovery.recover);
428 assert.equal(summary.terminalizedRuns, scenario.active, "terminalized active runs");
429 assert.equal(summary.stoppedSessions, scenario.active, "stopped active sessions");
430 assert.equal(yield* continuationEffectCount, scenario.active, "recorded continuations");
431 const [, secondRecoverMs] = yield* timed(recovery.recover);
432 assert.equal(yield* continuationEffectCount, scenario.active, "second recover is idempotent");
433 return { crashRecoverMs, secondRecoverMs };
434});
435
436const measure = Effect.fn(function* (scenario: Scenario) {
437 const graceful = yield* measureGraceful(scenario).pipe(Effect.provide(Layer.fresh(layerTest)));
438 const crash = yield* measureCrash(scenario).pipe(Effect.provide(Layer.fresh(layerTest)));
439 return { ...scenario, ...graceful, ...crash } satisfies Measurement;
440});
441
442const formatTable = (rows: ReadonlyArray<Measurement>) => {
443 const ms = (value: number) => value.toFixed(1);
444 const perActive = (value: number, active: number) => (value / Math.max(active, 1)).toFixed(2);
445 const header = [
446 "N",
447 "A",
448 "seed",
449 "cand",
450 "select",
451 "prepare",
452 "prep/A",
453 "shutdown",
454 "boot-after",
455 "crash-recover",
456 "recover/A",
457 "recover-2",
458 ];
459 const lines = rows.map((row) => [
460 String(row.settled),
461 String(row.active),
462 ms(row.seedMs),
463 String(row.candidates),
464 ms(row.selectMs),
465 ms(row.prepareMs),
466 perActive(row.prepareMs, row.active),
467 ms(row.shutdownMs),
468 ms(row.startupAfterShutdownMs),
469 ms(row.crashRecoverMs),
470 perActive(row.crashRecoverMs, row.active),
471 ms(row.secondRecoverMs),
472 ]);
473 const widths = header.map((cell, column) =>
474 Math.max(cell.length, ...lines.map((line) => line[column]!.length)),
475 );
476 return [header, ...lines]
477 .map((line) => line.map((cell, column) => cell.padStart(widths[column]!)).join(" "))
478 .join("\n");
479};
480
481it.live(
482 "restart recovery records one continuation per active thread and is idempotent",
483 () =>
484 Effect.gen(function* () {
485 const row = yield* measure({ settled: 500, active: 20 });
486 yield* Console.log(`provider runtime recovery (ms)\n${formatTable([row])}`);
487 }),
488 60_000,
489);
490
491it.live.skipIf(process.env.T3_BENCH_RECOVERY !== "1")(
492 "restart recovery scales with active threads, not settled history",
493 () =>
494 Effect.gen(function* () {
495 const rows: Array<Measurement> = [];
496 for (const settled of [5_000, 50_000]) {
497 for (const active of [10, 100, 1_000]) {
498 rows.push(yield* measure({ settled, active }));
499 yield* Console.log(`provider runtime recovery (ms)\n${formatTable(rows)}`);
500 }
501 }
502 }),
503 3_600_000,
504);