perf(server): keep shell snapshots bounded and active-only

- Omit transcript bodies from shell rows
- Query archived threads separately and stream compact resume metadata
This commit is contained in:
Julius Marminge committed 2026-08-15 16:51:45 +02:00
1 parent 4ef9640d2e
commit 4442054fc7
15 files changed
+297 -127

No files matched your search

@@ -159,10 +159,9 @@ export interface OrchestratorV2Shape {
},
OrchestratorV2Error
>;
readonly getShellSnapshot: () => Effect.Effect<
OrchestrationV2ThreadShellSnapshot,
OrchestratorV2Error
>;
readonly getShellSnapshot: (options?: {
readonly location?: "active" | "archive";
}) => Effect.Effect<OrchestrationV2ThreadShellSnapshot, OrchestratorV2Error>;
readonly getThreadShell: (
threadId: ThreadId,
) => Effect.Effect<OrchestrationV2ThreadShell | null, OrchestratorV2Error>;
@@ -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({
@@ -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 ?? [], []);
}),
);
@@ -103,10 +103,9 @@ export interface ProjectionStoreV2Shape {
readonly apply: (
event: OrchestrationV2DomainEvent,
) => Effect.Effect<void, ProjectionStoreV2Error>;
readonly getShellSnapshot: () => Effect.Effect<
OrchestrationV2ThreadShellSnapshot,
ProjectionStoreV2Error
>;
readonly getShellSnapshot: (options?: {
readonly location?: "active" | "archive";
}) => Effect.Effect<OrchestrationV2ThreadShellSnapshot, ProjectionStoreV2Error>;
readonly getThreadShell: (
threadId: ThreadId,
) => Effect.Effect<OrchestrationV2ThreadShell | null, ProjectionStoreV2Error>;
@@ -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<ProjectionStoreV2, never, SqlClient.SqlClient> =
),
);
const selectShellThreadRows = (threadId?: ThreadId) =>
const selectShellThreadRows = (threadId?: ThreadId, location?: "active" | "archive") =>
sql<ShellThreadRow>`
SELECT
t.thread_id,
@@ -2302,13 +2280,6 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
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<ProjectionStoreV2, never, SqlClient.SqlClient> =
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<ProjectionStoreV2, never, SqlClient.SqlClient> =
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<ProjectionStoreV2, never, SqlClient.SqlClient> =
: null,
lastError: row.last_error,
pendingRuntimeRequest,
latestVisibleMessage,
latestUserMessageAt:
row.latest_user_message_at === null
? null
@@ -2554,30 +2526,51 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
} 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 = <A>(
read: (ids: ReadonlyArray<ThreadId>) => Effect.Effect<ReadonlyArray<A>, unknown>,
) =>
threadIds.length === 0 ? Effect.succeed([] as ReadonlyArray<A>) : 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<ProjectionStoreV2, never, SqlClient.SqlClient> =
);
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<ProjectionStoreV2> = 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)),
);
@@ -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",
});
});
@@ -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<OrchestrationProjectShell>;
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<ApplicationStoredEvent>,
@@ -124,10 +141,18 @@ export function shellStreamItemFromThreadShell(input: {
readonly shell: OrchestrationV2ThreadShell | null;
}): Exclude<OrchestrationV2ShellStreamItem, { readonly kind: "snapshot" }> {
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,
};
}
@@ -279,10 +279,9 @@ export interface ThreadManagementServiceShape {
readonly projectId: ProjectId;
readonly threadId: ThreadId;
}) => Effect.Effect<OrchestrationV2ThreadProjection, ThreadManagementError>;
readonly getShellSnapshot: () => Effect.Effect<
OrchestrationV2ThreadShellSnapshot,
OrchestratorV2Error
>;
readonly getShellSnapshot: (options?: {
readonly location?: "active" | "archive";
}) => Effect.Effect<OrchestrationV2ThreadShellSnapshot, OrchestratorV2Error>;
readonly getThreadShell: OrchestratorV2["Service"]["getThreadShell"];
readonly listProjectThreads: (input: {
readonly projectId: ProjectId;
@@ -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;
+7 -8
View File
@@ -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);
@@ -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,
},
);
@@ -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,
@@ -142,6 +142,12 @@ export interface ProjectionSnapshotQueryShape {
projectId: ProjectId,
) => Effect.Effect<Option.Option<OrchestrationProjectShell>, ProjectionRepositoryError>;
/** Read every active project shell without hydrating thread rows or enrichment. */
readonly getProjectShellsWithoutEnrichment: () => Effect.Effect<
ReadonlyArray<OrchestrationProjectShell>,
ProjectionRepositoryError
>;
/**
* Read the earliest active thread for a project.
*/
+34 -16
View File
@@ -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;
}),
@@ -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.
@@ -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",
@@ -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,
};
}