@devries-cameron20 / t3code Mirror · read-only / commits / c7f8404d2e
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 23, 00:30 UTC

perf(server): fork threads load faster when local turns fill the first page (#20104)

Co-authored-by: Aaron Queen <bompus@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

Julius Marminge committed Oct 19, 2026 at 19:55 UTC c7f8404d2eadf5315ba9f4f0abbf96cfce138be0
2 files changed +276 -57
apps/server/src/orchestration-v2/ProjectionStore.test.ts
+156
@@ -42,6 +42,7 @@ import {
42 decodeThreadHistoryCursor,
43 selectHistoryPageFromCursor,
44 THREAD_HISTORY_PAGE_POLICY,
45 + THREAD_HISTORY_SNAPSHOT_ROW_LIMIT,
46 } from "./threadHistoryPaging.ts";
47
48 const layerTest = Layer.mergeAll(
@@ -6074,6 +6075,161 @@ it.layer(layerTest)("ProjectionStoreV2", (it) => {
6075 }),
6076 );
6077
6078 + it.effect("skips parent bodies once a fork's own turns fill its first page", () =>
6079 + Effect.gen(function* () {
6080 + const store = yield* ProjectionStore.ProjectionStoreV2;
6081 + const now = DateTime.makeUnsafe("2026-10-01T00:00:00.000Z");
6082 + const parentId = ThreadId.make("thread:filled-fork:parent");
6083 + const forkId = ThreadId.make("thread:filled-fork:fork");
6084 + const parentText = "parent prompt";
6085 + const createThread = (
6086 + threadId: ThreadId,
6087 + forkedFrom: { readonly threadId: ThreadId; readonly runId: RunId } | null,
6088 + ) =>
6089 + store.apply({
6090 + id: EventId.make(`event:${threadId}`),
6091 + type: "thread.created",
6092 + threadId,
6093 + occurredAt: now,
6094 + payload: {
6095 + createdBy: "user",
6096 + creationSource: "web",
6097 + id: threadId,
6098 + projectId: ProjectId.make("project:filled-fork"),
6099 + title: "Filled fork",
6100 + providerInstanceId,
6101 + modelSelection,
6102 + runtimeMode: "full-access",
6103 + interactionMode: "default",
6104 + branch: null,
6105 + worktreePath: null,
6106 + activeProviderThreadId: null,
6107 + lineage: {
6108 + parentThreadId: forkedFrom?.threadId ?? null,
6109 + relationshipToParent: forkedFrom === null ? null : "fork",
6110 + rootThreadId: parentId,
6111 + },
6112 + forkedFrom: forkedFrom === null ? null : { type: "run", ...forkedFrom },
6113 + createdAt: now,
6114 + updatedAt: now,
6115 + archivedAt: null,
6116 + settledOverride: null,
6117 + settledAt: null,
6118 + lastVisitedAt: null,
6119 + deletedAt: null,
6120 + },
6121 + });
6122 + const addTurn = Effect.fnUntraced(function* (threadId: ThreadId, turn: number, text: string) {
6123 + const runId = RunId.make(`run:${threadId}:${turn}`);
6124 + const nodeId = NodeId.make(`node:${threadId}:${turn}`);
6125 + yield* store.apply({
6126 + id: EventId.make(`event:${runId}`),
6127 + type: "run.created",
6128 + threadId,
6129 + runId,
6130 + nodeId,
6131 + driver,
6132 + occurredAt: now,
6133 + payload: {
6134 + id: runId,
6135 + threadId,
6136 + ordinal: turn,
6137 + providerInstanceId,
6138 + modelSelection,
6139 + providerThreadId: null,
6140 + userMessageId: MessageId.make(`message:${runId}`),
6141 + rootNodeId: nodeId,
6142 + activeAttemptId: null,
6143 + status: "completed",
6144 + requestedAt: now,
6145 + startedAt: now,
6146 + completedAt: now,
6147 + checkpointId: null,
6148 + contextHandoffId: null,
6149 + },
6150 + });
6151 + yield* store.apply({
6152 + id: EventId.make(`event:${runId}:prompt`),
6153 + type: "turn-item.updated",
6154 + threadId,
6155 + runId,
6156 + driver,
6157 + occurredAt: now,
6158 + payload: {
6159 + id: TurnItemId.make(`item:${runId}`),
6160 + threadId,
6161 + runId,
6162 + nodeId: null,
6163 + providerThreadId: null,
6164 + providerTurnId: null,
6165 + nativeItemRef: null,
6166 + parentItemId: null,
6167 + ordinal: turn,
6168 + status: "completed",
6169 + title: null,
6170 + startedAt: now,
6171 + completedAt: now,
6172 + updatedAt: now,
6173 + type: "user_message",
6174 + messageId: MessageId.make(`message:${runId}`),
6175 + inputIntent: "turn_start",
6176 + createdBy: "user",
6177 + creationSource: "web",
6178 + text,
6179 + attachments: [],
6180 + },
6181 + });
6182 + });
6183 + const readFirstPage = Effect.fnUntraced(function* (
6184 + threadId: ThreadId,
6185 + parsesParent: boolean,
6186 + ) {
6187 + const full = yield* store.getThreadSnapshot(threadId);
6188 + // Measure only the window read; the full snapshot is the pagination oracle.
6189 + const parse = yield* Effect.acquireRelease(
6190 + Effect.sync(() => vi.spyOn(JSON, "parse")),
6191 + (spy) => Effect.sync(() => spy.mockRestore()),
6192 + );
6193 + const window = yield* store.getThreadSnapshotWindow(threadId, {
6194 + rowLimit: THREAD_HISTORY_SNAPSHOT_ROW_LIMIT,
6195 + userTurnLimit: THREAD_HISTORY_PAGE_POLICY.maxUserTurns,
6196 + });
6197 + assert.equal(
6198 + parse.mock.calls.some(([text]) => text.includes(parentText)),
6199 + parsesParent,
6200 + );
6201 + const page = buildBoundedThreadProjection(window);
6202 + assert.deepEqual(page, buildBoundedThreadProjection(full));
6203 + assert.isTrue(page.hasMoreHistory);
6204 + assert.isNotNull(page.historyCursor);
6205 + return page.projection.visibleTurnItems;
6206 + }, Effect.scoped);
6207 +
6208 + yield* createThread(parentId, null);
6209 + for (const turn of [1, 2, 3]) yield* addTurn(parentId, turn, `${parentText} ${turn}`);
6210 + // The third parent turn is after the fork boundary and must stay excluded.
6211 + yield* createThread(forkId, { threadId: parentId, runId: RunId.make(`run:${parentId}:2`) });
6212 + for (let turn = 1; turn <= 9; turn += 1) yield* addTurn(forkId, turn, "fork prompt");
6213 + const partial = yield* readFirstPage(forkId, true);
6214 + assert.include(
6215 + partial.map((row) => row.visibility),
6216 + "inherited",
6217 + );
6218 +
6219 + yield* addTurn(forkId, 10, "fork prompt");
6220 + const filled = yield* readFirstPage(forkId, false);
6221 + assert.notInclude(
6222 + filled.map((row) => row.visibility),
6223 + "inherited",
6224 + );
6225 +
6226 + const nestedId = ThreadId.make("thread:filled-fork:nested");
6227 + yield* createThread(nestedId, { threadId: forkId, runId: RunId.make(`run:${forkId}:10`) });
6228 + for (let turn = 1; turn <= 10; turn += 1) yield* addTurn(nestedId, turn, "nested prompt");
6229 + yield* readFirstPage(nestedId, true);
6230 + }),
6231 + );
6232 +
6233 it.effect("a pull request watch keeps a finished thread working until it ends", () =>
6234 Effect.gen(function* () {
6235 const store = yield* ProjectionStore.ProjectionStoreV2;
apps/server/src/orchestration-v2/ProjectionStore.ts
+120 -57
@@ -1339,8 +1339,9 @@ function withLocalVisibleTurnItems(
1339
1340 function renumberVisibleTurnItems(
1341 rows: ReadonlyArray<Omit<OrchestrationV2ProjectedTurnItem, "position">>,
1342 + offset = 0,
1343 ): Array<OrchestrationV2ProjectedTurnItem> {
1343 - return rows.map((row, position) => ({ ...row, position }));
1344 + return rows.map((row, position) => ({ ...row, position: position + offset }));
1345 }
1346
1347 function makeForkMarkerTurnItem(input: {
@@ -1428,16 +1429,23 @@ function visibleTurnItemsThroughRun(input: {
1429 function buildVisibleTurnItems(input: {
1430 readonly projection: OrchestrationV2ThreadProjection;
1431 readonly sourceProjection: OrchestrationV2ThreadProjection | null;
1432 + readonly inheritedRowCount?: number;
1433 }): Array<OrchestrationV2ProjectedTurnItem> {
1434 const forkedFrom = input.projection.thread.forkedFrom;
1433 - if (forkedFrom?.type !== "run" || input.sourceProjection === null) {
1435 + if (
1436 + forkedFrom?.type !== "run" ||
1437 + (input.sourceProjection === null && input.inheritedRowCount === undefined)
1438 + ) {
1439 return localVisibleTurnItems(input.projection);
1440 }
1441
1437 - const inherited = visibleTurnItemsThroughRun({
1438 - sourceProjection: input.sourceProjection,
1439 - sourceRunId: forkedFrom.runId,
1440 - });
1442 + const inherited =
1443 + input.sourceProjection === null
1444 + ? []
1445 + : visibleTurnItemsThroughRun({
1446 + sourceProjection: input.sourceProjection,
1447 + sourceRunId: forkedFrom.runId,
1448 + });
1449 const markerItem = makeForkMarkerTurnItem({
1450 targetProjection: input.projection,
1451 sourceThreadId: forkedFrom.threadId,
@@ -1450,16 +1458,19 @@ function buildVisibleTurnItems(input: {
1458 item: row.item,
1459 }));
1460
1453 - return renumberVisibleTurnItems([
1454 - ...inherited,
1455 - {
1456 - visibility: "synthetic",
1457 - sourceThreadId: forkedFrom.threadId,
1458 - sourceItemId: markerItem.id,
1459 - item: markerItem,
1460 - },
1461 - ...local,
1462 - ]);
1461 + return renumberVisibleTurnItems(
1462 + [
1463 + ...inherited,
1464 + {
1465 + visibility: "synthetic",
1466 + sourceThreadId: forkedFrom.threadId,
1467 + sourceItemId: markerItem.id,
1468 + item: markerItem,
1469 + },
1470 + ...local,
1471 + ],
1472 + input.inheritedRowCount ?? 0,
1473 + );
1474 }
1475
1476 function pendingRuntimeRequestSummary(
@@ -2779,47 +2790,16 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
2790 ),
2791 );
2792
2782 - const readCanonicalProjection = Effect.fn("ProjectionStore.readCanonicalProjection")(
2783 - function* (
2784 - threadId: ThreadId,
2785 - window?: {
2786 - readonly rowLimit: number;
2787 - readonly userTurnLimit?: number | undefined;
2788 - readonly anchorItemId?: TurnItemId | undefined;
2789 - readonly requiredRunId?: RunId | undefined;
2790 - readonly suppressLocal?: boolean | undefined;
2791 - },
2792 - fields?: ReadonlyArray<ProjectionRecordField>,
2793 - filter?: ProjectionRecordFilter,
2794 - ) {
2795 - const threadRows = yield* sql<PayloadRow>`
2796 - SELECT payload_json
2797 - FROM orchestration_v2_projection_threads
2798 - WHERE thread_id = ${threadId}
2799 - LIMIT 1
2800 - `;
2801 - const threadRow = threadRows[0];
2802 - if (!threadRow) {
2803 - return yield* new ProjectionStoreThreadNotFoundError({ threadId });
2804 - }
2805 -
2806 - const boundedTurnItemRows =
2807 - (fields !== undefined && !fields.includes("turnItems")) ||
2808 - (window === undefined &&
2809 - matchesNothing(filter?.turnItemTypes, filter?.turnItemStatuses, filter?.turnItemRunIds))
2810 - ? []
2811 - : window === undefined
2812 - ? yield* sql<PayloadRow>`
2813 - SELECT payload_json
2814 - FROM orchestration_v2_projection_turn_items
2815 - WHERE thread_id = ${threadId}
2816 - ${filter?.turnItemTypes === undefined ? sql`` : sql`AND type IN (SELECT value FROM json_each(${encodeIdList(filter.turnItemTypes)}))`}
2817 - ${filter?.turnItemStatuses === undefined ? sql`` : sql`AND status IN (SELECT value FROM json_each(${encodeIdList(filter.turnItemStatuses)}))`}
2818 - ${filter?.turnItemRunId === undefined ? sql`` : sql`AND run_id = ${filter.turnItemRunId}`}
2819 - ${filter?.turnItemRunIds === undefined ? sql`` : sql`AND (run_id IN (SELECT value FROM json_each(${encodeIdList(filter.turnItemRunIds.filter((id): id is RunId => id !== null))})) OR (${filter.turnItemRunIds.includes(null) ? 1 : 0} = 1 AND run_id IS NULL))`}
2820 - ORDER BY ordinal ASC, turn_item_id ASC
2821 - `
2822 - : yield* sql<PayloadRow>`
2793 + // Share selection so counting discarded ancestry preserves payload-read positions.
2794 + const retainedWindowRows = (
2795 + threadId: ThreadId,
2796 + window: {
2797 + readonly rowLimit: number;
2798 + readonly userTurnLimit?: number | undefined;
2799 + readonly anchorItemId?: TurnItemId | undefined;
2800 + readonly requiredRunId?: RunId | undefined;
2801 + },
2802 + ) => sql`
2803 WITH eligible AS NOT MATERIALIZED (
2804 SELECT item.rowid AS item_rowid, item.payload_json, item.ordinal, item.turn_item_id,
2805 item.run_id, item.node_id, item.type
@@ -2984,6 +2964,50 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
2964 ) AS latest
2965 ORDER BY ordinal ASC, turn_item_id ASC
2966 )
2967 + `;
2968 +
2969 + const readCanonicalProjection = Effect.fn("ProjectionStore.readCanonicalProjection")(
2970 + function* (
2971 + threadId: ThreadId,
2972 + window?: {
2973 + readonly rowLimit: number;
2974 + readonly userTurnLimit?: number | undefined;
2975 + readonly anchorItemId?: TurnItemId | undefined;
2976 + readonly requiredRunId?: RunId | undefined;
2977 + readonly suppressLocal?: boolean | undefined;
2978 + },
2979 + fields?: ReadonlyArray<ProjectionRecordField>,
2980 + filter?: ProjectionRecordFilter,
2981 + ) {
2982 + const threadRows = yield* sql<PayloadRow>`
2983 + SELECT payload_json
2984 + FROM orchestration_v2_projection_threads
2985 + WHERE thread_id = ${threadId}
2986 + LIMIT 1
2987 + `;
2988 + const threadRow = threadRows[0];
2989 + if (!threadRow) {
2990 + return yield* new ProjectionStoreThreadNotFoundError({ threadId });
2991 + }
2992 +
2993 + const boundedTurnItemRows =
2994 + (fields !== undefined && !fields.includes("turnItems")) ||
2995 + (window === undefined &&
2996 + matchesNothing(filter?.turnItemTypes, filter?.turnItemStatuses, filter?.turnItemRunIds))
2997 + ? []
2998 + : window === undefined
2999 + ? yield* sql<PayloadRow>`
3000 + SELECT payload_json
3001 + FROM orchestration_v2_projection_turn_items
3002 + WHERE thread_id = ${threadId}
3003 + ${filter?.turnItemTypes === undefined ? sql`` : sql`AND type IN (SELECT value FROM json_each(${encodeIdList(filter.turnItemTypes)}))`}
3004 + ${filter?.turnItemStatuses === undefined ? sql`` : sql`AND status IN (SELECT value FROM json_each(${encodeIdList(filter.turnItemStatuses)}))`}
3005 + ${filter?.turnItemRunId === undefined ? sql`` : sql`AND run_id = ${filter.turnItemRunId}`}
3006 + ${filter?.turnItemRunIds === undefined ? sql`` : sql`AND (run_id IN (SELECT value FROM json_each(${encodeIdList(filter.turnItemRunIds.filter((id): id is RunId => id !== null))})) OR (${filter.turnItemRunIds.includes(null) ? 1 : 0} = 1 AND run_id IS NULL))`}
3007 + ORDER BY ordinal ASC, turn_item_id ASC
3008 + `
3009 + : yield* sql<PayloadRow>`
3010 + ${retainedWindowRows(threadId, window)}
3011 -- CROSS JOIN keeps the sorted IDs as the outer loop, so SQLite
3012 -- skips sorting again once the payloads are attached. Carry the
3013 -- rowid through selection to avoid a second string-key index lookup.
@@ -3592,6 +3616,45 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
3616 };
3617 });
3618
3619 + // Filled local pages need only the inherited count for cursor positions.
3620 + // Run-forked parents still need the recursive read to include their ancestry.
3621 + if (
3622 + window?.userTurnLimit !== undefined &&
3623 + window.historyAnchor === undefined &&
3624 + seenThreadIds.size === 0 &&
3625 + sourceWindow !== undefined &&
3626 + activeLocalTurnItems(projection).filter((row) => isThreadHistoryUserTurn(row.item))
3627 + .length >= Math.max(window.userTurnLimit, THREAD_HISTORY_PAGE_POLICY.maxUserTurns)
3628 + ) {
3629 + const counted = yield* sql<{ readonly inherited_rows: number | null }>`
3630 + ${retainedWindowRows(forkedFrom.threadId, {
3631 + ...sourceWindow,
3632 + rowLimit: sourceWindow.suppressLocal ? 0 : sourceWindow.rowLimit,
3633 + })}
3634 + SELECT CASE
3635 + WHEN json_extract(source.payload_json, '$.forkedFrom.type') = 'run' THEN NULL
3636 + WHEN NOT EXISTS (
3637 + SELECT 1 FROM orchestration_v2_projection_runs
3638 + WHERE thread_id = source.thread_id AND run_id = ${forkedFrom.runId}
3639 + ) THEN 0
3640 + ELSE (SELECT COUNT(*) FROM retained)
3641 + END AS inherited_rows
3642 + FROM orchestration_v2_projection_threads AS source
3643 + WHERE source.thread_id = ${forkedFrom.threadId}
3644 + `;
3645 + const inheritedRowCount = counted[0]?.inherited_rows ?? null;
3646 + if (inheritedRowCount !== null) {
3647 + return {
3648 + ...projection,
3649 + visibleTurnItems: buildVisibleTurnItems({
3650 + projection,
3651 + sourceProjection: null,
3652 + inheritedRowCount,
3653 + }),
3654 + };
3655 + }
3656 + }
3657 +
3658 const sourceProjection = yield* readProjection(
3659 forkedFrom.threadId,
3660 new Set([...seenThreadIds, threadId]),