perf(server): use one query for buffered provider events (#9706)

This commit is contained in:
Theo Browne authored and GitHub committed 2026-09-04 08:46:29 -07:00
1 parent 3bbbc1d9fd
commit dffb4cd3b1
10 files changed
+228 -65

No files matched your search

@@ -107,6 +107,7 @@ describe("CheckpointDiffQuery.layer", () => {
toCheckpointRef,
});
}),
getThreadRuntimeContext: () => Effect.die("unused"),
getThreadShellById: () => Effect.succeed(Option.none()),
getThreadDetailById: () => Effect.succeed(Option.none()),
getThreadDetailSnapshot: () => Effect.succeed(Option.none()),
@@ -203,6 +204,7 @@ describe("CheckpointDiffQuery.layer", () => {
getFirstActiveThreadIdByProjectId: () => Effect.succeed(Option.none()),
getThreadCheckpointContext: () => Effect.succeed(Option.some(threadCheckpointContext)),
getFullThreadDiffContext: () => Effect.die("unused"),
getThreadRuntimeContext: () => Effect.die("unused"),
getThreadShellById: () => Effect.succeed(Option.none()),
getThreadDetailById: () => Effect.succeed(Option.none()),
getThreadDetailSnapshot: () => Effect.succeed(Option.none()),
@@ -289,6 +291,7 @@ describe("CheckpointDiffQuery.layer", () => {
getFirstActiveThreadIdByProjectId: () => Effect.succeed(Option.none()),
getThreadCheckpointContext: () => Effect.succeed(Option.some(threadCheckpointContext)),
getFullThreadDiffContext: () => Effect.die("unused"),
getThreadRuntimeContext: () => Effect.die("unused"),
getThreadShellById: () => Effect.succeed(Option.none()),
getThreadDetailById: () => Effect.succeed(Option.none()),
getThreadDetailSnapshot: () => Effect.succeed(Option.none()),
@@ -360,6 +363,7 @@ describe("CheckpointDiffQuery.layer", () => {
getFirstActiveThreadIdByProjectId: () => Effect.succeed(Option.none()),
getThreadCheckpointContext: () => Effect.succeed(Option.some(threadCheckpointContext)),
getFullThreadDiffContext: () => Effect.die("unused"),
getThreadRuntimeContext: () => Effect.die("unused"),
getThreadShellById: () => Effect.succeed(Option.none()),
getThreadDetailById: () => Effect.succeed(Option.none()),
getThreadDetailSnapshot: () => Effect.succeed(Option.none()),
@@ -416,6 +420,7 @@ describe("CheckpointDiffQuery.layer", () => {
getFirstActiveThreadIdByProjectId: () => Effect.succeed(Option.none()),
getThreadCheckpointContext: () => Effect.succeed(Option.none()),
getFullThreadDiffContext: () => Effect.succeed(Option.none()),
getThreadRuntimeContext: () => Effect.die("unused"),
getThreadShellById: () => Effect.succeed(Option.none()),
getThreadDetailById: () => Effect.succeed(Option.none()),
getThreadDetailSnapshot: () => Effect.succeed(Option.none()),
@@ -418,6 +418,7 @@ describe("OrchestrationEngine", () => {
getFirstActiveThreadIdByProjectId: () => Effect.succeed(Option.none()),
getThreadCheckpointContext: () => Effect.succeed(Option.none()),
getFullThreadDiffContext: () => Effect.succeed(Option.none()),
getThreadRuntimeContext: () => Effect.die("unused"),
getThreadShellById: () => Effect.succeed(Option.none()),
getThreadDetailById: () => Effect.succeed(Option.none()),
getThreadDetailSnapshot: () => Effect.succeed(Option.none()),
@@ -22,6 +22,7 @@ import * as ThreadPlanProgress from "../ThreadPlanProgress.ts";
import { ProjectionSnapshotQuery } from "../Services/ProjectionSnapshotQuery.ts";
import { encodeThreadDetailPageCursor } from "../threadDetailCursor.ts";
import { projectThreadDetailSnapshot } from "../ActivityPayloadProjection.ts";
import { makeSqlStatementCounter } from "../../../integration/SqlStatementCounter.integration.ts";
const asProjectId = (value: string): ProjectId => ProjectId.make(value);
const asTurnId = (value: string): TurnId => TurnId.make(value);
@@ -560,6 +561,38 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
},
]);
}
const counter = makeSqlStatementCounter();
const context = yield* snapshotQuery
.getThreadRuntimeContext(ThreadId.make("thread-1"))
.pipe(Effect.withTracer(counter.tracer));
assert.equal(counter.count(), 1);
assert.equal(context._tag, "Some");
if (context._tag === "Some") {
assert.deepEqual(context.value, {
id: ThreadId.make("thread-1"),
title: "Thread 1",
session: snapshot.threads[0]?.session,
});
}
yield* sql`
UPDATE projection_thread_sessions
SET status = 'starting', active_turn_id = NULL, provider_name = 'claudeAgent',
provider_instance_id = 'claude-secondary', last_error = 'Starting another session'
WHERE thread_id = 'thread-1'
`;
const changedContext = yield* snapshotQuery.getThreadRuntimeContext(
ThreadId.make("thread-1"),
);
assert.equal(changedContext._tag, "Some");
if (changedContext._tag === "Some") {
assert.equal(changedContext.value.session?.status, "starting");
assert.equal(changedContext.value.session?.activeTurnId, null);
assert.equal(changedContext.value.session?.providerName, "claudeAgent");
assert.equal(changedContext.value.session?.providerInstanceId, "claude-secondary");
assert.equal(changedContext.value.session?.lastError, "Starting another session");
}
}),
);
@@ -680,6 +713,22 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
[ThreadId.make("thread-archived")],
);
assert.equal(archivedShellSnapshot.threads[0]?.archivedAt, "2026-04-06T00:00:06.000Z");
const activeContext = yield* snapshotQuery.getThreadRuntimeContext(
ThreadId.make("thread-active"),
);
assert.equal(activeContext._tag, "Some");
if (activeContext._tag === "Some") assert.equal(activeContext.value.session, null);
for (const threadId of ["thread-archived", "thread-missing"]) {
assert.equal(
(yield* snapshotQuery.getThreadRuntimeContext(ThreadId.make(threadId)))._tag,
"None",
);
}
yield* sql`UPDATE projection_threads SET deleted_at = '2026-04-06T00:00:08.000Z' WHERE thread_id = 'thread-active'`;
assert.equal(
(yield* snapshotQuery.getThreadRuntimeContext(ThreadId.make("thread-active")))._tag,
"None",
);
}),
);
@@ -113,6 +113,11 @@ const ProjectionThreadActivityIdRowSchema = Schema.Struct({
activityId: ProjectionThreadActivity.fields.activityId,
});
const ProjectionThreadSessionDbRowSchema = ProjectionThreadSession;
const ProjectionThreadRuntimeContextDbRowSchema = Schema.Struct({
id: ThreadId,
title: Schema.String,
session: Schema.NullOr(ProjectionThreadSessionDbRowSchema),
});
const ProjectionCheckpointDbRowSchema = ProjectionCheckpoint.mapFields(
Struct.assign({
files: Schema.fromJsonString(Schema.Array(OrchestrationCheckpointFile)),
@@ -1038,6 +1043,40 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
`,
});
const getThreadRuntimeContextRow = SqlSchema.findOneOption({
Request: ThreadIdLookupInput,
Result: ProjectionThreadRuntimeContextDbRowSchema,
execute: ({ threadId }) =>
sql`
SELECT
threads.thread_id AS id,
threads.title,
sessions.thread_id AS "threadId",
sessions.status,
sessions.provider_name AS "providerName",
sessions.provider_instance_id AS "providerInstanceId",
sessions.runtime_mode AS "runtimeMode",
sessions.active_turn_id AS "activeTurnId",
sessions.last_error AS "lastError",
sessions.updated_at AS "updatedAt"
FROM projection_threads AS threads
LEFT JOIN projection_thread_sessions AS sessions
ON sessions.thread_id = threads.thread_id
WHERE threads.thread_id = ${threadId}
AND threads.deleted_at IS NULL
AND threads.archived_at IS NULL
LIMIT 1
`.pipe(
Effect.map((rows) =>
rows.map((row) => ({
id: row.id,
title: row.title,
session: row.threadId === null ? null : row,
})),
),
),
});
const listThreadMessageRowsByThread = SqlSchema.findAll({
Request: ThreadIdLookupInput,
Result: ProjectionThreadMessageDbRowSchema,
@@ -2764,6 +2803,23 @@ pending_approval_requests AS (
} satisfies OrchestrationThreadShell);
});
const getThreadRuntimeContext: ProjectionSnapshotQueryShape["getThreadRuntimeContext"] =
Effect.fn("ProjectionSnapshotQuery.getThreadRuntimeContext")(function* (threadId) {
const context = yield* getThreadRuntimeContextRow({ threadId }).pipe(
Effect.mapError(
toPersistenceSqlOrDecodeError(
"ProjectionSnapshotQuery.getThreadRuntimeContext:query",
"ProjectionSnapshotQuery.getThreadRuntimeContext:decodeRow",
),
),
);
return Option.map(context, (row) => ({
id: row.id,
title: row.title,
session: row.session === null ? null : mapSessionRow(row.session),
}));
});
// Contiguous turn range bounding a windowed detail read; undefined loads the
// full thread. Resolved from a window request inside the snapshot
// transaction (see getThreadDetailSnapshot).
@@ -3200,6 +3256,7 @@ pending_approval_requests AS (
getThreadCheckpointContext,
getFullThreadDiffContext,
getThreadShellById,
getThreadRuntimeContext,
getThreadDetailById,
getThreadDetailSnapshot,
} satisfies ProjectionSnapshotQueryShape;
@@ -24,6 +24,7 @@ import {
TurnId,
} from "@t3tools/contracts";
import * as Clock from "effect/Clock";
import * as Deferred from "effect/Deferred";
import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit";
import * as Layer from "effect/Layer";
@@ -31,6 +32,7 @@ import * as ManagedRuntime from "effect/ManagedRuntime";
import * as PubSub from "effect/PubSub";
import * as Scope from "effect/Scope";
import * as Stream from "effect/Stream";
import * as Tracer from "effect/Tracer";
import { it as effectIt } from "@effect/vitest";
import { afterEach, describe, expect, it } from "vite-plus/test";
@@ -55,6 +57,7 @@ import { ProjectionSnapshotQuery } from "../Services/ProjectionSnapshotQuery.ts"
import { ServerConfig } from "../../config.ts";
import { ServerSettingsService } from "../../serverSettings.ts";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { makeSqlStatementCounter } from "../../../integration/SqlStatementCounter.integration.ts";
function makeTestServerSettingsLayer(overrides: Partial<ServerSettings> = {}) {
return ServerSettingsService.layerTest(overrides);
@@ -98,7 +101,12 @@ function isLegacyTurnCompletedEvent(
}
function createProviderServiceHarness() {
const runtimeEventPubSub = Effect.runSync(PubSub.unbounded<ProviderRuntimeEvent>());
const runtimeEventPubSub = Effect.runSync(
PubSub.unbounded<{
readonly events: ReadonlyArray<ProviderRuntimeEvent>;
readonly enqueued?: Deferred.Deferred<void>;
}>(),
);
const runtimeSessions: ProviderSession[] = [];
const unsupported = () => Effect.die(new Error("Unsupported provider call in test")) as never;
@@ -129,7 +137,16 @@ function createProviderServiceHarness() {
rollbackConversation: () => unsupported(),
uploadFeedback: () => unsupported(),
get streamEvents() {
return Stream.fromPubSub(runtimeEventPubSub);
return Stream.fromPubSub(runtimeEventPubSub).pipe(
Stream.flatMap(({ events, enqueued }) =>
Stream.concat(
Stream.fromIterable(events),
enqueued
? Stream.fromEffect(Deferred.succeed(enqueued, undefined)).pipe(Stream.drain)
: Stream.empty,
),
),
);
},
};
@@ -158,12 +175,24 @@ function createProviderServiceHarness() {
};
const emit = (event: LegacyProviderRuntimeEvent): void => {
Effect.runSync(PubSub.publish(runtimeEventPubSub, normalizeLegacyEvent(event)));
Effect.runSync(PubSub.publish(runtimeEventPubSub, { events: [normalizeLegacyEvent(event)] }));
};
const emitAndWaitForEnqueue = Effect.fnUntraced(function* (
events: ReadonlyArray<LegacyProviderRuntimeEvent>,
) {
const enqueued = yield* Deferred.make<void>();
yield* PubSub.publish(runtimeEventPubSub, {
events: events.map(normalizeLegacyEvent),
enqueued,
});
yield* Deferred.await(enqueued);
});
return {
service,
emit,
emitAndWaitForEnqueue,
setSession,
};
}
@@ -232,6 +261,7 @@ describe("ProviderRuntimeIngestion", () => {
const workspaceRoot = makeTempDir("t3-provider-project-");
NodeFS.mkdirSync(NodePath.join(workspaceRoot, ".git"));
const provider = createProviderServiceHarness();
const sqlCounter = makeSqlStatementCounter();
const orchestrationLayer = OrchestrationEngineLive.pipe(
Layer.provide(OrchestrationProjectionSnapshotQueryLive),
Layer.provide(OrchestrationProjectionPipelineLive),
@@ -256,15 +286,22 @@ describe("ProviderRuntimeIngestion", () => {
Layer.provideMerge(makeTestServerSettingsLayer(options?.serverSettings)),
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
Layer.provideMerge(NodeServices.layer),
Layer.provideMerge(Layer.succeed(Tracer.Tracer, sqlCounter.tracer)),
);
runtime = ManagedRuntime.make(layer);
const engine = await runtime.runPromise(Effect.service(OrchestrationEngineService));
const snapshotQuery = await runtime.runPromise(Effect.service(ProjectionSnapshotQuery));
const ingestion = await runtime.runPromise(Effect.service(ProviderRuntimeIngestionService));
const testRuntime = ManagedRuntime.make(layer);
runtime = testRuntime;
const engine = await testRuntime.runPromise(Effect.service(OrchestrationEngineService));
const snapshotQuery = await testRuntime.runPromise(Effect.service(ProjectionSnapshotQuery));
const ingestion = await testRuntime.runPromise(Effect.service(ProviderRuntimeIngestionService));
scope = await Effect.runPromise(Scope.make("sequential"));
await Effect.runPromise(ingestion.start().pipe(Scope.provide(scope)));
const drain = () => Effect.runPromise(ingestion.drain);
const dispatch = (command: OrchestrationCommand) => Effect.runPromise(engine.dispatch(command));
await testRuntime.runPromise(ingestion.start().pipe(Scope.provide(scope)));
const drain = () => testRuntime.runPromise(ingestion.drain);
const dispatch = (command: OrchestrationCommand) =>
testRuntime.runPromise(engine.dispatch(command));
const emitAndDrain = (events: ReadonlyArray<LegacyProviderRuntimeEvent>) =>
testRuntime.runPromise(
provider.emitAndWaitForEnqueue(events).pipe(Effect.andThen(ingestion.drain)),
);
const createdAt = "2026-01-01T00:00:00.000Z";
await dispatch({
@@ -322,8 +359,10 @@ describe("ProviderRuntimeIngestion", () => {
return {
engine,
dispatch,
readModel: () => Effect.runPromise(snapshotQuery.getSnapshot()),
readModel: () => testRuntime.runPromise(snapshotQuery.getSnapshot()),
emit: provider.emit,
emitAndDrain,
sqlCount: sqlCounter.count,
setProviderSession: provider.setSession,
drain,
};
@@ -2104,39 +2143,40 @@ describe("ProviderRuntimeIngestion", () => {
expect(proposedPlan?.planMarkdown).toBe("## Buffered plan\n\n- first\n- second");
});
it("buffers assistant deltas by default until completion", async () => {
it("buffers assistant deltas with one lifecycle query per event until completion", async () => {
const harness = await createHarness();
const now = "2026-01-01T00:00:00.000Z";
harness.emit({
type: "turn.started",
eventId: asEventId("evt-turn-started-buffered"),
provider: ProviderDriverKind.make("codex"),
createdAt: now,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-buffered"),
});
await waitForThread(
harness.readModel,
(thread) =>
thread.session?.status === "running" && thread.session?.activeTurnId === "turn-buffered",
);
harness.emit({
type: "content.delta",
eventId: asEventId("evt-message-delta-buffered"),
provider: ProviderDriverKind.make("codex"),
createdAt: now,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-buffered"),
itemId: asItemId("item-buffered"),
payload: {
streamKind: "assistant_text",
delta: "buffer me",
await harness.emitAndDrain([
{
type: "turn.started",
eventId: asEventId("evt-turn-started-buffered"),
provider: ProviderDriverKind.make("codex"),
createdAt: now,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-buffered"),
},
});
]);
const eventCount = 1_000;
const before = harness.sqlCount();
await harness.emitAndDrain(
Array.from({ length: eventCount }, (_, index) => ({
type: "content.delta",
eventId: asEventId(`evt-message-delta-buffered-${index}`),
provider: ProviderDriverKind.make("codex"),
createdAt: now,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-buffered"),
itemId: asItemId("item-buffered"),
payload: {
streamKind: "assistant_text",
delta: "a",
},
})),
);
expect(harness.sqlCount() - before).toBe(eventCount);
await harness.drain();
const midReadModel = await harness.readModel();
const midThread = midReadModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
expect(
@@ -2145,30 +2185,25 @@ describe("ProviderRuntimeIngestion", () => {
),
).toBe(false);
harness.emit({
type: "item.completed",
eventId: asEventId("evt-message-completed-buffered"),
provider: ProviderDriverKind.make("codex"),
createdAt: now,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-buffered"),
itemId: asItemId("item-buffered"),
payload: {
itemType: "assistant_message",
status: "completed",
await harness.emitAndDrain([
{
type: "item.completed",
eventId: asEventId("evt-message-completed-buffered"),
provider: ProviderDriverKind.make("codex"),
createdAt: now,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-buffered"),
itemId: asItemId("item-buffered"),
payload: {
itemType: "assistant_message",
status: "completed",
},
},
});
const thread = await waitForThread(harness.readModel, (entry) =>
entry.messages.some(
(message: ProviderRuntimeTestMessage) =>
message.id === "assistant:item-buffered" && !message.streaming,
),
);
const message = thread.messages.find(
(entry: ProviderRuntimeTestMessage) => entry.id === "assistant:item-buffered",
);
expect(message?.text).toBe("buffer me");
]);
const readModel = await harness.readModel();
const thread = readModel.threads.find((entry) => entry.id === asThreadId("thread-1"));
const message = thread?.messages.find((entry) => entry.id === "assistant:item-buffered");
expect(message?.text).toBe("a".repeat(eventCount));
expect(message?.streaming).toBe(false);
});
@@ -1018,9 +1018,11 @@ const make = Effect.gen(function* () {
.pipe(Effect.map(Option.getOrUndefined));
});
const resolveThreadShell = Effect.fn("resolveThreadShell")(function* (threadId: ThreadId) {
const resolveThreadRuntimeContext = Effect.fn("resolveThreadRuntimeContext")(function* (
threadId: ThreadId,
) {
return yield* projectionSnapshotQuery
.getThreadShellById(threadId)
.getThreadRuntimeContext(threadId)
.pipe(Effect.map(Option.getOrUndefined));
});
@@ -1562,7 +1564,7 @@ const make = Effect.gen(function* () {
return;
}
const thread = yield* resolveThreadShell(event.threadId);
const thread = yield* resolveThreadRuntimeContext(event.threadId);
if (!thread) return;
let loadedThreadDetail: OrchestrationThread | null | undefined;
@@ -193,6 +193,14 @@ export interface ProjectionSnapshotQueryShape {
threadId: ThreadId,
) => Effect.Effect<Option.Option<OrchestrationThreadShell>, ProjectionRepositoryError>;
/** Read the active thread and session facts used to ingest provider events. */
readonly getThreadRuntimeContext: (
threadId: ThreadId,
) => Effect.Effect<
Option.Option<Pick<OrchestrationThreadShell, "id" | "title" | "session">>,
ProjectionRepositoryError
>;
/**
* Read a single active thread detail snapshot by id.
*/
@@ -43,6 +43,7 @@ const makeProjectionSnapshotQueryLayer = (project: OrchestrationProject) =>
getFirstActiveThreadIdByProjectId: () => Effect.die("unused"),
getThreadCheckpointContext: () => Effect.die("unused"),
getFullThreadDiffContext: () => Effect.die("unused"),
getThreadRuntimeContext: () => Effect.die("unused"),
getThreadShellById: () => Effect.die("unused"),
getThreadDetailById: () => Effect.die("unused"),
getThreadDetailSnapshot: () => Effect.die("unused"),
@@ -219,6 +219,7 @@ describe("ProviderSessionReaper", () => {
getFirstActiveThreadIdByProjectId: () => Effect.die("unused"),
getThreadCheckpointContext: () => Effect.die("unused"),
getFullThreadDiffContext: () => Effect.die("unused"),
getThreadRuntimeContext: () => Effect.die("unused"),
getThreadShellById: (threadId) =>
Effect.succeed(
input.readModel.threads.find((thread) => thread.id === threadId)
@@ -138,6 +138,7 @@ it.effect("launchStartupHeartbeat does not block the caller while counts are loa
getFirstActiveThreadIdByProjectId: () => Effect.succeed(Option.none()),
getThreadCheckpointContext: () => Effect.succeed(Option.none()),
getFullThreadDiffContext: () => Effect.succeed(Option.none()),
getThreadRuntimeContext: () => Effect.die("unused"),
getThreadShellById: () => Effect.succeed(Option.none()),
getThreadDetailById: () => Effect.succeed(Option.none()),
getThreadDetailSnapshot: () => Effect.succeed(Option.none()),
@@ -211,6 +212,7 @@ it.effect("resolveAutoBootstrapWelcomeTargets returns existing project and threa
getFirstActiveThreadIdByProjectId: () => Effect.succeed(Option.some(bootstrapThreadId)),
getThreadCheckpointContext: () => Effect.succeed(Option.none()),
getFullThreadDiffContext: () => Effect.succeed(Option.none()),
getThreadRuntimeContext: () => Effect.die("unused"),
getThreadShellById: () => Effect.die("unused"),
getThreadDetailById: () => Effect.die("unused"),
getThreadDetailSnapshot: () => Effect.die("unused"),
@@ -265,6 +267,7 @@ it.effect("resolveAutoBootstrapWelcomeTargets creates a project and thread when
getFirstActiveThreadIdByProjectId: () => Effect.succeed(Option.none()),
getThreadCheckpointContext: () => Effect.succeed(Option.none()),
getFullThreadDiffContext: () => Effect.succeed(Option.none()),
getThreadRuntimeContext: () => Effect.die("unused"),
getThreadShellById: () => Effect.die("unused"),
getThreadDetailById: () => Effect.die("unused"),
getThreadDetailSnapshot: () => Effect.die("unused"),
@@ -328,6 +331,7 @@ it.effect("resolveAutoBootstrapWelcomeTargets preserves typed UUID generation fa
getFirstActiveThreadIdByProjectId: () => Effect.succeed(Option.none()),
getThreadCheckpointContext: () => Effect.succeed(Option.none()),
getFullThreadDiffContext: () => Effect.succeed(Option.none()),
getThreadRuntimeContext: () => Effect.die("unused"),
getThreadShellById: () => Effect.die("unused"),
getThreadDetailById: () => Effect.die("unused"),
getThreadDetailSnapshot: () => Effect.die("unused"),