TypeScript
perf(server): avoid unused history reads during thread waits (#27032)
Adamulek12320f45bf23ed6
diff --git a/apps/server/src/mcp/OrchestratorMcpService.test.ts b/apps/server/src/mcp/OrchestratorMcpService.test.tsindex 9f27dc69363..7617577422b 100644--- a/apps/server/src/mcp/OrchestratorMcpService.test.ts+++ b/apps/server/src/mcp/OrchestratorMcpService.test.ts@@ -2652,7 +2652,11 @@ describe("OrchestratorMcpService thread lookup", () => {capabilities: new Set(["orchestration"]),issuedAt: 1,};- const service = (shells: ReadonlyArray<OrchestrationV2ThreadShell>, sent: Ref.Ref<number>) =>+ const service = (+ shells: ReadonlyArray<OrchestrationV2ThreadShell>,+ sent: Ref.Ref<number>,+ overrides: Partial<ThreadManagementService.ThreadManagementService["Service"]> = {},+ ) =>layerOrchestratorService.pipe(Layer.provide(Layer.mergeAll(@@ -2661,6 +2665,7 @@ describe("OrchestratorMcpService thread lookup", () => {getThreadShell: (threadId) =>Effect.succeed(shells.find((shell) => shell.id === threadId) ?? null),sendToThread: () => Ref.update(sent, (count) => count + 1).pipe(Effect.as({} as never)),+ ...overrides,}),ServerSettings.layerTest(),Layer.mock(ProviderRegistry.ProviderRegistry)({ getProviders: Effect.succeed([]) }),@@ -2683,14 +2688,15 @@ describe("OrchestratorMcpService thread lookup", () => {const send = yield* mcp.sendToThread(client, { threadId: bareId, message: "hello" }).pipe(Effect.flip);- return { read, send, sends: yield* Ref.get(sent) };+ const wait = yield* mcp.waitForThread(client, { threadId: bareId }).pipe(Effect.flip);+ return { read, send, wait, sends: yield* Ref.get(sent) };}).pipe(Effect.provide(service(shells, sent)));});it.effect("points a bare uuid at the mcp: thread it belongs to", () =>Effect.gen(function* () {- const { read, send, sends } = yield* failuresFor([launched]);- for (const error of [read, send]) {+ const { read, send, wait, sends } = yield* failuresFor([launched]);+ for (const error of [read, send, wait]) {assert.equal(error.code, "thread_not_found");assert.include(error.message, `mcp:${bareId}`);}@@ -2700,19 +2706,76 @@ describe("OrchestratorMcpService thread lookup", () => {it.effect("keeps the plain message for an id that matches nothing", () =>Effect.gen(function* () {- const { read, send } = yield* failuresFor([]);+ const { read, send, wait } = yield* failuresFor([]);assert.equal(read.code, "thread_not_found");assert.equal(read.message, `Thread ${bareId} is no longer available.`);assert.equal(send.code, "thread_not_found");assert.equal(send.message, `Thread ${bareId} was not found.`);+ assert.equal(wait.code, "thread_not_found");+ assert.equal(wait.message, send.message);}),);it.effect("does not name an mcp: thread that was deleted", () =>Effect.gen(function* () {- const { read, send } = yield* failuresFor([deletedLaunched]);+ const { read, send, wait } = yield* failuresFor([deletedLaunched]);assert.equal(read.message, `Thread ${bareId} is no longer available.`);assert.equal(send.message, `Thread ${bareId} was not found.`);+ assert.equal(wait.message, send.message);+ }),+ );++ it.effect("refuses waiting without orchestration capability before reading the target", () =>+ Effect.gen(function* () {+ const sent = yield* Ref.make(0);+ return yield* Effect.gen(function* () {+ const mcp = yield* OrchestratorMcpService.OrchestratorMcpService;+ const error = yield* mcp+ .waitForThread({ ...client, capabilities: new Set() }, { threadId: bareId })+ .pipe(Effect.flip);+ assert.equal(error.code, "capability_denied");+ }).pipe(+ Effect.provide(+ service([], sent, {+ getThreadShell: () => Effect.die("Unauthorized target access"),+ }),+ ),+ );+ }),+ );++ it.effect("waits on the caller's own thread without a separate shell lookup", () =>+ Effect.gen(function* () {+ const sent = yield* Ref.make(0);+ return yield* Effect.gen(function* () {+ const mcp = yield* OrchestratorMcpService.OrchestratorMcpService;+ const result = yield* mcp.waitForThread(+ {+ ...client,+ thread: {+ threadId: launched.id,+ providerSessionId: "provider-session:wait-self",+ providerInstanceId: ProviderInstanceId.make("codex"),+ },+ },+ { threadId: launched.id },+ );+ assert.deepEqual(result, {+ threadId: launched.id,+ runId: null,+ status: "idle",+ timedOut: false,+ });+ }).pipe(+ Effect.provide(+ service([], sent, {+ getThreadShell: () => Effect.die("Unexpected shell lookup for the caller"),+ getThreadRecords: () => Effect.succeed(idleThreadProjection(launched)),+ waitForThread: () =>+ Effect.succeed({ threadId: launched.id, run: null, timedOut: false }),+ }),+ ),+ );}),);});diff --git a/apps/server/src/mcp/OrchestratorMcpService.ts b/apps/server/src/mcp/OrchestratorMcpService.tsindex 403d625d7e9..da4ad5c6d35 100644--- a/apps/server/src/mcp/OrchestratorMcpService.ts+++ b/apps/server/src/mcp/OrchestratorMcpService.ts@@ -1152,6 +1152,7 @@ const make = Effect.gen(function* () {const loadTargetThread = Effect.fn("OrchestratorMcpService.loadTargetThread")(function* (threadId: ThreadId,+ includeHistory = true,) {const shell = yield* threadManagement.getThreadShell(threadId)@@ -1159,18 +1160,24 @@ const make = Effect.gen(function* () {if (shell === null || shell.deletedAt !== null) {return yield* threadNotFound(threadManagement, threadId, `Thread ${threadId} was not found.`);}- return yield* loadProjectThread(shell.projectId, threadId);+ // Native wait owns its history reads; keep legacy import and project validation here.+ return yield* includeHistory+ ? loadProjectThread(shell.projectId, threadId)+ : threadManagement+ .getProjectThreadRecords({ projectId: shell.projectId, threadId }, [])+ .pipe(Effect.mapError(threadManagementFailure));});const loadScopedThread = Effect.fn("OrchestratorMcpService.loadScopedThread")(function* (scope: McpInvocationScope,threadId: ThreadId,+ includeHistory = true,) {const caller = yield* loadCaller(scope);const target =caller.parent !== undefined && threadId === caller.parent.thread.id? caller.parent- : yield* loadTargetThread(threadId);+ : yield* loadTargetThread(threadId, includeHistory);return { ...caller, target } as const;});@@ -3019,7 +3026,7 @@ const make = Effect.gen(function* () {} satisfies OrchestratorMcpThreadSendResult;}),waitForThread: Effect.fn("OrchestratorMcpService.waitForThread")(function* (scope, input) {- const { parent, target } = yield* loadScopedThread(scope, input.threadId);+ const { parent, target } = yield* loadScopedThread(scope, input.threadId, false);const result = yield* threadManagement.waitForThread({projectId: target.thread.projectId,diff --git a/apps/server/src/mcp/OrchestratorMcpToolkit.integration.test.ts b/apps/server/src/mcp/OrchestratorMcpToolkit.integration.test.tsindex e53a4d85583..bedf2ce0111 100644--- a/apps/server/src/mcp/OrchestratorMcpToolkit.integration.test.ts+++ b/apps/server/src/mcp/OrchestratorMcpToolkit.integration.test.ts@@ -597,6 +597,7 @@ describe("orchestrator MCP toolkit", () => {delegated.resultContextTransferId,);const transferReads: Array<string> = [];+ const messageReads: Array<string> = [];const tracer = Tracer.make({span(options) {const span = new Tracer.NativeSpan(options);@@ -610,10 +611,53 @@ describe("orchestrator MCP toolkit", () => {) {transferReads.push(query);}+ if (+ typeof query === "string" &&+ /SELECT\s+payload_json\s+FROM orchestration_v2_projection_messages/i.test(query)+ ) {+ messageReads.push(query);+ }};return span;},});+ const wait = yield* invoke(+ "t3_thread_wait",+ { threadId: delegated.childThreadId, runId: queuedFollowup.runId },+ { ...invocation, thread: undefined },+ ).pipe(Effect.withTracer(tracer));+ expect(wait.isError).not.toBe(true);+ const expectedWait = {+ threadId: delegated.childThreadId,+ runId: queuedFollowup.runId,+ status: "completed",+ timedOut: false,+ };+ expect(wait.structuredContent).toEqual(expectedWait);+ expect(messageReads).toEqual([]);+ expect(transferReads).toHaveLength(0);+ const settledWait = yield* invoke(+ "t3_thread_wait",+ {+ threadId: delegated.childThreadId,+ runId: queuedFollowup.runId,+ untilDelegatedWorkSettled: true,+ },+ { ...invocation, thread: undefined },+ ).pipe(Effect.withTracer(tracer));+ expect(settledWait.isError).not.toBe(true);+ expect(settledWait.structuredContent).toMatchObject({+ ...expectedWait,+ resultRun: { runId: queuedFollowup.runId, status: "completed" },+ });+ expect(messageReads.length).toBeGreaterThan(0);+ expect(+ messageReads.filter((query) => query.includes("$.notification.source.kind")),+ ).toHaveLength(1);+ // The orchestrator's restart-continuation guard still reads its own records.+ expect(+ messageReads.filter((query) => !query.includes("$.notification.source.kind")),+ ).toHaveLength(1);const parentlessRead = yield* invoke("t3_thread_read",{ threadId: delegated.childThreadId, limit: 100 },diff --git a/apps/server/src/orchestration-v2/ProjectionStore.test.ts b/apps/server/src/orchestration-v2/ProjectionStore.test.tsindex a29d698d76d..2f7c9f00b4e 100644--- a/apps/server/src/orchestration-v2/ProjectionStore.test.ts+++ b/apps/server/src/orchestration-v2/ProjectionStore.test.ts@@ -215,6 +215,71 @@ const addRolledBackRecoveryCandidate = Effect.fn("addRolledBackRecoveryCandidatereturn threadId;});+it.effect("record reads filter notification sources without dropping matching message bodies", () =>+ Effect.gen(function* () {+ const store = yield* ProjectionStore.ProjectionStoreV2;+ const threadId = yield* addRolledBackRecoveryCandidate("notification-filter");+ const now = yield* DateTime.now;+ for (const [id, role, kind] of [+ ["ordinary", "user", null],+ ["monitor", "user", "monitor"],+ ["system", "user", "system"],+ ["assistant-monitor", "assistant", "monitor"],+ ] as const) {+ yield* store.apply({+ id: EventId.make(`notification-filter:${id}`),+ type: "message.updated",+ threadId,+ occurredAt: now,+ payload: {+ id: MessageId.make(id),+ threadId,+ runId: null,+ nodeId: null,+ createdBy: "agent",+ creationSource: "server",+ role,+ text: `Complete body for ${id}`,+ attachments: [],+ streaming: false,+ createdAt: now,+ updatedAt: now,+ ...(kind === null+ ? {}+ : {+ notification: {+ source: { kind },+ outcome: "updated",+ summary: "Background notification",+ },+ }),+ },+ });+ }+ const matching = yield* store.getThreadRecords(threadId, ["messages"], {+ messageRoles: ["user"],+ monitorNotificationsOnly: true,+ });+ assert.deepEqual(+ matching.messages.map((message) => [message.id, message.text]),+ [["monitor", "Complete body for monitor"]],+ );+ assert.lengthOf((yield* store.getThreadRecords(threadId, ["messages"])).messages, 4);+ assert.lengthOf(+ (yield* store.getThreadRecords(threadId, ["messages"], {+ monitorNotificationsOnly: true,+ })).messages,+ 2,+ );+ assert.lengthOf(+ (yield* store.getThreadRecords(threadId, ["messages"], {+ monitorNotificationsOnly: false,+ })).messages,+ 4,+ );+ }).pipe(Effect.provide(layerTest)),+);+it.effect("SQL queue readiness skips held runs without bypassing active work", () =>Effect.gen(function* () {const store = yield* ProjectionStore.ProjectionStoreV2;diff --git a/apps/server/src/orchestration-v2/ProjectionStore.ts b/apps/server/src/orchestration-v2/ProjectionStore.tsindex 2e88fdc1190..e2481acda8a 100644--- a/apps/server/src/orchestration-v2/ProjectionStore.ts+++ b/apps/server/src/orchestration-v2/ProjectionStore.ts@@ -330,6 +330,7 @@ export interface ProjectionRuntimeResponseContext {export interface ProjectionRecordFilter {readonly messageRoles?: ReadonlyArray<OrchestrationV2ConversationMessage["role"]>;+ readonly monitorNotificationsOnly?: boolean;readonly turnItemRunId?: RunId;readonly messageIds?: ReadonlyArray<MessageId>;readonly messageRunIds?: ReadonlyArray<RunId>;@@ -3422,6 +3423,7 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =WHERE thread_id = ${threadId}${filter?.messageIds === undefined ? sql`` : sql`AND message_id IN (SELECT value FROM json_each(${encodeIdList(filter.messageIds)}))`}${filter?.messageRoles === undefined ? sql`` : sql`AND role IN (SELECT value FROM json_each(${encodeIdList(filter.messageRoles)}))`}+ ${filter?.monitorNotificationsOnly === true ? sql`AND json_extract(payload_json, '$.notification.source.kind') = 'monitor'` : sql``}${filter?.messageRunIds === undefined ? sql`` : sql`AND run_id IN (SELECT value FROM json_each(${encodeIdList(filter.messageRunIds)}))`}ORDER BY created_at ASC, message_id ASC`diff --git a/apps/server/src/orchestration-v2/ThreadManagementService.ts b/apps/server/src/orchestration-v2/ThreadManagementService.tsindex 276d673a39d..c1727567f9e 100644--- a/apps/server/src/orchestration-v2/ThreadManagementService.ts+++ b/apps/server/src/orchestration-v2/ThreadManagementService.ts@@ -940,7 +940,7 @@ const make = Effect.gen(function* () {const records = yield* getProjectThreadRecords(input,["runs", "messages", "subagents", "providerThreads"],- { messageRoles: ["user"] },+ { messageRoles: ["user"], monitorNotificationsOnly: true },);const progress = delegatedTaskProgress(records);// A thread rolled back past all its work, with nothing left running, has no answer to wait for.