Skip to content

Commit 844c0e3

Browse files
shivamhwpclaude
andcommitted
fix(server): side chat cascades clean up files both threads sent
Deleting a thread together with its side chats planned each thread's file cleanup while the others still counted as live readers, so a file both sent was never removed. Attachment selection now takes the whole deletion set and excludes it from surviving readers. The family transcript reads also use CROSS JOIN so SQLite searches by thread_id instead of scanning every message and turn item when it has no planner statistics. Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent 8a414ed commit 844c0e3

4 files changed

Lines changed: 43 additions & 21 deletions

File tree

‎apps/server/src/orchestration-v2/Orchestrator.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13114,7 +13114,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
1311413114
command: deletion,
1311513115
projection,
1311613116
attachmentIds: yield* projectionStore
13117-
.getThreadAttachmentIds(deletion.threadId)
13117+
.getThreadAttachmentIds(deletion.threadId, [command.threadId, ...sideChatIds])
1311813118
.pipe(mapDispatchError(command)),
1311913119
now,
1312013120
idAllocator,

‎apps/server/src/orchestration-v2/ProjectionStore.test.ts‎

Lines changed: 24 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -64,7 +64,8 @@ const providerInstanceId = modelSelection.instanceId;
6464
const encodeUnknownJsonString = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown));
6565

6666
// Each "thread-n" key is that run's message file and question answer file; "source-queued" is a
67-
// runless message, which only forks of imported history show.
67+
// runless message, which only forks of imported history show. Deleting the source also deletes
68+
// its side chat in the same commit, and the side chat resends "source-2-file".
6869
it.effect.each([
6970
{
7071
order: ["source", "fork", "nested"],
@@ -97,7 +98,7 @@ it.effect.each([
9798
RunId.make(`run:fork-files:${name}:${ordinal}`);
9899
const filesOf = (key: string) =>
99100
key === "source-queued" ? [`${key}-file`] : [`${key}-file`, `${key}-answer`];
100-
const createThread = (name: string, source?: string) =>
101+
const createThread = (name: string, source?: string, sideChat?: true) =>
101102
store.apply({
102103
id: EventId.make(`event:fork-files:${name}:created`),
103104
type: "thread.created",
@@ -120,6 +121,7 @@ it.effect.each([
120121
parentThreadId: source === undefined ? null : id(source),
121122
relationshipToParent: source === undefined ? null : "fork",
122123
rootThreadId: id("source"),
124+
...(sideChat ? { sideChat } : {}),
123125
},
124126
forkedFrom:
125127
source === undefined
@@ -138,6 +140,7 @@ it.effect.each([
138140
const addMessage = Effect.fn("ForkFilesTest.addMessage")(function* (
139141
name: string,
140142
ordinal: number | null,
143+
fileKey?: string,
141144
) {
142145
const key = `${name}-${ordinal ?? "queued"}`;
143146
const messageId = MessageId.make(`message:fork-files:${key}`);
@@ -219,7 +222,7 @@ it.effect.each([
219222
nodeId: null,
220223
role: "user",
221224
text: "Read the attachment",
222-
attachments: [file(`${key}-file`)],
225+
attachments: [file(`${fileKey ?? key}-file`)],
223226
streaming: false,
224227
createdBy: "user",
225228
creationSource: "web",
@@ -242,7 +245,7 @@ it.effect.each([
242245
creationSource: "web",
243246
inputIntent: "turn_start",
244247
text: "Read the attachment",
245-
attachments: [file(`${key}-file`)],
248+
attachments: [file(`${fileKey ?? key}-file`)],
246249
},
247250
});
248251
});
@@ -254,9 +257,12 @@ it.effect.each([
254257
yield* addMessage("fork", 1);
255258
yield* addMessage("fork", 2);
256259
yield* createThread("nested", "fork");
260+
yield* createThread("side", "source", true);
261+
yield* addMessage("side", null, "source-2");
257262

258263
const selected = [];
259264
for (const name of order) {
265+
const deleted = name === "source" ? [id("source"), id("side")] : [id(name)];
260266
const projection = yield* store.getThreadProjection(id(name));
261267
if (name === "nested") {
262268
assert.deepEqual(
@@ -278,14 +284,20 @@ it.effect.each([
278284
],
279285
);
280286
}
281-
selected.push((yield* store.getThreadAttachmentIds(id(name))).toSorted());
282-
yield* store.apply({
283-
id: EventId.make(`event:fork-files:${name}:deleted`),
284-
type: "thread.deleted",
285-
threadId: id(name),
286-
occurredAt: now,
287-
payload: { ...projection.thread, deletedAt: now },
288-
});
287+
const plans = yield* Effect.forEach(deleted, (threadId) =>
288+
store.getThreadAttachmentIds(threadId, deleted),
289+
);
290+
selected.push([...new Set(plans.flat())].toSorted());
291+
for (const threadId of deleted) {
292+
const { thread } = yield* store.getThreadProjection(threadId);
293+
yield* store.apply({
294+
id: EventId.make(`event:${threadId}:deleted`),
295+
type: "thread.deleted",
296+
threadId,
297+
occurredAt: now,
298+
payload: { ...thread, deletedAt: now },
299+
});
300+
}
289301
}
290302
assert.deepEqual(
291303
selected,

‎apps/server/src/orchestration-v2/ProjectionStore.ts‎

Lines changed: 15 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -444,8 +444,10 @@ export interface ProjectionStoreV2Shape {
444444
readonly searchThread: (
445445
input: OrchestrationV2SearchThreadInput,
446446
) => Effect.Effect<OrchestrationV2SearchThreadResult, ProjectionStoreV2Error>;
447+
/** `deletedWith` are threads deleted in the same commit, so they keep no files. */
447448
readonly getThreadAttachmentIds: (
448449
threadId: ThreadId,
450+
deletedWith?: ReadonlyArray<ThreadId>,
449451
) => Effect.Effect<ReadonlyArray<string>, ProjectionStoreV2Error>;
450452
readonly getThreadHistoryPage: (
451453
threadId: ThreadId,
@@ -1248,6 +1250,7 @@ interface FamilyAttachment {
12481250
/** Forks show their source's files without copying them, so a file outlives the thread that sent it. */
12491251
function unreadThreadAttachmentIds(input: {
12501252
readonly threadId: ThreadId;
1253+
readonly deletedWith: ReadonlyArray<ThreadId>;
12511254
readonly threads: ReadonlyArray<FamilyThread>;
12521255
readonly attachments: ReadonlyArray<FamilyAttachment>;
12531256
}): Array<string> {
@@ -1279,7 +1282,9 @@ function unreadThreadAttachmentIds(input: {
12791282
};
12801283
const kept = new Set(
12811284
input.threads.flatMap((thread) =>
1282-
thread.deleted || thread.id === input.threadId ? [] : [...shownBy(thread.id)],
1285+
thread.deleted || thread.id === input.threadId || input.deletedWith.includes(thread.id)
1286+
? []
1287+
: [...shownBy(thread.id)],
12831288
),
12841289
);
12851290
return [...shownBy(input.threadId)].filter((id) => !kept.has(id));
@@ -5500,7 +5505,10 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
55005505
Effect.mapError(controlReadError(threadId)),
55015506
);
55025507

5503-
const getThreadAttachmentIds: ProjectionStoreV2Shape["getThreadAttachmentIds"] = (threadId) => {
5508+
const getThreadAttachmentIds: ProjectionStoreV2Shape["getThreadAttachmentIds"] = (
5509+
threadId,
5510+
deletedWith = [],
5511+
) => {
55045512
const family = sql`
55055513
SELECT thread_id, deleted_at, payload_json
55065514
FROM orchestration_v2_projection_threads
@@ -5517,6 +5525,7 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
55175525
run_ordinal: number | null;
55185526
id: string;
55195527
};
5528+
// CROSS JOIN keeps family as the outer loop; without planner stats SQLite scans every transcript.
55205529
return Effect.all([
55215530
sql<{
55225531
thread_id: ThreadId;
@@ -5549,7 +5558,7 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
55495558
run.ordinal AS run_ordinal,
55505559
json_extract(attachment.value, '$.id') AS id
55515560
FROM family
5552-
JOIN orchestration_v2_projection_messages AS message
5561+
CROSS JOIN orchestration_v2_projection_messages AS message
55535562
ON message.thread_id = family.thread_id
55545563
JOIN json_each(message.payload_json, '$.attachments') AS attachment
55555564
LEFT JOIN orchestration_v2_projection_runs AS run
@@ -5563,7 +5572,7 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
55635572
run.ordinal AS run_ordinal,
55645573
json_extract(attachment.value, '$.id') AS id
55655574
FROM family
5566-
JOIN orchestration_v2_projection_turn_items AS item
5575+
CROSS JOIN orchestration_v2_projection_turn_items AS item
55675576
ON item.thread_id = family.thread_id
55685577
JOIN json_each(item.payload_json, '$.questionAnswer.attachmentsByQuestionId') AS question
55695578
JOIN json_each(question.value) AS attachment
@@ -5584,7 +5593,7 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
55845593
run.ordinal AS run_ordinal,
55855594
item.payload_json
55865595
FROM family
5587-
JOIN orchestration_v2_projection_turn_items AS item
5596+
CROSS JOIN orchestration_v2_projection_turn_items AS item
55885597
ON item.thread_id = family.thread_id
55895598
LEFT JOIN orchestration_v2_projection_runs AS run
55905599
ON run.run_id = item.run_id AND run.thread_id = item.thread_id
@@ -5615,6 +5624,7 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
56155624
...new Set([
56165625
...unreadThreadAttachmentIds({
56175626
threadId,
5627+
deletedWith,
56185628
threads: threads.map((row) => ({
56195629
id: row.thread_id,
56205630
deleted: row.deleted_at !== null,

‎apps/server/src/orchestration-v2/runtimeLayer.test.ts‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -880,13 +880,13 @@ it.layer(layerProjectDeletionTest)("project deletion during thread commands", (i
880880
const getThreadAttachmentIds = projectionStore.getThreadAttachmentIds;
881881
const readSpy = vi
882882
.spyOn(projectionStore, "getThreadAttachmentIds")
883-
.mockImplementation((id) =>
883+
.mockImplementation((id, deletedWith) =>
884884
id === projectThreadId
885885
? Effect.sync(() => projectDeletePlannedAfterCommit.push(threadDeleteCommitted)).pipe(
886886
Effect.andThen(Deferred.succeed(projectDeletePlanning, undefined)),
887-
Effect.andThen(getThreadAttachmentIds(id)),
887+
Effect.andThen(getThreadAttachmentIds(id, deletedWith)),
888888
)
889-
: getThreadAttachmentIds(id),
889+
: getThreadAttachmentIds(id, deletedWith),
890890
);
891891
const withDeletionLock = executor.withDeletionLock;
892892
let deletionLockRequests = 0;

0 commit comments

Comments
 (0)