From 4442054fc7b5ab5e3834fdcf4a2f4429e1b7499f Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sat, 15 Aug 2026 16:47:12 +0200 Subject: [PATCH] perf(server): keep shell snapshots bounded and active-only - Omit transcript bodies from shell rows - Query archived threads separately and stream compact resume metadata --- .../src/orchestration-v2/Orchestrator.ts | 11 +- .../orchestration-v2/ProjectionStore.test.ts | 1 + .../src/orchestration-v2/ProjectionStore.ts | 142 +++++++++--------- .../src/orchestration-v2/ShellStream.test.ts | 42 +++++- .../src/orchestration-v2/ShellStream.ts | 32 +++- .../ThreadManagementService.ts | 7 +- .../orchestration-v2/WireProjection.test.ts | 65 +++++++- apps/server/src/orchestration-v2/http.ts | 15 +- .../src/orchestration-v2/runtimeLayer.test.ts | 20 ++- .../Layers/ProjectionSnapshotQuery.ts | 19 +++ .../Services/ProjectionSnapshotQuery.ts | 6 + apps/server/src/ws.ts | 50 ++++-- docs/internals/performance-regressions.md | 2 + .../src/state/shellReducer.test.ts | 4 +- .../client-runtime/src/state/shellReducer.ts | 8 +- 15 files changed, 297 insertions(+), 127 deletions(-) diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index 41cdb1c93d..4bb8f7d56a 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -159,10 +159,9 @@ export interface OrchestratorV2Shape { }, OrchestratorV2Error >; - readonly getShellSnapshot: () => Effect.Effect< - OrchestrationV2ThreadShellSnapshot, - OrchestratorV2Error - >; + readonly getShellSnapshot: (options?: { + readonly location?: "active" | "archive"; + }) => Effect.Effect; readonly getThreadShell: ( threadId: ThreadId, ) => Effect.Effect; @@ -7108,8 +7107,8 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio projectionStore .getThreadSnapshot(threadId) .pipe(Effect.mapError((cause) => new OrchestratorProjectionError({ threadId, cause }))), - getShellSnapshot: () => - projectionStore.getShellSnapshot().pipe( + getShellSnapshot: (options) => + projectionStore.getShellSnapshot(options).pipe( Effect.mapError( (cause) => new OrchestratorProjectionError({ diff --git a/apps/server/src/orchestration-v2/ProjectionStore.test.ts b/apps/server/src/orchestration-v2/ProjectionStore.test.ts index 98cec43d2b..fc8f8730b8 100644 --- a/apps/server/src/orchestration-v2/ProjectionStore.test.ts +++ b/apps/server/src/orchestration-v2/ProjectionStore.test.ts @@ -1210,6 +1210,7 @@ it.layer(TestLayer)("ProjectionStoreV2", (it) => { const shell = yield* projectionStore.getShellSnapshot(); const rolledBackShellThread = shell.threads.find((entry) => entry.id === threadId); assert.isDefined(rolledBackShellThread); + assert.isNull(rolledBackShellThread.latestVisibleMessage); assert.deepEqual(rolledBackShellThread?.pendingBackgroundTasks ?? [], []); }), ); diff --git a/apps/server/src/orchestration-v2/ProjectionStore.ts b/apps/server/src/orchestration-v2/ProjectionStore.ts index 25263ea93c..8177facb2d 100644 --- a/apps/server/src/orchestration-v2/ProjectionStore.ts +++ b/apps/server/src/orchestration-v2/ProjectionStore.ts @@ -103,10 +103,9 @@ export interface ProjectionStoreV2Shape { readonly apply: ( event: OrchestrationV2DomainEvent, ) => Effect.Effect; - readonly getShellSnapshot: () => Effect.Effect< - OrchestrationV2ThreadShellSnapshot, - ProjectionStoreV2Error - >; + readonly getShellSnapshot: (options?: { + readonly location?: "active" | "archive"; + }) => Effect.Effect; readonly getThreadShell: ( threadId: ThreadId, ) => Effect.Effect; @@ -446,7 +445,6 @@ type ShellThreadRow = { readonly activity_run_status: string | null; readonly last_error: string | null; readonly pending_request_payload_json: string | null; - readonly latest_message_payload_json: string | null; readonly latest_user_message_at: string | null; readonly has_actionable_proposed_plan: number; readonly item_count: number; @@ -831,11 +829,6 @@ export function threadShellFromProjection( (left, right) => DateTime.toEpochMillis(right.createdAt) - DateTime.toEpochMillis(left.createdAt), )[0] ?? null; - const latestVisibleMessage = - projection.messages.toSorted( - (left, right) => - DateTime.toEpochMillis(right.updatedAt) - DateTime.toEpochMillis(left.updatedAt), - )[0] ?? null; const latestUserMessage = projection.messages .filter((message) => message.role === "user") @@ -891,15 +884,9 @@ export function threadShellFromProjection( kind: pendingRuntimeRequest.kind, createdAt: pendingRuntimeRequest.createdAt, }, - latestVisibleMessage: - latestVisibleMessage === null - ? null - : { - id: latestVisibleMessage.id, - role: latestVisibleMessage.role, - text: latestVisibleMessage.text, - updatedAt: latestVisibleMessage.updatedAt, - }, + // Thread detail owns message bodies. Keeping them out of shell rows makes + // initial hydration and streaming updates independent of transcript size. + latestVisibleMessage: null, latestUserMessageAt: latestUserMessage?.updatedAt ?? null, hasActionableProposedPlan: projection.plans.some( (plan) => plan.kind === "proposed_plan" && plan.status === "active", @@ -947,7 +934,6 @@ type ShellThreadState = { readonly activityRunStatus: ShellActivityRunStatus | null; readonly lastError: string | null; readonly pendingRuntimeRequest: OrchestrationV2ThreadProjection["runtimeRequests"][number] | null; - readonly latestVisibleMessage: OrchestrationV2ConversationMessage | null; readonly latestUserMessageAt: DateTime.Utc | null; readonly hasActionableProposedPlan: boolean; readonly pendingBackgroundTasks: OrchestrationV2ThreadShell["pendingBackgroundTasks"]; @@ -1078,15 +1064,7 @@ function shellFromState(input: { kind: input.state.pendingRuntimeRequest.kind, createdAt: input.state.pendingRuntimeRequest.createdAt, }, - latestVisibleMessage: - input.state.latestVisibleMessage === null - ? null - : { - id: input.state.latestVisibleMessage.id, - role: input.state.latestVisibleMessage.role, - text: input.state.latestVisibleMessage.text, - updatedAt: input.state.latestVisibleMessage.updatedAt, - }, + latestVisibleMessage: null, latestUserMessageAt: input.state.latestUserMessageAt, hasActionableProposedPlan: input.state.hasActionableProposedPlan, pendingBackgroundTasks: input.state.pendingBackgroundTasks, @@ -2223,7 +2201,7 @@ export const layer: Layer.Layer = ), ); - const selectShellThreadRows = (threadId?: ThreadId) => + const selectShellThreadRows = (threadId?: ThreadId, location?: "active" | "archive") => sql` SELECT t.thread_id, @@ -2302,13 +2280,6 @@ export const layer: Layer.Layer = ORDER BY request.created_at DESC, request.runtime_request_id DESC LIMIT 1 ) AS pending_request_payload_json, - ( - SELECT message.payload_json - FROM orchestration_v2_projection_messages message - WHERE message.thread_id = t.thread_id - ORDER BY message.updated_at DESC, message.message_id DESC - LIMIT 1 - ) AS latest_message_payload_json, ( SELECT message.updated_at FROM orchestration_v2_projection_messages message @@ -2339,7 +2310,13 @@ export const layer: Layer.Layer = AND i.run_id IS NULL ) AS runless_item_count FROM orchestration_v2_projection_threads t - WHERE t.deleted_at IS NULL${threadId === undefined ? sql`` : sql` AND t.thread_id = ${threadId}`} + WHERE t.deleted_at IS NULL${threadId === undefined ? sql`` : sql` AND t.thread_id = ${threadId}`}${ + location === "active" + ? sql` AND json_extract(t.payload_json, '$.archivedAt') IS NULL` + : location === "archive" + ? sql` AND json_extract(t.payload_json, '$.archivedAt') IS NOT NULL` + : sql`` + } ORDER BY t.updated_at ASC, t.thread_id ASC `; @@ -2491,10 +2468,6 @@ export const layer: Layer.Layer = row.pending_request_payload_json === null ? null : yield* decodeRuntimeRequestPayload(row.pending_request_payload_json); - const latestVisibleMessage = - row.latest_message_payload_json === null - ? null - : yield* decodeMessagePayload(row.latest_message_payload_json); const latestRunId = row.latest_run_id === null ? null : RunId.make(row.latest_run_id); const latestRunStatus = shellStatusFromStoredRunStatus(row.latest_run_status); const pendingBackgroundTasks = [ @@ -2539,7 +2512,6 @@ export const layer: Layer.Layer = : null, lastError: row.last_error, pendingRuntimeRequest, - latestVisibleMessage, latestUserMessageAt: row.latest_user_message_at === null ? null @@ -2554,30 +2526,51 @@ export const layer: Layer.Layer = } satisfies ShellThreadState; }); - const getShellSnapshot: ProjectionStoreV2Shape["getShellSnapshot"] = () => + const getShellSnapshot: ProjectionStoreV2Shape["getShellSnapshot"] = (options) => sql .withTransaction( Effect.gen(function* () { - const [ - threadRows, - runRows, - itemCountRows, - sequenceRows, - providerThreadRows, - pendingTurnItemRows, - ] = yield* Effect.all([ - selectShellThreadRows(), - selectShellRunRows(), - selectShellRunItemCounts(), - sql<{ readonly snapshot_sequence: number | null }>` + const targetThreadRows = yield* selectShellThreadRows(undefined, options?.location); + const targetThreadIds = new Set( + targetThreadRows.map((row) => ThreadId.make(row.thread_id)), + ); + const rowsByThreadId = new Map( + targetThreadRows.map((row) => [ThreadId.make(row.thread_id), row] as const), + ); + const pendingSourceIds = targetThreadRows.flatMap((row) => + row.forked_from_run_source_thread_id === null + ? [] + : [ThreadId.make(row.forked_from_run_source_thread_id)], + ); + while (pendingSourceIds.length > 0) { + const sourceId = pendingSourceIds.pop(); + if (sourceId === undefined || rowsByThreadId.has(sourceId)) continue; + const source = (yield* selectShellThreadRows(sourceId))[0]; + if (source === undefined) continue; + rowsByThreadId.set(sourceId, source); + if (source.forked_from_run_source_thread_id !== null) { + pendingSourceIds.push(ThreadId.make(source.forked_from_run_source_thread_id)); + } + } + const threadRows = [...rowsByThreadId.values()]; + const threadIds = [...rowsByThreadId.keys()]; + const readForThreadIds = ( + read: (ids: ReadonlyArray) => Effect.Effect, unknown>, + ) => + threadIds.length === 0 ? Effect.succeed([] as ReadonlyArray) : read(threadIds); + const [runRows, itemCountRows, sequenceRows, providerThreadRows, pendingTurnItemRows] = + yield* Effect.all([ + readForThreadIds(selectShellRunRows), + readForThreadIds(selectShellRunItemCounts), + sql<{ readonly snapshot_sequence: number | null }>` SELECT MAX(sequence) AS snapshot_sequence FROM orchestration_events WHERE application_event_version = 2 AND aggregate_kind = 'thread' `, - selectShellProviderThreadRows(), - selectShellPendingTurnItemRows(), - ]); + readForThreadIds(selectShellProviderThreadRows), + readForThreadIds(selectShellPendingTurnItemRows), + ]); const { runOrdinalsByThreadId, itemCountsByThreadId } = runMapsByThreadId({ runRows, @@ -2596,15 +2589,17 @@ export const layer: Layer.Layer = ); const statesByThreadId = new Map(states.map((state) => [state.thread.id, state])); - const shells = states.map((state) => - shellFromState({ - state, - visibleItemCount: visibleItemCountForShell({ - threadId: state.thread.id, - statesByThreadId, + const shells = states + .filter((state) => targetThreadIds.has(state.thread.id)) + .map((state) => + shellFromState({ + state, + visibleItemCount: visibleItemCountForShell({ + threadId: state.thread.id, + statesByThreadId, + }), }), - }), - ); + ); return { schemaVersion: ORCHESTRATION_V2_PROJECTION_SCHEMA_VERSION, @@ -2727,13 +2722,18 @@ export const layerMemory: Layer.Layer = Layer.effect( } yield* Ref.update(sequence, (current) => current + 1); }), - getShellSnapshot: () => + getShellSnapshot: (options) => Effect.gen(function* () { const existing = (yield* Ref.get(replayState)).projections; + const selectedThreadIds = [...existing.entries()] + .filter(([, projection]) => { + if (options?.location === "active") return projection.thread.archivedAt === null; + if (options?.location === "archive") return projection.thread.archivedAt !== null; + return true; + }) + .map(([threadId]) => threadId); const shells = yield* Effect.forEach( - [...existing.keys()].toSorted((left, right) => - String(left).localeCompare(String(right)), - ), + selectedThreadIds.toSorted((left, right) => String(left).localeCompare(String(right))), (threadId) => service.getThreadProjection(threadId).pipe(Effect.map(threadShellFromProjection)), ); diff --git a/apps/server/src/orchestration-v2/ShellStream.test.ts b/apps/server/src/orchestration-v2/ShellStream.test.ts index b51614b129..0b2b7929eb 100644 --- a/apps/server/src/orchestration-v2/ShellStream.test.ts +++ b/apps/server/src/orchestration-v2/ShellStream.test.ts @@ -11,6 +11,7 @@ import * as Stream from "effect/Stream"; import { archivedShellStreamItemFromThreadShell, + buildActiveShellSnapshot, coalesceShellApplicationEvents, coalesceStoredThreadEvents, composeShellStreamWithEnrichment, @@ -43,6 +44,35 @@ const emptyShellSnapshot = { archivedThreads: [], } as OrchestrationV2ShellSnapshot; +describe("buildActiveShellSnapshot", () => { + it("never duplicates archived rows into the regular shell", () => { + const active = shellFixture({ archivedAt: null }); + const archived = shellFixture({ + id: ThreadId.make("thread-archived"), + archivedAt: "2026-07-30T00:00:00.000Z" as never, + }); + + expect( + buildActiveShellSnapshot({ + projects: [], + threads: { + schemaVersion: 1, + snapshotSequence: 4, + threads: [active], + archivedThreads: [archived], + }, + snapshotSequence: 7, + }), + ).toEqual({ + schemaVersion: 1, + snapshotSequence: 7, + projects: [], + threads: [active], + archivedThreads: [], + }); + }); +}); + describe("coalesceShellApplicationEvents", () => { it("keeps the newest event per aggregate and preserves sequence order", () => { expect( @@ -94,19 +124,19 @@ describe("shellStreamItemFromThreadShell", () => { }); }); - it("emits an archive update when the shell is archived", () => { + it("removes archived threads from the active-only shell", () => { const shell = shellFixture({ archivedAt: "2026-07-30T00:00:00.000Z" as never }); expect( shellStreamItemFromThreadShell({ stored: storedThreadEvent(4, "thread-a"), shell }), ).toEqual({ - kind: "thread.updated", + kind: "thread.removed", sequence: 4, - location: "archive", - thread: shell, + location: "active", + threadId: "thread-a", }); }); - it("emits a removal from the archive when an archived thread is deleted", () => { + it("emits an active-shell removal when an archived thread is deleted", () => { expect( shellStreamItemFromThreadShell({ stored: storedThreadEvent(6, "thread-a", { @@ -118,7 +148,7 @@ describe("shellStreamItemFromThreadShell", () => { ).toEqual({ kind: "thread.removed", sequence: 6, - location: "archive", + location: "active", threadId: "thread-a", }); }); diff --git a/apps/server/src/orchestration-v2/ShellStream.ts b/apps/server/src/orchestration-v2/ShellStream.ts index 942b909d7c..57bb876c20 100644 --- a/apps/server/src/orchestration-v2/ShellStream.ts +++ b/apps/server/src/orchestration-v2/ShellStream.ts @@ -1,13 +1,30 @@ import type { ApplicationStoredEvent, + OrchestrationProjectShell, OrchestrationV2ArchivedShellStreamItem, OrchestrationV2ShellSnapshot, OrchestrationV2ThreadShell, + OrchestrationV2ThreadShellSnapshot, OrchestrationV2ShellStreamItem, OrchestrationV2StoredEvent, } from "@t3tools/contracts"; import * as Stream from "effect/Stream"; +/** Build the regular navigation shell without duplicating the archive dataset. */ +export function buildActiveShellSnapshot(input: { + readonly projects: ReadonlyArray; + readonly threads: OrchestrationV2ThreadShellSnapshot; + readonly snapshotSequence: number; +}): OrchestrationV2ShellSnapshot { + return { + schemaVersion: input.threads.schemaVersion, + snapshotSequence: input.snapshotSequence, + projects: input.projects, + threads: input.threads.threads, + archivedThreads: [], + }; +} + /** Keep only the newest shell-relevant event per project/thread aggregate. */ export function coalesceShellApplicationEvents( events: ReadonlyArray, @@ -124,10 +141,18 @@ export function shellStreamItemFromThreadShell(input: { readonly shell: OrchestrationV2ThreadShell | null; }): Exclude { if (input.shell !== null) { + if (input.shell.archivedAt !== null) { + return { + kind: "thread.removed", + sequence: input.stored.sequence, + location: "active", + threadId: input.shell.id, + }; + } return { kind: "thread.updated", sequence: input.stored.sequence, - location: input.shell.archivedAt === null ? "active" : "archive", + location: "active", thread: input.shell, }; } @@ -135,10 +160,7 @@ export function shellStreamItemFromThreadShell(input: { return { kind: "thread.removed", sequence: input.stored.sequence, - location: - input.stored.event.type === "thread.deleted" && input.stored.event.payload.archivedAt !== null - ? "archive" - : "active", + location: "active", threadId: input.stored.event.threadId, }; } diff --git a/apps/server/src/orchestration-v2/ThreadManagementService.ts b/apps/server/src/orchestration-v2/ThreadManagementService.ts index a85477b788..77e52bffbb 100644 --- a/apps/server/src/orchestration-v2/ThreadManagementService.ts +++ b/apps/server/src/orchestration-v2/ThreadManagementService.ts @@ -279,10 +279,9 @@ export interface ThreadManagementServiceShape { readonly projectId: ProjectId; readonly threadId: ThreadId; }) => Effect.Effect; - readonly getShellSnapshot: () => Effect.Effect< - OrchestrationV2ThreadShellSnapshot, - OrchestratorV2Error - >; + readonly getShellSnapshot: (options?: { + readonly location?: "active" | "archive"; + }) => Effect.Effect; readonly getThreadShell: OrchestratorV2["Service"]["getThreadShell"]; readonly listProjectThreads: (input: { readonly projectId: ProjectId; diff --git a/apps/server/src/orchestration-v2/WireProjection.test.ts b/apps/server/src/orchestration-v2/WireProjection.test.ts index 8c1cbc1bf8..3694d92ed4 100644 --- a/apps/server/src/orchestration-v2/WireProjection.test.ts +++ b/apps/server/src/orchestration-v2/WireProjection.test.ts @@ -1,8 +1,17 @@ -import { ThreadId, TurnItemId, type OrchestrationV2TurnItem } from "@t3tools/contracts"; +import { + MessageId, + ProjectId, + ProviderInstanceId, + ThreadId, + TurnItemId, + type OrchestrationV2ThreadProjection, + type OrchestrationV2TurnItem, +} from "@t3tools/contracts"; import { describe, expect, it } from "@effect/vitest"; import * as DateTime from "effect/DateTime"; import { projectTurnItemForWire } from "./WireProjection.ts"; +import { threadShellFromProjection } from "./ProjectionStore.ts"; const base = { id: TurnItemId.make("tool-1"), @@ -25,6 +34,60 @@ const base = { }; describe("orchestration V2 wire projection", () => { + it("keeps transcript bodies out of shell rows", () => { + const now = DateTime.makeUnsafe("2026-08-13T00:00:00.000Z"); + const threadId = ThreadId.make("thread-shell-budget"); + const projection = { + thread: { + createdBy: "user", + creationSource: "web", + id: threadId, + projectId: ProjectId.make("project-shell-budget"), + title: "Shell payload budget", + providerInstanceId: ProviderInstanceId.make("codex"), + modelSelection: null, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: null, + lineage: { + parentThreadId: null, + relationshipToParent: null, + rootThreadId: threadId, + }, + forkedFrom: null, + activeProviderThreadId: null, + createdAt: now, + updatedAt: now, + archivedAt: null, + settledOverride: null, + settledAt: null, + deletedAt: null, + }, + runs: [], + runtimeRequests: [], + messages: [ + { + id: MessageId.make("message-shell-budget"), + role: "assistant", + text: "x".repeat(1_000_000), + updatedAt: now, + }, + ], + providerSessions: [], + providerThreads: [], + turnItems: [], + visibleTurnItems: [], + plans: [], + updatedAt: now, + } as unknown as OrchestrationV2ThreadProjection; + + const shell = threadShellFromProjection(projection); + + expect(shell.latestVisibleMessage).toBeNull(); + expect(JSON.stringify(shell).length).toBeLessThan(2_000); + }); + it("summarizes oversized dynamic tool results without mutating persistence data", () => { const output = { content: [{ type: "text", text: "first line\n" + "x".repeat(100_000) }] }; const item = { ...base, output } satisfies OrchestrationV2TurnItem; diff --git a/apps/server/src/orchestration-v2/http.ts b/apps/server/src/orchestration-v2/http.ts index 045afefd53..1b8f046014 100644 --- a/apps/server/src/orchestration-v2/http.ts +++ b/apps/server/src/orchestration-v2/http.ts @@ -24,6 +24,7 @@ import { selectHistoryPageFromCursor, } from "./threadHistoryPaging.ts"; import * as ThreadManagementService from "./ThreadManagementService.ts"; +import { buildActiveShellSnapshot } from "./ShellStream.ts"; import { projectThreadProjectionForWire } from "./WireProjection.ts"; function isThreadNotFound(error: unknown): boolean { @@ -88,15 +89,13 @@ export const orchestrationHttpApiLayer = HttpApiBuilder.group( const loadShellSnapshot = Effect.fn("http.orchestration.loadShellSnapshot")(function* () { const base = yield* sql.withTransaction( Effect.gen(function* () { - const projects = yield* projectionSnapshotQuery.getShellSnapshotWithoutEnrichment(); - const threads = yield* threadManagement.getShellSnapshot(); - return { - schemaVersion: threads.schemaVersion, + const projects = yield* projectionSnapshotQuery.getProjectShellsWithoutEnrichment(); + const threads = yield* threadManagement.getShellSnapshot({ location: "active" }); + return buildActiveShellSnapshot({ + projects, + threads, snapshotSequence: yield* applicationEvents.latestApplicationSequence, - projects: projects.projects, - threads: threads.threads, - archivedThreads: threads.archivedThreads, - } as const; + }); }), ); const projects = yield* enrichProjectShells(base.projects); diff --git a/apps/server/src/orchestration-v2/runtimeLayer.test.ts b/apps/server/src/orchestration-v2/runtimeLayer.test.ts index 1f34589ec3..4200c6aa3d 100644 --- a/apps/server/src/orchestration-v2/runtimeLayer.test.ts +++ b/apps/server/src/orchestration-v2/runtimeLayer.test.ts @@ -655,16 +655,28 @@ it.layer(TestLayer)("OrchestrationV2LayerLive lifecycle", (it) => { archivedShell.archivedThreads.map((thread) => thread.id), threadId, ); + const activeOnlyShell = yield* orchestrator.getShellSnapshot({ location: "active" }); + assert.notInclude( + activeOnlyShell.threads.map((thread) => thread.id), + threadId, + ); + assert.lengthOf(activeOnlyShell.archivedThreads, 0); + const archiveOnlyShell = yield* orchestrator.getShellSnapshot({ location: "archive" }); + assert.lengthOf(archiveOnlyShell.threads, 0); + assert.include( + archiveOnlyShell.archivedThreads.map((thread) => thread.id), + threadId, + ); assert.deepEqual( shellStreamItemFromThreadShell({ stored: archive.storedEvents[0]!, shell: yield* orchestrator.getThreadShell(threadId), }), { - kind: "thread.updated", + kind: "thread.removed", sequence: archive.sequence, - location: "archive", - thread: archivedShell.archivedThreads[0]!, + location: "active", + threadId, }, ); @@ -690,7 +702,7 @@ it.layer(TestLayer)("OrchestrationV2LayerLive lifecycle", (it) => { { kind: "thread.removed", sequence: remove.sequence, - location: "archive", + location: "active", threadId, }, ); diff --git a/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts b/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts index 14fb875da5..a6e55af72b 100644 --- a/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts +++ b/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts @@ -2376,6 +2376,24 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () { ), ); + const getProjectShellsWithoutEnrichment: ProjectionSnapshotQueryShape["getProjectShellsWithoutEnrichment"] = + () => + listProjectRows(undefined).pipe( + Effect.mapError( + toPersistenceSqlOrDecodeError( + "ProjectionSnapshotQuery.getProjectShellsWithoutEnrichment:query", + "ProjectionSnapshotQuery.getProjectShellsWithoutEnrichment:decodeRows", + ), + ), + Effect.map((rows) => + Arr.filterMap(rows, (row) => + row.deletedAt === null + ? Result.succeed(mapProjectShellRow(row, null)) + : Result.failVoid, + ), + ), + ); + const getFirstActiveThreadIdByProjectId: ProjectionSnapshotQueryShape["getFirstActiveThreadIdByProjectId"] = (projectId) => getFirstActiveThreadIdByProject({ projectId }).pipe( @@ -2864,6 +2882,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () { getCounts, getActiveProjectByWorkspaceRoot, getProjectShellById, + getProjectShellsWithoutEnrichment, getFirstActiveThreadIdByProjectId, getThreadCheckpointContext, getFullThreadDiffContext, diff --git a/apps/server/src/orchestration/Services/ProjectionSnapshotQuery.ts b/apps/server/src/orchestration/Services/ProjectionSnapshotQuery.ts index 7eaee65623..acd4c2b9bc 100644 --- a/apps/server/src/orchestration/Services/ProjectionSnapshotQuery.ts +++ b/apps/server/src/orchestration/Services/ProjectionSnapshotQuery.ts @@ -142,6 +142,12 @@ export interface ProjectionSnapshotQueryShape { projectId: ProjectId, ) => Effect.Effect, ProjectionRepositoryError>; + /** Read every active project shell without hydrating thread rows or enrichment. */ + readonly getProjectShellsWithoutEnrichment: () => Effect.Effect< + ReadonlyArray, + ProjectionRepositoryError + >; + /** * Read the earliest active thread for a project. */ diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts index 3daaa28a84..44e3f4ef9c 100644 --- a/apps/server/src/ws.ts +++ b/apps/server/src/ws.ts @@ -76,6 +76,7 @@ import * as ThreadLaunchService from "./orchestration-v2/ThreadLaunchService.ts" import * as ScheduledTasks from "./scheduledTasks/ScheduledTaskService.ts"; import { archivedShellStreamItemFromThreadShell, + buildActiveShellSnapshot, coalesceShellApplicationEvents, coalesceStoredThreadEvents, composeShellStreamWithEnrichment, @@ -84,6 +85,7 @@ import { shellStreamItemsFromInitialSnapshot, shellStreamItemsFromResumeSnapshot, } from "./orchestration-v2/ShellStream.ts"; +import { ORCHESTRATION_V2_PROJECTION_SCHEMA_VERSION } from "./orchestration-v2/ProjectionStore.ts"; import { decideThreadResume, threadReplayEncodedBytes, @@ -740,18 +742,32 @@ const makeWsRpcLayer = ( readonly requestCompletionMarker?: boolean; }) { const enrichmentChanges = yield* projectEnrichment.subscribeChanges; + const loadProjectMetadataSnapshot = Effect.fn( + "ws.orchestrationV2.loadProjectMetadataSnapshot", + )(function* (snapshotSequence: number) { + const projects = yield* projectionSnapshotQuery.getProjectShellsWithoutEnrichment(); + const enriched = yield* enrichProjectShells(projects); + return { + snapshot: { + schemaVersion: ORCHESTRATION_V2_PROJECTION_SCHEMA_VERSION, + snapshotSequence, + projects: enriched.projects, + threads: [], + archivedThreads: [], + } as OrchestrationV2ShellSnapshot, + resolvedRepositoryIdentityRoots: enriched.resolvedRepositoryIdentityRoots, + }; + }); const loadSnapshot = Effect.fn("ws.orchestrationV2.loadShellSnapshot")(function* () { const base = yield* sql.withTransaction( Effect.gen(function* () { - const projects = yield* projectionSnapshotQuery.getShellSnapshotWithoutEnrichment(); - const threads = yield* threadManagement.getShellSnapshot(); - return { - schemaVersion: threads.schemaVersion, + const projects = yield* projectionSnapshotQuery.getProjectShellsWithoutEnrichment(); + const threads = yield* threadManagement.getShellSnapshot({ location: "active" }); + return buildActiveShellSnapshot({ + projects, + threads, snapshotSequence: yield* applicationEvents.latestApplicationSequence, - projects: projects.projects, - threads: threads.threads, - archivedThreads: threads.archivedThreads, - } as const; + }); }), ); const enriched = yield* enrichProjectShells(base.projects); @@ -822,7 +838,8 @@ const makeWsRpcLayer = ( Stream.filter((change) => change.repositoryIdentityResolved), Stream.groupedWithin(64, Duration.millis(25)), Stream.mapEffect((changes) => - loadSnapshot().pipe( + applicationEvents.latestApplicationSequence.pipe( + Effect.flatMap(loadProjectMetadataSnapshot), Effect.map(({ snapshot }) => shellStreamItemFromEnrichmentRefresh({ snapshot, @@ -880,11 +897,10 @@ const makeWsRpcLayer = ( Stream.concat(completionMarker, liveFrom(afterSequence)); const stream = yield* Effect.gen(function* () { - const loaded = yield* loadSnapshot(); - const initial = initialSnapshotItems(loaded); if (input.afterSequence === undefined) { + const loaded = yield* loadSnapshot(); return composeShellStreamWithEnrichment({ - initial, + initial: initialSnapshotItems(loaded), tail: completionThenLive(loaded.snapshot.snapshotSequence), enrichment: enrichmentRefreshes, }); @@ -893,13 +909,15 @@ const makeWsRpcLayer = ( const highWater = yield* applicationEvents.latestApplicationSequence; const replayGap = highWater - input.afterSequence; if (replayGap < 0 || replayGap > SHELL_RESUME_MAX_GAP) { + const loaded = yield* loadSnapshot(); return composeShellStreamWithEnrichment({ - initial, + initial: initialSnapshotItems(loaded), tail: completionThenLive(loaded.snapshot.snapshotSequence), enrichment: enrichmentRefreshes, }); } + const loaded = yield* loadProjectMetadataSnapshot(highWater); const replay = toShellStream( applicationEvents.readApplicationEvents({ afterSequence: input.afterSequence, @@ -936,12 +954,12 @@ const makeWsRpcLayer = ( const getOrchestrationV2ArchivedShellSnapshot = sql .withTransaction( Effect.gen(function* () { - const projects = yield* projectionSnapshotQuery.getShellSnapshotWithoutEnrichment(); - const threads = yield* threadManagement.getShellSnapshot(); + const projects = yield* projectionSnapshotQuery.getProjectShellsWithoutEnrichment(); + const threads = yield* threadManagement.getShellSnapshot({ location: "archive" }); return { schemaVersion: threads.schemaVersion, snapshotSequence: yield* applicationEvents.latestApplicationSequence, - projects: projects.projects, + projects, threads: threads.archivedThreads, } as const; }), diff --git a/docs/internals/performance-regressions.md b/docs/internals/performance-regressions.md index 01799be8b0..2b4905fd87 100644 --- a/docs/internals/performance-regressions.md +++ b/docs/internals/performance-regressions.md @@ -21,6 +21,8 @@ The v2 checks pin these invariants: replacing stale state with a current snapshot. - Oversized dynamic-tool results and detail strings are reduced only at the wire boundary; the persisted event remains complete. +- The initial shell contains active navigation rows only. Archived rows use the dedicated archive + query, and transcript message bodies stay in thread detail regardless of message size. - Shell resume sends deltas plus compact repository-enrichment metadata, not another full project and thread snapshot. - Known idle sends and interrupts do not fetch a full thread projection before dispatch. diff --git a/packages/client-runtime/src/state/shellReducer.test.ts b/packages/client-runtime/src/state/shellReducer.test.ts index 8aa8fd1772..2527aca1ca 100644 --- a/packages/client-runtime/src/state/shellReducer.test.ts +++ b/packages/client-runtime/src/state/shellReducer.test.ts @@ -390,7 +390,7 @@ describe("applyShellStreamEvent", () => { expect(next.projects[0]?.repositoryIdentity).toEqual(liveIdentity); }); - it("moves a thread between active and archive without duplicating it", () => { + it("keeps archive deltas out of the normal shell cache", () => { const archived = applyShellStreamEvent(v2ShellSnapshot, { kind: "thread.updated", sequence: 3, @@ -398,7 +398,7 @@ describe("applyShellStreamEvent", () => { thread: { ...v2ThreadShell, archivedAt: v2ThreadShell.updatedAt }, }); expect(archived.threads).toEqual([]); - expect(archived.archivedThreads).toHaveLength(1); + expect(archived.archivedThreads).toEqual([]); const active = applyShellStreamEvent(archived, { kind: "thread.updated", diff --git a/packages/client-runtime/src/state/shellReducer.ts b/packages/client-runtime/src/state/shellReducer.ts index c5d0e0631f..3272cdc959 100644 --- a/packages/client-runtime/src/state/shellReducer.ts +++ b/packages/client-runtime/src/state/shellReducer.ts @@ -131,10 +131,10 @@ export function applyShellStreamEvent( event.location === "active" ? upsertById(withoutThread(snapshot.threads), event.thread) : withoutThread(snapshot.threads), - archivedThreads: - event.location === "archive" - ? upsertById(withoutThread(snapshot.archivedThreads), event.thread) - : withoutThread(snapshot.archivedThreads), + // The archive has its own bounded query/subscription. Older servers may + // still send archive-located deltas here; remove them from the normal + // shell instead of growing its persisted cache again. + archivedThreads: withoutThread(snapshot.archivedThreads), snapshotSequence: event.sequence, }; }