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

CheckpointRestoreSafety.test.ts

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