TypeScript
perf(server): batch projector cursor writes (#9671)
Theo Browne2263e13fda8c
diff --git a/apps/server/src/orchestration/Layers/ProjectionPipeline.test.ts b/apps/server/src/orchestration/Layers/ProjectionPipeline.test.tsindex 986c078c1c5..0249844864f 100644--- a/apps/server/src/orchestration/Layers/ProjectionPipeline.test.ts+++ b/apps/server/src/orchestration/Layers/ProjectionPipeline.test.ts@@ -20,6 +20,7 @@ import * as Layer from "effect/Layer";import * as Path from "effect/Path";import * as SqlClient from "effect/unstable/sql/SqlClient";+import { makeSqlStatementCounter } from "../../../integration/SqlStatementCounter.integration.ts";import { OrchestrationCommandReceiptRepositoryLive } from "../../persistence/Layers/OrchestrationCommandReceipts.ts";import { OrchestrationEventStoreLive } from "../../persistence/Layers/OrchestrationEventStore.ts";import {@@ -27,6 +28,7 @@ import {SqlitePersistenceMemory,} from "../../persistence/Layers/Sqlite.ts";import { OrchestrationEventStore } from "../../persistence/Services/OrchestrationEventStore.ts";+import { ProjectionStateRepository } from "../../persistence/Services/ProjectionState.ts";import * as RepositoryIdentityResolver from "../../project/RepositoryIdentityResolver.ts";import { OrchestrationEngineLive } from "./OrchestrationEngine.ts";import {@@ -58,6 +60,54 @@ const exists = (filePath: string) =>const BaseTestLayer = makeProjectionPipelinePrefixedTestLayer("t3-projection-pipeline-test-");+it.layer(Layer.fresh(makeProjectionPipelinePrefixedTestLayer("t3-projection-cursor-batch-")))(+ "OrchestrationProjectionPipeline cursor batches",+ (it) => {+ it.effect("writes a project and all projector cursors in two statements", () =>+ Effect.gen(function* () {+ const projectionPipeline = yield* OrchestrationProjectionPipeline;+ const eventStore = yield* OrchestrationEventStore;+ const projectionState = yield* ProjectionStateRepository;+ const counter = makeSqlStatementCounter();+ const createdAt = "2026-01-01T00:00:00.000Z";+ const event = yield* eventStore.append({+ type: "project.created",+ eventId: EventId.make("evt-cursor-batch-project"),+ aggregateKind: "project",+ aggregateId: ProjectId.make("project-cursor-batch"),+ occurredAt: createdAt,+ commandId: CommandId.make("cmd-cursor-batch-project"),+ causationEventId: null,+ correlationId: null,+ metadata: {},+ payload: {+ projectId: ProjectId.make("project-cursor-batch"),+ title: "Cursor batch project",+ workspaceRoot: "/tmp/project-cursor-batch",+ defaultModelSelection: null,+ scripts: [],+ createdAt,+ updatedAt: createdAt,+ },+ });++ yield* projectionPipeline.projectEvent(event).pipe(Effect.withTracer(counter.tracer));+ assert.strictEqual(counter.count(), 2);+ assert.deepEqual(+ yield* projectionState.listAll(),+ Object.values(ORCHESTRATION_PROJECTOR_NAMES)+ .sort()+ .map((projector) => ({+ projector,+ lastAppliedSequence: event.sequence,+ updatedAt: createdAt,+ })),+ );+ }),+ );+ },+);+it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => {it.effect("bootstraps all projection states and writes projection rows", () =>Effect.gen(function* () {@@ -813,6 +863,8 @@ it.layer(},});+ const projectionState = yield* ProjectionStateRepository;+ const cursorsBeforeFailure = yield* projectionState.listAll();yield* sql`CREATE TRIGGER fail_thread_messages_projection_state_updateBEFORE UPDATE ON projection_state@@ -822,39 +874,39 @@ it.layer(END;`;- const result = yield* Effect.result(- appendAndProject({- type: "thread.message-sent",- eventId: EventId.make("evt-rollback-3"),- aggregateKind: "thread",- aggregateId: ThreadId.make("thread-rollback"),- occurredAt: now,- commandId: CommandId.make("cmd-rollback-3"),- causationEventId: null,- correlationId: CorrelationId.make("cmd-rollback-3"),- metadata: {},- payload: {- threadId: ThreadId.make("thread-rollback"),- messageId: MessageId.make("message-rollback"),- role: "user",- text: "Rollback me",- attachments: [- {- type: "image",- id: "thread-rollback-att-1",- name: "rollback.png",- mimeType: "image/png",- sizeBytes: 5,- },- ],- turnId: null,- streaming: false,- createdAt: now,- updatedAt: now,- },- }),- );+ const pendingEvent = yield* eventStore.append({+ type: "thread.message-sent",+ eventId: EventId.make("evt-rollback-3"),+ aggregateKind: "thread",+ aggregateId: ThreadId.make("thread-rollback"),+ occurredAt: now,+ commandId: CommandId.make("cmd-rollback-3"),+ causationEventId: null,+ correlationId: CorrelationId.make("cmd-rollback-3"),+ metadata: {},+ payload: {+ threadId: ThreadId.make("thread-rollback"),+ messageId: MessageId.make("message-rollback"),+ role: "user",+ text: "Rollback me",+ attachments: [+ {+ type: "image",+ id: "thread-rollback-att-1",+ name: "rollback.png",+ mimeType: "image/png",+ sizeBytes: 5,+ },+ ],+ turnId: null,+ streaming: false,+ createdAt: now,+ updatedAt: now,+ },+ });+ const result = yield* Effect.result(projectionPipeline.projectEvent(pendingEvent));assert.equal(result._tag, "Failure");+ assert.deepEqual(yield* projectionState.listAll(), cursorsBeforeFailure);const rows = yield* sql<{readonly count: number;@@ -869,6 +921,21 @@ it.layer(const attachmentPath = path.join(attachmentsDir, "thread-rollback-att-1.png");assert.isFalse(yield* exists(attachmentPath));yield* sql`DROP TRIGGER IF EXISTS fail_thread_messages_projection_state_update`;++ yield* projectionPipeline.bootstrap;+ yield* projectionPipeline.bootstrap;+ assert.deepEqual(+ yield* projectionState.listAll(),+ cursorsBeforeFailure.map((cursor) => ({+ ...cursor,+ lastAppliedSequence: pendingEvent.sequence,+ updatedAt: pendingEvent.occurredAt,+ })),+ );+ const replayedMessages = yield* sql<{ readonly text: string }>`+ SELECT text FROM projection_thread_messages WHERE message_id = 'message-rollback'+ `;+ assert.deepEqual(replayedMessages, [{ text: "Rollback me" }]);}),);});@@ -3888,6 +3955,14 @@ engineLayer("OrchestrationProjectionPipeline via engine dispatch", (it) => {yield* fileSystem.makeDirectory(attachmentsDir, { recursive: true });yield* fileSystem.writeFileString(attachmentPath, "keep this attachment");+ const readCursors = sql<{+ readonly projector: string;+ readonly lastAppliedSequence: number;+ }>`+ SELECT projector, last_applied_sequence AS "lastAppliedSequence"+ FROM projection_state ORDER BY projector+ `;+ const cursorsBeforeFailure = yield* readCursors;yield* sql`CREATE TRIGGER fail_attachment_command_receiptBEFORE INSERT ON orchestration_command_receipts@@ -3899,6 +3974,7 @@ engineLayer("OrchestrationProjectionPipeline via engine dispatch", (it) => {const deleteCommand = { type: "thread.delete", commandId, threadId } as const;const dispatchError = yield* engine.dispatch(deleteCommand).pipe(Effect.flip);assert.equal(dispatchError._tag, "PersistenceSqlError");+ assert.deepEqual(yield* readCursors, cursorsBeforeFailure);assert.equal(yield* fileSystem.readFileString(attachmentPath), "keep this attachment");const rolledBackThreads = yield* sql<{ readonly deletedAt: string | null }>`SELECT deleted_at AS "deletedAt" FROM projection_threads WHERE thread_id = ${threadId}@@ -3915,6 +3991,13 @@ engineLayer("OrchestrationProjectionPipeline via engine dispatch", (it) => {yield* sql`DROP TRIGGER fail_attachment_command_receipt`;const result = yield* engine.dispatch(deleteCommand);+ assert.deepEqual(+ yield* readCursors,+ cursorsBeforeFailure.map((cursor) => ({+ ...cursor,+ lastAppliedSequence: result.sequence,+ })),+ );assert.isFalse(yield* exists(attachmentPath));const committedReceipts = yield* sql<{readonly status: string;diff --git a/apps/server/src/orchestration/Layers/ProjectionPipeline.ts b/apps/server/src/orchestration/Layers/ProjectionPipeline.tsindex ff6c5866fea..77dfb5e3b88 100644--- a/apps/server/src/orchestration/Layers/ProjectionPipeline.ts+++ b/apps/server/src/orchestration/Layers/ProjectionPipeline.ts@@ -1947,11 +1947,21 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjectiprunedThreadRelativePaths: new Map<string, Set<string>>(),};yield* sql.withTransaction(- Effect.forEach(- projectors,- (projector) => applyProjectorForEvent(projector, event, attachmentSideEffects),- { concurrency: 1, discard: true },- ),+ Effect.gen(function* () {+ yield* Effect.forEach(+ projectors,+ (projector) => projector.apply(event, attachmentSideEffects),+ { concurrency: 1, discard: true },+ );+ // Runtime projectors commit together. Bootstrap still advances each cursor separately.+ yield* projectionStateRepository.upsertMany(+ projectors.map((projector) => ({+ projector: projector.name,+ lastAppliedSequence: event.sequence,+ updatedAt: event.occurredAt,+ })),+ );+ }),);// Return the cleanup effect so the caller runs it after the outer transaction commits.// @effect-diagnostics-next-line returnEffectInGen:offdiff --git a/apps/server/src/persistence/Layers/ProjectionState.ts b/apps/server/src/persistence/Layers/ProjectionState.tsindex f630fe51e03..a6fb7f3be4d 100644--- a/apps/server/src/persistence/Layers/ProjectionState.ts+++ b/apps/server/src/persistence/Layers/ProjectionState.ts@@ -42,6 +42,26 @@ const makeProjectionStateRepository = Effect.gen(function* () {`,});+ const upsertProjectionStateRows = SqlSchema.void({+ Request: Schema.Array(ProjectionState),+ execute: (rows) =>+ rows.length === 0+ ? Effect.void+ : sql`+ INSERT INTO projection_state ${sql.insert(+ rows.map((row) => ({+ projector: row.projector,+ last_applied_sequence: row.lastAppliedSequence,+ updated_at: row.updatedAt,+ })),+ )}+ ON CONFLICT (projector)+ DO UPDATE SET+ last_applied_sequence = excluded.last_applied_sequence,+ updated_at = excluded.updated_at+ `,+ });+const getProjectionStateRow = SqlSchema.findOneOption({Request: GetProjectionStateInput,Result: ProjectionState,@@ -86,6 +106,11 @@ const makeProjectionStateRepository = Effect.gen(function* () {Effect.mapError(toPersistenceSqlError("ProjectionStateRepository.upsert:query")),);+ const upsertMany: ProjectionStateRepositoryShape["upsertMany"] = (rows) =>+ upsertProjectionStateRows(rows).pipe(+ Effect.mapError(toPersistenceSqlError("ProjectionStateRepository.upsertMany:query")),+ );+const getByProjector: ProjectionStateRepositoryShape["getByProjector"] = (input) =>getProjectionStateRow(input).pipe(Effect.mapError(toPersistenceSqlError("ProjectionStateRepository.getByProjector:query")),@@ -106,6 +131,7 @@ const makeProjectionStateRepository = Effect.gen(function* () {return {upsert,+ upsertMany,getByProjector,listAll,minLastAppliedSequence,diff --git a/apps/server/src/persistence/Services/ProjectionState.ts b/apps/server/src/persistence/Services/ProjectionState.tsindex ba1ca151736..9372acdeeb6 100644--- a/apps/server/src/persistence/Services/ProjectionState.ts+++ b/apps/server/src/persistence/Services/ProjectionState.ts@@ -37,6 +37,11 @@ export interface ProjectionStateRepositoryShape {*/readonly upsert: (row: ProjectionState) => Effect.Effect<void, ProjectionRepositoryError>;+ /** Insert or replace projector cursors in one statement. Empty batches do nothing. */+ readonly upsertMany: (+ rows: ReadonlyArray<ProjectionState>,+ ) => Effect.Effect<void, ProjectionRepositoryError>;+/*** Read projection cursor state for a projector key.*/