From 081388252262d13c9a25da3718257fe79abd7654 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Sun, 22 Feb 2026 19:35:21 +0000 Subject: [PATCH] Fix event processing: decouple listener failures from dispatch, skip persistence for streaming deltas, remove unused PubSub - Bug 1: Succeed the deferred before running listener notifications so that listener failures (e.g. WebSocket send errors) don't fail the caller after the event is already persisted and the read model updated. Listener errors are now caught and logged as warnings. - Bug 2: Mark streaming text delta dispatches as transient so they update the in-memory read model and notify listeners but skip SQLite persistence. On turn completion, the accumulated message text is read from the snapshot and persisted as a single event, preventing unbounded event store growth and slow bootstrap replay. - Bug 3: Remove readModelPubSub and eventPubSub instances that were created and published to but never subscribed to anywhere in the codebase. --- apps/server/src/orchestration/Layer.ts | 38 ++++++++++++++---------- apps/server/src/orchestration/Service.ts | 2 ++ apps/server/src/wsServer.ts | 31 ++++++++++++------- 3 files changed, 45 insertions(+), 26 deletions(-) diff --git a/apps/server/src/orchestration/Layer.ts b/apps/server/src/orchestration/Layer.ts index 1edacd925c..6cd70f9511 100644 --- a/apps/server/src/orchestration/Layer.ts +++ b/apps/server/src/orchestration/Layer.ts @@ -4,7 +4,7 @@ import type { OrchestrationReadModel, } from "@t3tools/contracts"; import { OrchestrationCommandSchema } from "@t3tools/contracts"; -import { Deferred, Effect, Layer, PubSub, Queue, Schema } from "effect"; +import { Deferred, Effect, Layer, Queue, Schema } from "effect"; import { createLogger } from "../logger.ts"; import { OrchestrationEventRepository } from "../persistence/Services/OrchestrationEvents.ts"; @@ -20,6 +20,7 @@ import { OrchestrationEngineService, type OrchestrationEngineShape } from "./Ser interface CommandEnvelope { command: OrchestrationCommand; result: Deferred.Deferred<{ sequence: number }, OrchestrationDispatchError>; + transient?: boolean | undefined; } function mapCommandToEvent(command: OrchestrationCommand): Omit { @@ -169,8 +170,6 @@ const makeOrchestrationEngine = Effect.gen(function* () { let readModel = createEmptyReadModel(new Date().toISOString()); const commandQueue = yield* Queue.unbounded(); - const readModelPubSub = yield* PubSub.unbounded(); - const eventPubSub = yield* PubSub.unbounded(); const readModelListeners = new Set<(snapshot: OrchestrationReadModel) => void>(); const domainEventListeners = new Set<(event: OrchestrationEvent) => void>(); @@ -194,19 +193,28 @@ const makeOrchestrationEngine = Effect.gen(function* () { const processEnvelope = (envelope: CommandEnvelope): Effect.Effect => Effect.gen(function* () { const eventBase = mapCommandToEvent(envelope.command); - const savedEvent = yield* eventStore.append(eventBase); + + let savedEvent: OrchestrationEvent; + if (envelope.transient) { + savedEvent = { ...eventBase, sequence: readModel.sequence }; + } else { + savedEvent = yield* eventStore.append(eventBase); + } readModel = yield* reduceEvent(readModel, savedEvent); - const snapshot = readModel; - yield* Effect.all([ - PubSub.publish(eventPubSub, savedEvent), - PubSub.publish(readModelPubSub, snapshot), - ]); - - yield* notifyDomainEventListeners(savedEvent); - yield* notifyReadModelListeners(snapshot); - yield* Deferred.succeed(envelope.result, { sequence: savedEvent.sequence }); + + const snapshot = readModel; + yield* notifyDomainEventListeners(savedEvent).pipe( + Effect.catch((error) => + Effect.sync(() => logger.warn("domain event listener failed", { error: String(error) })), + ), + ); + yield* notifyReadModelListeners(snapshot).pipe( + Effect.catch((error) => + Effect.sync(() => logger.warn("read model listener failed", { error: String(error) })), + ), + ); }).pipe(Effect.catch((error) => Deferred.fail(envelope.result, error).pipe(Effect.asVoid))); const bootstrapReadModel: Effect.Effect = Effect.gen( @@ -232,10 +240,10 @@ const makeOrchestrationEngine = Effect.gen(function* () { const replayEvents: OrchestrationEngineShape["replayEvents"] = (fromSequenceExclusive) => eventStore.readFromSequence(fromSequenceExclusive); - const dispatch: OrchestrationEngineShape["dispatch"] = (command) => + const dispatch: OrchestrationEngineShape["dispatch"] = (command, options) => Effect.gen(function* () { const result = yield* Deferred.make<{ sequence: number }, OrchestrationDispatchError>(); - yield* Queue.offer(commandQueue, { command, result }); + yield* Queue.offer(commandQueue, { command, result, transient: options?.transient }); return yield* Deferred.await(result); }); diff --git a/apps/server/src/orchestration/Service.ts b/apps/server/src/orchestration/Service.ts index 1dadacce97..db5fdb436e 100644 --- a/apps/server/src/orchestration/Service.ts +++ b/apps/server/src/orchestration/Service.ts @@ -51,10 +51,12 @@ export interface OrchestrationEngineShape { * Dispatch a validated orchestration command. * * @param command - Valid orchestration command. + * @param options - Optional dispatch options. Set `transient` to skip persistence. * @returns Effect containing the sequence of the persisted event. */ readonly dispatch: ( command: OrchestrationCommand, + options?: { transient?: boolean | undefined } | undefined, ) => Effect.Effect<{ sequence: number }, OrchestrationDispatchError>; /** diff --git a/apps/server/src/wsServer.ts b/apps/server/src/wsServer.ts index d9fde1cb73..70c0bcf022 100644 --- a/apps/server/src/wsServer.ts +++ b/apps/server/src/wsServer.ts @@ -250,20 +250,29 @@ export function createServer(options: ServerOptions) { if (event.textDelta && event.textDelta.length > 0) { const assistantMessageId = `assistant:${event.turnId ?? event.itemId ?? event.sessionId}`; await runtime.runPromise( - liveOrchestrationEngine.dispatch({ - type: "message.send", - commandId: crypto.randomUUID(), - threadId: thread.id, - messageId: assistantMessageId, - role: "assistant", - text: event.textDelta, - streaming: true, - createdAt: now, - }), + liveOrchestrationEngine.dispatch( + { + type: "message.send", + commandId: crypto.randomUUID(), + threadId: thread.id, + messageId: assistantMessageId, + role: "assistant", + text: event.textDelta, + streaming: true, + createdAt: now, + }, + { transient: true }, + ), ); } if (event.method === "turn/completed") { const assistantMessageId = `assistant:${event.turnId ?? event.itemId ?? event.sessionId}`; + const latestSnapshot = await runtime.runPromise(liveOrchestrationEngine.getSnapshot()); + const latestThread = latestSnapshot.threads.find( + (entry) => entry.session?.sessionId === event.sessionId, + ); + const existingMessage = latestThread?.messages.find((m) => m.id === assistantMessageId); + const accumulatedText = existingMessage?.text ?? ""; await runtime.runPromise( liveOrchestrationEngine.dispatch({ type: "message.send", @@ -271,7 +280,7 @@ export function createServer(options: ServerOptions) { threadId: thread.id, messageId: assistantMessageId, role: "assistant", - text: "", + text: accumulatedText, streaming: false, createdAt: now, }),