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

ProjectService.deletion.test.ts

422 lines17.6 KB

1import * as NodeServices from "@effect/platform-node/NodeServices";
2import { assert, it } from "@effect/vitest";
3import {
4 CommandId,
5 EventId,
6 type OrchestrationV2AppThread,
7 ProjectId,
8 ProviderInstanceId,
9 ThreadId,
10} from "@t3tools/contracts";
11import * as DateTime from "effect/DateTime";
12import * as Effect from "effect/Effect";
13import * as Layer from "effect/Layer";
14import * as Option from "effect/Option";
15import * as Schema from "effect/Schema";
16import { TestClock } from "effect/testing";
17import * as SqlClient from "effect/unstable/sql/SqlClient";
18​
19import { ServerConfig } from "../config.ts";
20import { OrchestrationLayerLive } from "../orchestration/runtimeLayer.ts";
21import { OrchestrationEffectRequestV2 } from "../orchestration-v2/EffectOutbox.ts";
22import {
23 EventSinkV2,
24 type EventSinkV2Shape,
25 EventSinkWriteError,
26 layer as eventSinkLayer,
27} from "../orchestration-v2/EventSink.ts";
28import { layer as eventStoreLayer } from "../orchestration-v2/EventStore.ts";
29import { layer as idAllocatorLayer } from "../orchestration-v2/IdAllocator.ts";
30import {
31 LegacyV1ThreadImporter,
32 layer as legacyImporterLayer,
33} from "../orchestration-v2/LegacyV1ThreadImporter.ts";
34import {
35 ProjectionMaintenanceV2,
36 layer as projectionMaintenanceLayer,
37} from "../orchestration-v2/ProjectionMaintenance.ts";
38import {
39 ProjectionStoreV2,
40 layer as projectionStoreLayer,
41} from "../orchestration-v2/ProjectionStore.ts";
42import { layer as threadCommandExecutorLayer } from "../orchestration-v2/ThreadCommandExecutor.ts";
43import { ProjectionProjectRepositoryLive } from "../persistence/Layers/ProjectionProjects.ts";
44import { SqlitePersistenceMemory } from "../persistence/Layers/Sqlite.ts";
45import * as WorkspacePaths from "../workspace/WorkspacePaths.ts";
46import * as ProjectEnrichmentService from "./ProjectEnrichmentService.ts";
47import * as ProjectFaviconResolver from "./ProjectFaviconResolver.ts";
48import * as ProjectService from "./ProjectService.ts";
49import * as RepositoryIdentityResolver from "./RepositoryIdentityResolver.ts";
50​
51const eventPersistenceLayer = eventSinkLayer.pipe(
52 Layer.provideMerge(Layer.merge(eventStoreLayer, projectionStoreLayer)),
53);
54const servicesLayer = Layer.mergeAll(
55 legacyImporterLayer.pipe(Layer.provideMerge(eventPersistenceLayer)),
56 projectionMaintenanceLayer.pipe(Layer.provide(eventPersistenceLayer)),
57 OrchestrationLayerLive,
58 ProjectionProjectRepositoryLive,
59 idAllocatorLayer,
60 threadCommandExecutorLayer,
61 Layer.succeed(WorkspacePaths.WorkspacePaths, {
62 normalizeWorkspaceRoot: (workspaceRoot) => Effect.succeed(workspaceRoot),
63 resolveRelativePathWithinRoot: ({ workspaceRoot, relativePath }) =>
64 Effect.succeed({ absolutePath: `${workspaceRoot}/${relativePath}`, relativePath }),
65 }),
66).pipe(
67 Layer.provideMerge(
68 ProjectEnrichmentService.layer.pipe(
69 Layer.provide(
70 Layer.merge(
71 Layer.succeed(RepositoryIdentityResolver.RepositoryIdentityResolver, {
72 resolve: () => Effect.succeed(null),
73 }),
74 Layer.succeed(ProjectFaviconResolver.ProjectFaviconResolver, {
75 resolvePath: () => Effect.succeed(null),
76 }),
77 ),
78 ),
79 ),
80 ),
81);
82const databaseLayer = SqlitePersistenceMemory.pipe(
83 Layer.provideMerge(ServerConfig.layerTest(process.cwd(), { prefix: "project-deletion-test-" })),
84 Layer.provideMerge(NodeServices.layer),
85);
86const decodeEffectRequest = Schema.decodeUnknownEffect(
87 Schema.fromJsonString(OrchestrationEffectRequestV2),
88);
89​
90const seedProject = Effect.fn("ProjectDeletionTest.seedProject")(function* (projectId: ProjectId) {
91 const sql = yield* SqlClient.SqlClient;
92 yield* sql`
93 INSERT INTO projection_projects (
94 project_id, title, workspace_root, default_model_selection_json,
95 scripts_json, created_at, updated_at, deleted_at
96 ) VALUES (
97 ${projectId}, 'Deletion test', ${`/work/${projectId}`}, NULL,
98 '[]', '2026-01-01T00:00:00.000Z', '2026-01-01T00:00:00.000Z', NULL
99 )
100 `;
101});
102​
103function nativeThreadCreated(projectId: ProjectId, threadId: ThreadId) {
104 const createdAt = DateTime.makeUnsafe("2026-01-01T00:00:00.000Z");
105 const providerInstanceId = ProviderInstanceId.make("codex");
106 const payload: OrchestrationV2AppThread = {
107 createdBy: "user",
108 creationSource: "web",
109 id: threadId,
110 projectId,
111 title: threadId,
112 providerInstanceId,
113 modelSelection: { instanceId: providerInstanceId, model: "gpt-5" },
114 runtimeMode: "full-access",
115 interactionMode: "default",
116 branch: null,
117 worktreePath: null,
118 activeProviderThreadId: null,
119 lineage: { parentThreadId: null, relationshipToParent: null, rootThreadId: threadId },
120 forkedFrom: null,
121 createdAt,
122 updatedAt: createdAt,
123 archivedAt: null,
124 settledOverride: null,
125 settledAt: null,
126 lastVisitedAt: null,
127 deletedAt: null,
128 };
129 return {
130 id: EventId.make(`created:${threadId}`),
131 type: "thread.created" as const,
132 threadId,
133 providerInstanceId,
134 occurredAt: createdAt,
135 payload,
136 };
138​
139it.effect("retries a partial project deletion without repeating child events or cleanup", () =>
140 Effect.gen(function* () {
141 const sql = yield* SqlClient.SqlClient;
142 const projectId = ProjectId.make("project:partial-deletion");
143 const threadIds = [ThreadId.make("thread:delete-a"), ThreadId.make("thread:delete-b")] as const;
144 const commandId = CommandId.make("command:partial-project-delete");
145 yield* seedProject(projectId);
146 yield* TestClock.setTime(Date.parse("2026-09-04T12:00:00.000Z"));
147​
148 yield* Effect.gen(function* () {
149 const eventSink = yield* EventSinkV2;
150 const projections = yield* ProjectionStoreV2;
151 yield* eventSink.write({
152 events: threadIds.map((threadId) => nativeThreadCreated(projectId, threadId)),
153 });
154 const attempts: ThreadId[] = [];
155 const failingEventSink = EventSinkV2.of({
156 ...eventSink,
157 commitCommand: Effect.fn("ProjectDeletionTest.failSecondChild")(function* (
158 input: Parameters<EventSinkV2Shape["commitCommand"]>[0],
159 ) {
160 attempts.push(input.threadId);
161 if (attempts.length === 2) {
162 return yield* new EventSinkWriteError({
163 commandId: input.commandId,
164 eventCount: input.events.length,
165 cause: new Error("Injected failure for the second child"),
166 });
167 }
168 return yield* eventSink.commitCommand(input);
169 }),
170 });
171 const service = yield* ProjectService.make.pipe(
172 Effect.provideService(EventSinkV2, failingEventSink),
173 );
174 const input = { commandId, projectId, force: true };
175 const failure = yield* service.delete(input).pipe(Effect.flip);
176 assert.instanceOf(failure, ProjectService.ProjectOperationError);
177 if (failure._tag !== "ProjectOperationError") return assert.fail("Expected a child failure");
178 assert.equal(failure.operation, "delete-thread");
179 assert.lengthOf(attempts, 2);
180 const firstThreadId = attempts[0] ?? assert.fail("The first child was not attempted");
181 const failedThreadId = attempts[1] ?? assert.fail("The second child was not attempted");
182 assert.notEqual(firstThreadId, failedThreadId);
183 assert.isTrue(Option.isSome(yield* service.getById(projectId)));
184 assert.isNotNull((yield* projections.getThreadProjection(firstThreadId)).thread.deletedAt);
185 assert.isNull((yield* projections.getThreadProjection(failedThreadId)).thread.deletedAt);
186​
187 const readDeletions = sql<{
188 readonly sequence: number;
189 readonly stream_id: string;
190 readonly command_id: string;
191 readonly event_type: string;
192 }>`
193 SELECT sequence, stream_id, command_id, event_type
194 FROM orchestration_events
195 WHERE event_type IN ('thread.deleted', 'project.deleted')
196 AND stream_id IN (${threadIds[0]}, ${threadIds[1]}, ${projectId})
197 ORDER BY sequence ASC
198 `;
199 const readCleanup = sql<{
200 readonly effect_id: string;
201 readonly thread_id: string;
202 readonly command_id: string;
203 readonly effect_type: string;
204 }>`
205 SELECT effect_id, thread_id, command_id, effect_type
206 FROM orchestration_v2_effect_outbox
207 WHERE thread_id IN (${threadIds[0]}, ${threadIds[1]})
208 ORDER BY effect_id ASC
209 `;
210 const partialEvents = yield* readDeletions;
211 const partialCleanup = yield* readCleanup;
212 assert.lengthOf(partialEvents, 1);
213 assert.equal(partialEvents[0]?.stream_id, firstThreadId);
214 assert.equal(partialEvents[0]?.event_type, "thread.deleted");
215 assert.lengthOf(partialCleanup, 1);
216 assert.equal(partialCleanup[0]?.thread_id, firstThreadId);
217 assert.equal(partialCleanup[0]?.effect_type, "terminal.cleanup");
218​
219 const deletedProject = yield* service.delete(input);
220 assert.isNotNull(deletedProject.deletedAt);
221 assert.isTrue(Option.isNone(yield* service.getById(projectId)));
222 assert.deepEqual(attempts, [firstThreadId, failedThreadId, failedThreadId]);
223 for (const threadId of threadIds) {
224 assert.isNotNull((yield* projections.getThreadProjection(threadId)).thread.deletedAt);
225 }
226 const finalEvents = yield* readDeletions;
227 assert.deepEqual(
228 finalEvents.map((event) => [event.stream_id, event.event_type]),
229 [
230 [firstThreadId, "thread.deleted"],
231 [failedThreadId, "thread.deleted"],
232 [projectId, "project.deleted"],
233 ],
234 );
235 assert.deepEqual(finalEvents[0], partialEvents[0]);
236 assert.equal(finalEvents[2]?.command_id, commandId);
237 const finalCleanup = yield* readCleanup;
238 assert.lengthOf(finalCleanup, 2);
239 assert.deepEqual(
240 finalCleanup.filter((effect) => effect.thread_id === firstThreadId),
241 partialCleanup,
242 );
243 for (const threadId of threadIds) {
244 const expectedCommandId = `${commandId}:delete-thread:${threadId}`;
245 assert.deepEqual(
246 finalCleanup.filter((effect) => effect.thread_id === threadId),
247 [
248 {
249 effect_id: `effect:${expectedCommandId}:terminal.cleanup`,
250 thread_id: threadId,
251 command_id: expectedCommandId,
252 effect_type: "terminal.cleanup",
253 },
254 ],
255 );
256 }
257 }).pipe(Effect.provide(servicesLayer));
258 }).pipe(Effect.provide(databaseLayer)),
259);
260​
261it.effect(
262 "hydrates a migrated transcript before deleting its project and cleaning attachments",
263 () =>
264 Effect.gen(function* () {
265 const sql = yield* SqlClient.SqlClient;
266 const projectId = ProjectId.make("project:legacy-deletion");
267 const threadId = ThreadId.make("thread:legacy-deletion");
268 const commandId = CommandId.make("command:legacy-project-delete");
269 yield* seedProject(projectId);
270 yield* sql`
271 INSERT INTO projection_threads (
272 thread_id, project_id, title, model_selection_json,
273 runtime_mode, interaction_mode, branch, worktree_path, latest_turn_id,
274 created_at, updated_at, archived_at, deleted_at
275 ) VALUES (
276 ${threadId}, ${projectId}, 'Legacy thread', '{"instanceId":"codex","model":"gpt-5.4"}',
277 'full-access', 'default', NULL, NULL, NULL,
278 '2026-01-01T00:00:00.000Z', '2026-01-04T00:00:00.000Z', NULL, NULL
279 )
280 `;
281 yield* sql`
282 INSERT INTO projection_thread_messages (
283 message_id, thread_id, turn_id, role, text, attachments_json,
284 is_streaming, created_at, updated_at
285 ) VALUES
286 (
287 'message:legacy-delete:1', ${threadId}, NULL, 'user', 'First question with screenshot',
288 '[{"type":"image","id":"legacy_screenshot","name":"screenshot.png","mimeType":"image/png","sizeBytes":128}]',
289 0, '2026-01-01T01:00:00.000Z', '2026-01-01T01:00:00.000Z'
290 ),
291 (
292 'message:legacy-delete:2', ${threadId}, NULL, 'assistant', 'First answer', '[]',
293 0, '2026-01-02T01:00:00.000Z', '2026-01-02T01:00:00.000Z'
294 ),
295 (
296 'message:legacy-delete:3', ${threadId}, NULL, 'user', 'Follow-up question', '[]',
297 0, '2026-01-03T01:00:00.000Z', '2026-01-03T01:00:00.000Z'
298 ),
299 (
300 'message:legacy-delete:4', ${threadId}, NULL, 'assistant', 'Follow-up answer', '[]',
301 0, '2026-01-04T01:00:00.000Z', '2026-01-04T01:00:00.000Z'
302 )
303 `;
304 yield* TestClock.setTime(Date.parse("2026-09-04T12:00:00.000Z"));
305​
306 // Build the engine after seeding the legacy database, as on a real restart.
307 yield* Effect.gen(function* () {
308 const importer = yield* LegacyV1ThreadImporter;
309 const maintenance = yield* ProjectionMaintenanceV2;
310 const projections = yield* ProjectionStoreV2;
311 const service = yield* ProjectService.make;
312 assert.deepEqual(yield* importer.reconcileShells, {
313 importedThreadCount: 1,
314 importedMessageCount: 2,
315 });
316 assert.equal(yield* importer.pendingThreadCount, 1);
317 assert.isTrue((yield* maintenance.rebuild).valid);
318 const shellProjection = yield* projections.getThreadProjection(threadId);
319 assert.deepEqual(
320 shellProjection.messages.map((message) => message.id),
321 ["message:legacy-delete:3", "message:legacy-delete:4"],
322 );
323 assert.deepEqual(
324 shellProjection.messages.flatMap((message) => message.attachments),
325 [],
326 );
327​
328 const deletedProject = yield* service.delete({ commandId, projectId, force: true });
329 assert.isNotNull(deletedProject.deletedAt);
330 assert.isTrue(Option.isNone(yield* service.getById(projectId)));
331 const projection = yield* projections.getThreadProjection(threadId);
332 assert.isNotNull(projection.thread.deletedAt);
333 assert.lengthOf(projection.messages, 4);
334 assert.equal(yield* importer.pendingThreadCount, 0);
335 const rows = yield* sql<{
336 readonly legacy_deleted_at: string | null;
337 readonly v2_deleted_at: string | null;
338 readonly project_deleted_at: string | null;
339 }>`
340 SELECT legacy.deleted_at AS legacy_deleted_at,
341 v2.deleted_at AS v2_deleted_at,
342 project.deleted_at AS project_deleted_at
343 FROM projection_threads AS legacy
344 JOIN orchestration_v2_projection_threads AS v2 ON v2.thread_id = legacy.thread_id
345 JOIN projection_projects AS project ON project.project_id = legacy.project_id
346 WHERE legacy.thread_id = ${threadId}
347 `;
348 assert.lengthOf(rows, 1);
349 assert.isNotNull(rows[0]?.legacy_deleted_at);
350 assert.isNotNull(rows[0]?.v2_deleted_at);
351 assert.isNotNull(rows[0]?.project_deleted_at);
352​
353 const cleanup = yield* sql<{
354 readonly command_id: string;
355 readonly payload_json: string;
356 readonly status: string;
357 }>`
358 SELECT command_id, payload_json, status
359 FROM orchestration_v2_effect_outbox
360 WHERE thread_id = ${threadId} AND effect_type = 'attachment.cleanup'
361 `;
362 assert.lengthOf(cleanup, 1);
363 assert.equal(cleanup[0]?.command_id, `${commandId}:delete-thread:${threadId}`);
364 assert.equal(cleanup[0]?.status, "pending");
365 const request = yield* decodeEffectRequest(cleanup[0]?.payload_json);
366 assert.deepEqual(request, {
367 type: "attachment.cleanup",
368 attachmentIds: ["legacy_screenshot"],
369 });
370 }).pipe(Effect.provide(servicesLayer));
371 }).pipe(Effect.provide(databaseLayer)),
372);
373​
374it.effect("rejects a child deletion command ID already accepted for an unrelated thread", () =>
375 Effect.gen(function* () {
376 const sql = yield* SqlClient.SqlClient;
377 const projectId = ProjectId.make("project:receipt-collision");
378 const otherProjectId = ProjectId.make("project:unrelated-receipt");
379 const threadId = ThreadId.make("thread:receipt-collision");
380 const otherThreadId = ThreadId.make("thread:unrelated-receipt");
381 const commandId = CommandId.make("command:collision-project-delete");
382 yield* seedProject(projectId);
383 yield* seedProject(otherProjectId);
384​
385 yield* Effect.gen(function* () {
386 const eventSink = yield* EventSinkV2;
387 const projections = yield* ProjectionStoreV2;
388 const service = yield* ProjectService.make;
389 yield* eventSink.write({ events: [nativeThreadCreated(projectId, threadId)] });
390 const accepted = yield* eventSink.commitCommand({
391 commandId: CommandId.make(`${commandId}:delete-thread:${threadId}`),
392 commandType: "thread.create",
393 threadId: otherThreadId,
394 acceptedAt: DateTime.makeUnsafe("2026-01-01T00:00:00.000Z"),
395 events: [nativeThreadCreated(otherProjectId, otherThreadId)],
396 effects: [],
397 });
398 assert.equal(accepted.receipt.status, "accepted");
399​
400 const failure = yield* service
401 .delete({ commandId, projectId, force: true })
402 .pipe(Effect.flip);
403 assert.instanceOf(failure, ProjectService.ProjectOperationError);
404 if (failure._tag !== "ProjectOperationError") return assert.fail("Expected a child failure");
405 assert.equal(failure.operation, "delete-thread");
406 assert.isTrue(Option.isSome(yield* service.getById(projectId)));
407 assert.isNull((yield* projections.getThreadProjection(threadId)).thread.deletedAt);
408 assert.isNull((yield* projections.getThreadProjection(otherThreadId)).thread.deletedAt);
409 const deletions = yield* sql`
410 SELECT sequence FROM orchestration_events
411 WHERE event_type IN ('thread.deleted', 'project.deleted')
412 AND stream_id IN (${threadId}, ${otherThreadId}, ${projectId})
413 `;
414 assert.deepEqual(deletions, []);
415 const cleanup = yield* sql`
416 SELECT effect_id FROM orchestration_v2_effect_outbox
417 WHERE thread_id = ${threadId}
418 `;
419 assert.deepEqual(cleanup, []);
420 }).pipe(Effect.provide(servicesLayer));
421 }).pipe(Effect.provide(databaseLayer)),
422);