TypeScript
perf(server): skip full-message reads while streaming (#9032)
Theo Brownee86604d3372a
diff --git a/apps/server/src/orchestration/Layers/ProjectionPipeline.test.ts b/apps/server/src/orchestration/Layers/ProjectionPipeline.test.tsindex b8f65a54b92..32551643b0d 100644--- a/apps/server/src/orchestration/Layers/ProjectionPipeline.test.ts+++ b/apps/server/src/orchestration/Layers/ProjectionPipeline.test.ts@@ -1462,6 +1462,8 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => {const eventStore = yield* OrchestrationEventStore;const sql = yield* SqlClient.SqlClient;const now = "2026-01-01T00:00:00.000Z";+ const streamingAt = "2026-01-01T00:00:01.000Z";+ const completedAt = "2026-01-01T00:00:02.000Z";yield* eventStore.append({type: "project.created",@@ -1526,7 +1528,7 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => {role: "assistant",text: "hello",turnId: null,- streaming: false,+ streaming: true,createdAt: now,updatedAt: now,},@@ -1539,7 +1541,7 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => {eventId: EventId.make("evt-a4"),aggregateKind: "thread",aggregateId: ThreadId.make("thread-a"),- occurredAt: now,+ occurredAt: streamingAt,commandId: CommandId.make("cmd-a4"),causationEventId: null,correlationId: CorrelationId.make("cmd-a4"),@@ -1551,18 +1553,61 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => {text: " world",turnId: null,streaming: true,- createdAt: now,- updatedAt: now,+ createdAt: streamingAt,+ updatedAt: streamingAt,},});yield* projectionPipeline.bootstrap;yield* projectionPipeline.bootstrap;- const messageRows = yield* sql<{ readonly text: string }>`- SELECT text FROM projection_thread_messages WHERE message_id = 'message-a'+ yield* eventStore.append({+ type: "thread.message-sent",+ eventId: EventId.make("evt-a5"),+ aggregateKind: "thread",+ aggregateId: ThreadId.make("thread-a"),+ occurredAt: completedAt,+ commandId: CommandId.make("cmd-a5"),+ causationEventId: null,+ correlationId: CorrelationId.make("cmd-a5"),+ metadata: {},+ payload: {+ threadId: ThreadId.make("thread-a"),+ messageId: MessageId.make("message-a"),+ role: "assistant",+ text: "",+ turnId: null,+ streaming: false,+ createdAt: completedAt,+ updatedAt: completedAt,+ },+ });++ yield* projectionPipeline.bootstrap;+ yield* projectionPipeline.bootstrap;++ const messageRows = yield* sql<{+ readonly text: string;+ readonly isStreaming: number;+ readonly createdAt: string;+ readonly updatedAt: string;+ }>`+ SELECT+ text,+ is_streaming AS "isStreaming",+ created_at AS "createdAt",+ updated_at AS "updatedAt"+ FROM projection_thread_messages+ WHERE message_id = 'message-a'`;- assert.deepEqual(messageRows, [{ text: "hello world" }]);+ assert.deepEqual(messageRows, [+ {+ text: "hello world",+ isStreaming: 0,+ createdAt: now,+ updatedAt: completedAt,+ },+ ]);const stateRows = yield* sql<{readonly projector: string;diff --git a/apps/server/src/orchestration/Layers/ProjectionPipeline.ts b/apps/server/src/orchestration/Layers/ProjectionPipeline.tsindex 67233681672..22daeee6936 100644--- a/apps/server/src/orchestration/Layers/ProjectionPipeline.ts+++ b/apps/server/src/orchestration/Layers/ProjectionPipeline.ts@@ -1008,21 +1008,34 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjectireturn;case "thread.message-sent": {+ if (event.payload.streaming) {+ const attachments =+ event.payload.attachments !== undefined+ ? yield* materializeAttachmentsForProjection({+ attachments: event.payload.attachments,+ })+ : undefined;+ yield* projectionThreadMessageRepository.appendStreaming({+ messageId: event.payload.messageId,+ threadId: event.payload.threadId,+ turnId: event.payload.turnId,+ role: event.payload.role,+ text: event.payload.text,+ ...(attachments !== undefined ? { attachments: [...attachments] } : {}),+ createdAt: event.payload.createdAt,+ updatedAt: event.payload.updatedAt,+ });+ return;+ }+const existingMessage = yield* projectionThreadMessageRepository.getByMessageId({messageId: event.payload.messageId,});const previousMessage = Option.getOrUndefined(existingMessage);const nextText = Option.match(existingMessage, {onNone: () => event.payload.text,- onSome: (message) => {- if (event.payload.streaming) {- return `${message.text}${event.payload.text}`;- }- if (event.payload.text.length === 0) {- return message.text;- }- return event.payload.text;- },+ onSome: (message) =>+ event.payload.text.length === 0 ? message.text : event.payload.text,});const nextAttachments =event.payload.attachments !== undefined@@ -1037,7 +1050,7 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjectirole: event.payload.role,text: nextText,...(nextAttachments !== undefined ? { attachments: [...nextAttachments] } : {}),- isStreaming: event.payload.streaming,+ isStreaming: false,createdAt: previousMessage?.createdAt ?? event.payload.createdAt,updatedAt: event.payload.updatedAt,});diff --git a/apps/server/src/persistence/Layers/ProjectionThreadMessages.test.ts b/apps/server/src/persistence/Layers/ProjectionThreadMessages.test.tsindex b1f394a9e57..30e0f42cab8 100644--- a/apps/server/src/persistence/Layers/ProjectionThreadMessages.test.ts+++ b/apps/server/src/persistence/Layers/ProjectionThreadMessages.test.ts@@ -12,6 +12,71 @@ const layer = it.layer();layer("ProjectionThreadMessageRepository", (it) => {+ it.effect("appends streaming text and applies attachment updates", () =>+ Effect.gen(function* () {+ const repository = yield* ProjectionThreadMessageRepository;+ const threadId = ThreadId.make("thread-streaming-append");+ const messageId = MessageId.make("message-streaming-append");+ const createdAt = "2026-02-28T19:05:00.000Z";+ const attachments = [+ {+ type: "image" as const,+ id: "thread-streaming-append-att-1",+ name: "example.png",+ mimeType: "image/png",+ sizeBytes: 5,+ },+ ];++ yield* repository.appendStreaming({+ messageId,+ threadId,+ turnId: null,+ role: "assistant",+ text: "hello",+ attachments,+ createdAt,+ updatedAt: createdAt,+ });+ yield* repository.appendStreaming({+ messageId,+ threadId,+ turnId: null,+ role: "assistant",+ text: " world",+ createdAt: "2026-02-28T19:05:01.000Z",+ updatedAt: "2026-02-28T19:05:01.000Z",+ });++ const rowWithPreservedAttachments = yield* repository.getByMessageId({ messageId });+ assert.equal(rowWithPreservedAttachments._tag, "Some");+ if (rowWithPreservedAttachments._tag === "Some") {+ assert.deepEqual(rowWithPreservedAttachments.value.attachments, attachments);+ }++ yield* repository.appendStreaming({+ messageId,+ threadId,+ turnId: null,+ role: "assistant",+ text: "",+ attachments: [],+ createdAt: "2026-02-28T19:05:02.000Z",+ updatedAt: "2026-02-28T19:05:02.000Z",+ });++ const row = yield* repository.getByMessageId({ messageId });+ assert.equal(row._tag, "Some");+ if (row._tag === "Some") {+ assert.equal(row.value.text, "hello world");+ assert.deepEqual(row.value.attachments, []);+ assert.equal(row.value.createdAt, createdAt);+ assert.equal(row.value.updatedAt, "2026-02-28T19:05:02.000Z");+ assert.isTrue(row.value.isStreaming);+ }+ }),+ );+it.effect("preserves existing attachments when upsert omits attachments", () =>Effect.gen(function* () {const repository = yield* ProjectionThreadMessageRepository;diff --git a/apps/server/src/persistence/Layers/ProjectionThreadMessages.ts b/apps/server/src/persistence/Layers/ProjectionThreadMessages.tsindex 71919166886..85e854dc660 100644--- a/apps/server/src/persistence/Layers/ProjectionThreadMessages.ts+++ b/apps/server/src/persistence/Layers/ProjectionThreadMessages.ts@@ -9,6 +9,7 @@ import { ChatAttachment } from "@t3tools/contracts";import { toPersistenceSqlError } from "../Errors.ts";import {+ AppendStreamingProjectionThreadMessage,GetProjectionThreadMessageInput,ProjectionThreadMessageRepository,type ProjectionThreadMessageRepositoryShape,@@ -95,6 +96,50 @@ const makeProjectionThreadMessageRepository = Effect.gen(function* () {},});+ const appendStreamingProjectionThreadMessageRow = SqlSchema.void({+ Request: AppendStreamingProjectionThreadMessage,+ execute: (row) => {+ const nextAttachmentsJson =+ row.attachments !== undefined ? JSON.stringify(row.attachments) : null;+ return sql`+ INSERT INTO projection_thread_messages (+ message_id,+ thread_id,+ turn_id,+ role,+ text,+ attachments_json,+ is_streaming,+ created_at,+ updated_at+ )+ VALUES (+ ${row.messageId},+ ${row.threadId},+ ${row.turnId},+ ${row.role},+ ${row.text},+ ${nextAttachmentsJson},+ 1,+ ${row.createdAt},+ ${row.updatedAt}+ )+ ON CONFLICT (message_id)+ DO UPDATE SET+ thread_id = excluded.thread_id,+ turn_id = excluded.turn_id,+ role = excluded.role,+ text = projection_thread_messages.text || excluded.text,+ attachments_json = COALESCE(+ excluded.attachments_json,+ projection_thread_messages.attachments_json+ ),+ is_streaming = 1,+ updated_at = excluded.updated_at+ `;+ },+ });+const getProjectionThreadMessageRow = SqlSchema.findOneOption({Request: GetProjectionThreadMessageInput,Result: ProjectionThreadMessageDbRowSchema,@@ -151,6 +196,13 @@ const makeProjectionThreadMessageRepository = Effect.gen(function* () {Effect.mapError(toPersistenceSqlError("ProjectionThreadMessageRepository.upsert:query")),);+ const appendStreaming: ProjectionThreadMessageRepositoryShape["appendStreaming"] = (row) =>+ appendStreamingProjectionThreadMessageRow(row).pipe(+ Effect.mapError(+ toPersistenceSqlError("ProjectionThreadMessageRepository.appendStreaming:query"),+ ),+ );+const getByMessageId: ProjectionThreadMessageRepositoryShape["getByMessageId"] = (input) =>getProjectionThreadMessageRow(input).pipe(Effect.mapError(@@ -176,6 +228,7 @@ const makeProjectionThreadMessageRepository = Effect.gen(function* () {return {upsert,+ appendStreaming,getByMessageId,listByThreadId,deleteByThreadId,diff --git a/apps/server/src/persistence/Services/ProjectionThreadMessages.ts b/apps/server/src/persistence/Services/ProjectionThreadMessages.tsindex d50ff320256..17b659a2f8d 100644--- a/apps/server/src/persistence/Services/ProjectionThreadMessages.ts+++ b/apps/server/src/persistence/Services/ProjectionThreadMessages.ts@@ -16,6 +16,7 @@ import {} from "@t3tools/contracts";import * as Schema from "effect/Schema";import * as Context from "effect/Context";+import * as Struct from "effect/Struct";import type * as Option from "effect/Option";import type * as Effect from "effect/Effect";@@ -34,6 +35,12 @@ export const ProjectionThreadMessage = Schema.Struct({});export type ProjectionThreadMessage = typeof ProjectionThreadMessage.Type;+export const AppendStreamingProjectionThreadMessage = Schema.Struct(+ Struct.omit(ProjectionThreadMessage.fields, ["isStreaming"]),+);+export type AppendStreamingProjectionThreadMessage =+ typeof AppendStreamingProjectionThreadMessage.Type;+export const ListProjectionThreadMessagesInput = Schema.Struct({threadId: ThreadId,});@@ -62,6 +69,11 @@ export interface ProjectionThreadMessageRepositoryShape {message: ProjectionThreadMessage,) => Effect.Effect<void, ProjectionRepositoryError>;+ /** Insert a streaming message or append text to its existing row. */+ readonly appendStreaming: (+ message: AppendStreamingProjectionThreadMessage,+ ) => Effect.Effect<void, ProjectionRepositoryError>;+/*** Read a projected thread message by id.*/