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

CheckpointRestoreSafety.test.ts

228 lines9.0 KB

1import * as NodeServices from "@effect/platform-node/NodeServices";
2import { assert, it } from "@effect/vitest";
3import {
4 CheckpointId,
5 CheckpointScopeId,
6 ProjectId,
7 ProviderInstanceId,
8 ProviderSessionId,
9 ProviderThreadId,
10 ThreadId,
11} from "@t3tools/contracts";
12import * as Effect from "effect/Effect";
13import * as FileSystem from "effect/FileSystem";
14import * as Layer from "effect/Layer";
15import * as Option from "effect/Option";
16import * as Path from "effect/Path";
17import { symlinksSupported } from "@t3tools/shared/testing/symlinks";
18import * as ServerConfig from "../config.ts";
19import * as ServerSettings from "../serverSettings.ts";
20import * as GitWorkflowService from "../git/GitWorkflowService.ts";
21import * as CheckpointRollbackService from "./CheckpointRollbackService.ts";
22import { isCheckpointRestoreIsolated } from "./CheckpointRestoreSafety.ts";
23import * as ThreadCommandExecutor from "./ThreadCommandExecutor.ts";
24import { CheckpointServiceV2 } from "./CheckpointService.ts";
25import { EventSinkV2 } from "./EventSink.ts";
26import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
27import { ProjectionStoreV2, type ProjectionCheckpointRollbackContext } from "./ProjectionStore.ts";
28import * as ProjectStore from "./ProjectStore.ts";
29import { ProviderSessionManagerV2 } from "./ProviderSessionManager.ts";
30import { RuntimePolicyV2 } from "./RuntimePolicy.ts";
31​
32it.effect.each([
33 "nested",
34 "ancestor",
35 "archived-nested",
36 ...(symlinksSupported ? (["aliased-nested"] as const) : []),
37 "project",
38 "provider",
39 "scope",
40 "sibling",
41 "stopped-provider",
42 "errored-provider",
43 "shared-provider",
44 "conversation",
45] as const)("preserves overlapping workspace files, owner=%s", (owner) =>
46 Effect.gen(function* () {
47 const fs = yield* FileSystem.FileSystem;
48 const path = yield* Path.Path;
49 const parent = yield* fs.makeTempDirectoryScoped({ prefix: "t3-v2-restore-" });
50 const cwd = path.join(parent, "worktree");
51 const nested = path.join(cwd, "nested");
52 const sibling = path.join(parent, "worktree2");
53 yield* fs.makeDirectory(nested, { recursive: true });
54 yield* fs.makeDirectory(sibling);
55 const otherFile = path.join(nested, "other-thread.txt");
56 yield* fs.writeFileString(otherFile, "other thread's uncommitted work");
57 const alias = path.join(parent, "alias");
58 if (owner === "aliased-nested") yield* fs.symlink(nested, alias);
59 const threadId = ThreadId.make("restore-current");
60 const otherId = ThreadId.make("restore-other");
61 const projectId = ProjectId.make("restore-project");
62 const providerThreadId = ProviderThreadId.make("restore-provider");
63 const providerSessionId = ProviderSessionId.make("restore-session");
64 const instanceId = ProviderInstanceId.make("restore-instance");
65 const checkpointId = CheckpointId.make("restore-checkpoint");
66 const scopeId = CheckpointScopeId.make("restore-scope");
67 const calls: string[] = [];
68 const providerThread = {
69 id: providerThreadId,
70 providerSessionId,
71 providerInstanceId: instanceId,
72 };
73 const otherThread = {
74 id: otherId,
75 projectId,
76 deletedAt: null,
77 worktreePath:
78 owner === "project"
79 ? null
80 : owner === "ancestor" || owner === "conversation"
81 ? parent
82 : owner === "nested" || owner === "archived-nested"
83 ? nested
84 : owner === "aliased-nested"
85 ? alias
86 : sibling,
87 };
88 const projection = {
89 thread: {
90 id: threadId,
91 projectId,
92 worktreePath: cwd,
93 activeProviderThreadId: providerThreadId,
94 modelSelection: { instanceId, model: "test" },
95 },
96 providerThread,
97 providerSession: undefined,
98 providerTurns: [],
99 rootNodes: [],
100 targetAttempt: undefined,
101 rolledBackAttemptIds: [],
102 staleCheckpoints: [],
103 checkpoint: { id: checkpointId, scopeId, status: "ready", appRunOrdinal: null },
104 scope: { id: scopeId, cwd },
105 runsToRollback: [{ id: "later-run", ordinal: 1, status: "completed", rootNodeId: null }],
106 } as unknown as ProjectionCheckpointRollbackContext;
107 const layerTest = CheckpointRollbackService.layer.pipe(
108 Layer.provide(
109 Layer.mergeAll(
110 NodeServices.layer,
111 Layer.mock(ServerConfig.ServerConfig)({ worktreesDir: "/synthetic-worktrees" } as never),
112 ServerSettings.layerTest(),
113 ThreadCommandExecutor.layer,
114 IdAllocator.layer,
115 Layer.mock(GitWorkflowService.GitWorkflowService)({}),
116 Layer.mock(ProjectStore.ProjectStoreV2)({
117 get: () => Effect.succeed(Option.some({ workspaceRoot: parent } as never)),
118 }),
119 Layer.mock(ProjectionStoreV2)({
120 getThread: () => Effect.succeed(projection.thread),
121 getCheckpointRollbackContext: () => Effect.succeed(projection),
122 getShellSnapshot: () =>
123 Effect.succeed({
124 schemaVersion: 1,
125 snapshotSequence: 0,
126 threads: owner === "archived-nested" ? [] : ([otherThread] as never),
127 archivedThreads: owner === "archived-nested" ? ([otherThread] as never) : [],
128 }),
129 getCheckpointContext: () =>
130 Effect.succeed({
131 runs: [],
132 checkpoints: [],
133 checkpointScopes: owner === "scope" ? ([{ cwd: nested }] as never) : [],
134 }),
135 getThreadProviderContext: () =>
136 Effect.succeed({
137 thread: otherThread as never,
138 providerThreads: [],
139 providerSessions: [
140 "provider",
141 "stopped-provider",
142 "errored-provider",
143 "shared-provider",
144 ].includes(owner)
145 ? ([
146 {
147 cwd: owner === "shared-provider" ? cwd : nested,
148 status:
149 owner === "provider" || owner === "shared-provider"
150 ? "running"
151 : owner === "errored-provider"
152 ? "error"
153 : "stopped",
154 capabilities: {
155 sessions: {
156 supportsMultipleProviderThreadsPerSession: owner === "shared-provider",
157 },
158 },
159 },
160 ] as never)
161 : [],
162 }),
163 }),
164 Layer.mock(CheckpointServiceV2)({
165 restore: () =>
166 Effect.gen(function* () {
167 calls.push("files");
168 yield* fs.remove(otherFile).pipe(Effect.orDie);
169 }),
170 }),
171 Layer.mock(EventSinkV2)({ write: () => Effect.succeed([]) }),
172 Layer.mock(ProviderSessionManagerV2)({
173 open: () =>
174 Effect.succeed({
175 rollbackThread: () =>
176 Effect.sync(() => {
177 calls.push("provider");
178 return { providerThread };
179 }),
180 } as never),
181 }),
182 Layer.mock(RuntimePolicyV2)({ resolve: () => Effect.succeed({} as never) }),
183 ),
184 ),
185 );
186 const service = yield* CheckpointRollbackService.CheckpointRollbackServiceV2.pipe(
187 Effect.provide(layerTest),
188 );
189 const restoreFiles = owner !== "conversation";
190 const rejected = !["sibling", "stopped-provider", "shared-provider", "conversation"].includes(
191 owner,
192 );
193 if (rejected) {
194 const error = yield* service
195 .execute({ threadId, providerThreadId, checkpointId, scopeId, restoreFiles })
196 .pipe(Effect.flip);
197 assert.equal(error.reason, "shared-workspace");
198 assert.deepEqual(calls, []);
199 assert.equal(yield* fs.readFileString(otherFile), "other thread's uncommitted work");
200 } else {
201 yield* service.execute({ threadId, providerThreadId, checkpointId, scopeId, restoreFiles });
202 assert.deepEqual(calls, restoreFiles ? ["provider", "files"] : ["provider"]);
203 assert.equal(yield* fs.exists(otherFile), !restoreFiles);
204 }
205 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
206);
207​
208it.effect("lets rollback recreate a worktree storage cleanup removed", () =>
209 Effect.gen(function* () {
210 const fileSystem = yield* FileSystem.FileSystem;
211 const path = yield* Path.Path;
212 const parent = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-v2-restore-removed-" });
213 const worktreePath = path.join(parent, "worktree");
214 const isolated = yield* isCheckpointRestoreIsolated(
215 { id: ThreadId.make("restore-removed"), worktreePath },
216 { cwd: worktreePath },
217 {
218 fileSystem,
219 path,
220 projections: {
221 getShellSnapshot: () => Effect.succeed({ threads: [], archivedThreads: [] }),
222 } as never,
223 projects: {} as never,
224 },
225 );
226 assert.isTrue(isolated);
227 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
228);