Open History to see the last commit
1import { assert, it } from "@effect/vitest";
2import { CheckpointScopeId, CommandId, GitCommandError, RunId, ThreadId } from "@t3tools/contracts";
3import * as Deferred from "effect/Deferred";
4import * as Effect from "effect/Effect";
5import * as Fiber from "effect/Fiber";
6import * as Layer from "effect/Layer";
7import * as Option from "effect/Option";
8
9import * as SqlitePersistence from "../persistence/Sqlite.ts";
10import * as ProjectEnrichment from "../project/ProjectEnrichmentService.ts";
11import * as ProjectService from "../project/ProjectService.ts";
12import * as PullRequestService from "../pullRequest/PullRequestService.ts";
13import * as ServerSettings from "../serverSettings.ts";
14import * as VcsStatusBroadcaster from "../vcs/VcsStatusBroadcaster.ts";
15import * as WorkspaceEntries from "../workspace/WorkspaceEntries.ts";
16import * as CheckpointCapture from "./CheckpointCaptureService.ts";
17import * as CheckpointRollback from "./CheckpointRollbackService.ts";
18import * as EffectOutbox from "./EffectOutbox.ts";
19import * as EffectWorker from "./EffectWorker.ts";
20import * as ProjectionStore from "./ProjectionStore.ts";
21import * as ProviderSessions from "./ProviderSessionManager.ts";
22import * as ProviderTurnControl from "./ProviderTurnControlService.ts";
23import * as ProviderTurnStart from "./ProviderTurnStartService.ts";
24import * as RunFinalization from "./RunFinalizationService.ts";
25import * as RuntimeRequests from "./RuntimeRequestService.ts";
26import * as ThreadManagement from "./ThreadManagementService.ts";
27import * as ThreadTitles from "./ThreadTitleRegenerationService.ts";
28
29const threadId = ThreadId.make("thread:finalization-queue");
30const runId = RunId.make("run:finalization-queue");
31const scopeId = CheckpointScopeId.make("scope:finalization-queue");
32const captureEffect = {
33 id: "effect:finalization-queue:capture",
34 commandId: CommandId.make("command:finalization-queue:capture"),
35 threadId,
36 request: { type: "checkpoint.capture" as const, runId, scopeId },
37};
38const startEffect = {
39 id: "effect:finalization-queue:start",
40 commandId: CommandId.make("command:finalization-queue:start"),
41 threadId,
42 request: { type: "provider-turn.start" as const, runId: RunId.make("run:next") },
43};
44
45const makeWorker = (
46 calls: string[],
47 capture: Effect.Effect<void, CheckpointCapture.CheckpointCaptureExecutionError>,
48) => {
49 const projections = Layer.mock(ProjectionStore.ProjectionStoreV2)({
50 getCheckpointContext: () =>
51 Effect.succeed({
52 runs: [],
53 checkpointScopes: [{ id: scopeId, runId, kind: "root_run" as const, cwd: "/repo" }],
54 checkpoints: [],
55 }),
56 getThreadShell: () => Effect.succeed(null),
57 });
58 const observer = RunFinalization.layerObserver.pipe(
59 Layer.provide(
60 Layer.mergeAll(
61 projections,
62 Layer.mock(ProjectService.ProjectService)({}),
63 Layer.mock(ProjectEnrichment.ProjectEnrichmentService)({}),
64 Layer.mock(WorkspaceEntries.WorkspaceEntries)({ refresh: () => Effect.void }),
65 Layer.mock(PullRequestService.PullRequestService)({ refreshAfterTurn: () => Effect.void }),
66 Layer.mock(VcsStatusBroadcaster.VcsStatusBroadcaster)({
67 refreshLocalStatus: () =>
68 Effect.gen(function* () {
69 calls.push("refresh");
70 return yield* new GitCommandError({
71 operation: "statusDetailsLocal",
72 command: "git",
73 cwd: "/repo",
74 detail: "VCS process timed out after 30000ms",
75 });
76 }),
77 }),
78 ),
79 ),
80 );
81 const finalization = RunFinalization.layer.pipe(
82 Layer.provide(
83 Layer.mergeAll(
84 projections,
85 observer,
86 Layer.mock(CheckpointCapture.CheckpointCaptureServiceV2)({
87 execute: () => Effect.sync(() => calls.push("capture")).pipe(Effect.andThen(capture)),
88 }),
89 ),
90 ),
91 );
92 const executor = EffectWorker.layerExecutor.pipe(
93 Layer.provide(
94 Layer.mergeAll(
95 finalization,
96 Layer.mock(ProviderSessions.ProviderSessionManagerV2)({}),
97 Layer.mock(ProviderTurnControl.ProviderTurnControlServiceV2)({}),
98 Layer.mock(CheckpointRollback.CheckpointRollbackServiceV2)({}),
99 Layer.mock(RuntimeRequests.RuntimeRequestServiceV2)({}),
100 Layer.mock(ThreadTitles.ThreadTitleRegenerationService)({}),
101 Layer.mock(ThreadManagement.ThreadManagementService)({
102 recoverDelegatedTask: () => Effect.void,
103 }),
104 Layer.mock(ProjectionStore.ProjectionStoreV2)({}),
105 ServerSettings.layerTest(),
106 Layer.mock(ProviderTurnStart.ProviderTurnStartServiceV2)({
107 start: () => Effect.sync(() => calls.push("start")).pipe(Effect.asVoid),
108 }),
109 ),
110 ),
111 );
112 const outbox = EffectOutbox.layer.pipe(Layer.provide(SqlitePersistence.layerMemory));
113 return Layer.fresh(EffectWorker.layer.pipe(Layer.provideMerge(Layer.merge(executor, outbox))));
114};
115
116it.effect.each([
117 ["starts the next turn after a post-capture Git status failure", false],
118 ["keeps the next turn queued when checkpoint capture fails", true],
119] as const)("%s", ([, captureFails]) => {
120 const calls: string[] = [];
121 const checkpointFailure = new CheckpointCapture.CheckpointCaptureExecutionError({
122 threadId,
123 runId,
124 scopeId,
125 cause: "checkpoint storage unavailable",
126 });
127 return Effect.gen(function* () {
128 const queue = yield* EffectOutbox.EffectOutboxV2;
129 const effectWorker = yield* EffectWorker.OrchestrationEffectWorkerV2;
130 yield* queue.enqueue([captureEffect, startEffect]);
131
132 assert.equal(yield* effectWorker.drain(2), captureFails ? 1 : 2);
133 const captured = Option.getOrThrow(yield* queue.get("effect:finalization-queue:capture"));
134 const started = Option.getOrThrow(yield* queue.get("effect:finalization-queue:start"));
135 assert.equal(captured.status, captureFails ? "pending" : "succeeded");
136 assert.equal(captured.attemptCount, 1);
137 assert.equal(started.status, captureFails ? "pending" : "succeeded");
138 assert.equal(started.attemptCount, captureFails ? 0 : 1);
139 assert.deepEqual(calls, captureFails ? ["capture"] : ["capture", "refresh", "start"]);
140 if (captureFails) assert.include(captured.lastError ?? "", "checkpoint storage unavailable");
141 else assert.equal(captured.lastError, null);
142 }).pipe(Effect.provide(makeWorker(calls, captureFails ? checkpointFailure : Effect.void)));
143});
144
145// A run completes before its capture, so the next turn's start is enqueued while capture runs.
146it.effect("keeps a next turn started during capture behind that capture", () => {
147 const calls: string[] = [];
148 return Effect.gen(function* () {
149 const captureStarted = yield* Deferred.make<void>();
150 const releaseCapture = yield* Deferred.make<void>();
151 const capture = Deferred.succeed(captureStarted, undefined).pipe(
152 Effect.andThen(Deferred.await(releaseCapture)),
153 );
154 return yield* Effect.gen(function* () {
155 const queue = yield* EffectOutbox.EffectOutboxV2;
156 const effectWorker = yield* EffectWorker.OrchestrationEffectWorkerV2;
157 yield* queue.enqueue([captureEffect]);
158 const draining = yield* Effect.forkChild(effectWorker.drain(2));
159 yield* Deferred.await(captureStarted);
160
161 yield* queue.enqueue([startEffect]);
162 assert.isTrue(Option.isNone(yield* queue.claimNext({ workerId: "second-slot" })));
163 assert.deepEqual(calls, ["capture"]);
164
165 yield* Deferred.succeed(releaseCapture, undefined);
166 assert.equal(yield* Fiber.join(draining), 2);
167 assert.deepEqual(calls, ["capture", "refresh", "start"]);
168 }).pipe(Effect.provide(makeWorker(calls, capture)));
169 });
170});