TypeScript
perf(server): narrow delegated recovery reads to delivery records (#29435)
Yash Singh7cf653bca60d
diff --git a/apps/server/src/orchestration-v2/DelegatedCompletionDelivery.test.ts b/apps/server/src/orchestration-v2/DelegatedCompletionDelivery.test.tsindex 87f6bbd1a67..900dc150877 100644--- a/apps/server/src/orchestration-v2/DelegatedCompletionDelivery.test.ts+++ b/apps/server/src/orchestration-v2/DelegatedCompletionDelivery.test.ts@@ -25,6 +25,7 @@ import * as Deferred from "effect/Deferred";import * as Fiber from "effect/Fiber";import * as Layer from "effect/Layer";import * as Stream from "effect/Stream";+import * as Tracer from "effect/Tracer";import * as CheckpointStore from "../checkpointing/CheckpointStore.ts";import * as ServerConfig from "../config.ts";@@ -1346,6 +1347,76 @@ const seedRestartCancelledChild = (input: {it.layer(Layer.merge(layerTest, ProviderContinuationRequests.layer))("subagent follow-ups",(it) => {+ it.effect("recovers a reserved delivery without loading conversation history", () =>+ Effect.gen(function* () {+ const orchestrator = yield* Orchestrator.OrchestratorV2;+ const sink = yield* EventSink.EventSinkV2;+ const requests = yield* ProviderContinuationRequests.ProviderContinuationRequests;+ const now = yield* DateTime.now;+ const threadId = ThreadId.make("thread:bounded-delivery-recovery");+ const runId = RunId.make("run:bounded-delivery-recovery");+ const taskId = NodeId.make("task:bounded-delivery-recovery");+ yield* seedParentWithTerminalTask({+ threadId,+ runId,+ taskId,+ projectId: ProjectId.make("project:bounded-delivery-recovery"),+ rootNodeId: NodeId.make("node:bounded-delivery-recovery"),+ deliveryState: "claimed",+ deliveryTaskIds: [taskId],+ completionWake: "always",+ now,+ });+ for (const suffix of ["first", "second"]) {+ yield* sink.write({+ events: [+ {+ id: EventId.make(`event:bounded-delivery-history:${suffix}`),+ type: "message.updated",+ threadId,+ occurredAt: now,+ payload: {+ id: MessageId.make(`message:bounded-delivery-history:${suffix}`),+ threadId,+ runId: null,+ nodeId: null,+ createdBy: "user",+ creationSource: "web",+ role: "user",+ text: "Unrelated historical input",+ attachments: [],+ streaming: false,+ createdAt: now,+ updatedAt: now,+ },+ },+ ],+ });+ }+ const statements: string[] = [];+ const tracer = Tracer.make({+ span(options) {+ const span = new Tracer.NativeSpan(options);+ const end = span.end.bind(span);+ span.end = (time, exit) => {+ end(time, exit);+ const query = span.attributes.get("db.query.text");+ if (typeof query === "string") statements.push(query);+ };+ return span;+ },+ });+ yield* orchestrator.recoverDelegatedTasks.pipe(Effect.withTracer(tracer));+ assert.isFalse(statements.some((query) => query.includes("MIN(ordinal)")));+ const messageReads = statements.filter((query) =>+ query.includes("FROM orchestration_v2_projection_messages"),+ );+ assert.isNotEmpty(messageReads);+ assert.isTrue(messageReads.every((query) => query.includes("message_id IN")));+ const wake = yield* requests.take;+ assert.equal(wake.delegatedCompletion?.parentRunId, runId);+ }),+ );it.effect("keeps a checkpoint completion committed between finalize's read and write", () =>Effect.gen(function* () {const orchestrator = yield* Orchestrator.OrchestratorV2;diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.tsindex 75df815127f..0df010b6908 100644--- a/apps/server/src/orchestration-v2/Orchestrator.ts+++ b/apps/server/src/orchestration-v2/Orchestrator.ts@@ -1346,27 +1346,40 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functioconst offerDelegatedCompletionDelivery =/* This helper runs for individual orchestration events; the enclosing operation owns the span. */Effect.fnUntraced(function* (threadId: ThreadId, parentRunId: RunId) {- const projection = yield* projectionStore.getThreadRecords(- threadId,- ["runs", "messages", "providerTurns", "providerThreads"],- { messageRoles: ["user"] },- );- const parentRun = projection.runs.find((candidate) => candidate.id === parentRunId);+ const controls = yield* projectionStore.getThreadRecords(threadId, ["runs"], {+ runIds: [parentRunId],+ });+ const parentRun = controls.runs[0];const cohort = parentRun?.delegatedCompletion;const delivery = cohort?.delivery;if (parentRun === undefined ||cohort?.disposition !== "open" ||- delivery === null ||- delivery === undefined ||+ delivery == null ||delivery.taskIds.length === 0 ||- projection.thread.archivedAt !== null ||- projection.thread.deletedAt !== null ||- (completionDeliveryMessage(projection, delivery) !== undefined &&- !isUndeliveredMailboxSteer(projection, delivery.messageId))- ) {+ controls.thread.archivedAt !== null ||+ controls.thread.deletedAt !== null+ )return;+ const messages = yield* projectionStore.getThreadRecords(threadId, ["messages"], {+ messageIds: [delivery.messageId],+ });+ const message = messages.messages[0];+ if (message !== undefined) {+ if (message.delegatedCompletion === undefined || message.runId === null) return;+ const runs = yield* projectionStore.getThreadRecords(threadId, ["runs"], {+ runIds: [message.runId],+ });+ const run = runs.runs[0];+ const turns = yield* projectionStore.getThreadRecords(threadId, ["providerTurns"], {+ providerTurnAttemptIds: run?.activeAttemptId == null ? [] : [run.activeAttemptId],+ });+ if (!isUndeliveredMailboxSteer({ ...messages, ...runs, ...turns }, delivery.messageId))+ return;}+ const projection = yield* projectionStore.getThreadRecords(threadId, ["providerThreads"], {+ providerThreadIds: parentRun.providerThreadId === null ? [] : [parentRun.providerThreadId],+ });const providerThread =parentRun.providerThreadId === null? undefined@@ -12708,7 +12721,11 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functioconst projection = yield* projectionStore.getThreadRecords(threadId,["runs", "messages", "subagents"],- { messageRoles: ["user"] },+ {+ runIds: [runId, message.delegatedCompletion.parentRunId],+ messageIds: [message.id],+ subagentRunIds: [message.delegatedCompletion.parentRunId],+ },);const deliveryRun = projection.runs.find((candidate) => candidate.id === runId);const deliveryMessage =diff --git a/apps/server/src/orchestration-v2/ProjectionStore.test.ts b/apps/server/src/orchestration-v2/ProjectionStore.test.tsindex aadd9ecc8be..4b72c9610c5 100644--- a/apps/server/src/orchestration-v2/ProjectionStore.test.ts+++ b/apps/server/src/orchestration-v2/ProjectionStore.test.ts@@ -215,6 +215,98 @@ const addRolledBackRecoveryCandidate = Effect.fn("addRolledBackRecoveryCandidatereturn threadId;});+it.effect("record reads restrict provider histories to delivery identities", () =>+ Effect.gen(function* () {+ const store = yield* ProjectionStore.ProjectionStoreV2;+ const threadId = yield* addRolledBackRecoveryCandidate("delivery-identities");+ const sql = yield* SqlClient.SqlClient;+ const now = yield* DateTime.now;+ for (const suffix of ["selected", "history"]) {+ const id = ProviderThreadId.make(`provider-thread:${suffix}`);+ yield* store.apply({+ id: EventId.make(`event:delivery-identities:${suffix}`),+ type: "provider-thread.updated",+ threadId,+ occurredAt: now,+ payload: {+ id,+ appThreadId: threadId,+ driver,+ providerInstanceId,+ providerSessionId: null,+ ownerNodeId: null,+ nativeThreadRef: null,+ nativeConversationHeadRef: null,+ lastRunOrdinal: null,+ handoffIds: [],+ forkedFrom: null,+ status: "active",+ firstRunOrdinal: 1,+ createdAt: now,+ updatedAt: now,+ },+ });+ }+ for (const [suffix, attempt] of [+ ["selected", "current"],+ ["history", "old"],+ ["runless", null],+ ] as const) {+ yield* store.apply({+ id: EventId.make(`event:delivery-turn:${suffix}`),+ type: "provider-turn.updated",+ threadId,+ occurredAt: now,+ payload: {+ id: ProviderTurnId.make(`turn:${suffix}`),+ providerThreadId: ProviderThreadId.make("provider-thread:selected"),+ nodeId: NodeId.make("node:delivery"),+ runAttemptId: attempt === null ? null : RunAttemptId.make(attempt),+ nativeTurnRef: null,+ ordinal: suffix === "selected" ? 1 : suffix === "history" ? 2 : 3,+ status: "completed",+ startedAt: now,+ completedAt: now,+ },+ });+ }+ assert.deepEqual(+ (yield* store.getThreadRecords(threadId, ["providerTurns"], {+ providerTurnAttemptIds: [RunAttemptId.make("current")],+ })).providerTurns.map((turn) => turn.id),+ ["turn:selected"],+ );+ assert.deepEqual(+ (yield* store.getThreadRecords(threadId, ["providerTurns"], {+ providerTurnAttemptIds: [],+ })).providerTurns,+ [],+ );+ const selected = yield* store.getThreadRecords(threadId, ["providerThreads"], {+ providerThreadIds: [ProviderThreadId.make("provider-thread:selected")],+ });+ assert.deepEqual(+ selected.providerThreads.map((row) => row.id),+ ["provider-thread:selected"],+ );+ assert.deepEqual(+ (yield* store.getThreadRecords(threadId, ["providerThreads"], {+ providerThreadIds: [],+ })).providerThreads,+ [],+ );+ // Unselected history must not be decoded, even if its payload is unreadable.+ yield* sql`UPDATE orchestration_v2_projection_provider_threads SET payload_json = '{}'+ WHERE provider_thread_id = 'provider-thread:history'`;+ assert.lengthOf(+ (yield* store.getThreadRecords(threadId, ["providerThreads"], {+ providerThreadIds: [ProviderThreadId.make("provider-thread:selected")],+ })).providerThreads,+ 1,+ );+ }).pipe(Effect.provide(layerTest)),+);+it.effect("record reads filter notification sources without dropping matching message bodies", () =>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 90a9582cb64..b214349d90f 100644--- a/apps/server/src/orchestration-v2/ProjectionStore.ts+++ b/apps/server/src/orchestration-v2/ProjectionStore.ts@@ -329,6 +329,8 @@ export interface ProjectionRuntimeResponseContext {}export interface ProjectionRecordFilter {+ readonly providerThreadIds?: ReadonlyArray<ProviderThreadId>;+ readonly providerTurnAttemptIds?: ReadonlyArray<RunAttemptId>;readonly messageRoles?: ReadonlyArray<OrchestrationV2ConversationMessage["role"]>;readonly monitorNotificationsOnly?: boolean;readonly turnItemRunId?: RunId;@@ -3387,13 +3389,14 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =OR threads.provider_thread_id IN (SELECT value FROM json_each(${cohortProviderThreadIds})))ORDER BY sessions.updated_at ASC, sessions.provider_session_id ASC`,- fields !== undefined && !fields.includes("providerThreads")+ (fields !== undefined && !fields.includes("providerThreads")) ||+ (window === undefined && matchesNothing(filter?.providerThreadIds))? Effect.succeed([]): window === undefined? sql<PayloadRow>`SELECT payload_jsonFROM orchestration_v2_projection_provider_threads- WHERE thread_id = ${threadId}+ WHERE (thread_id = ${threadId}OR owner_node_id IN (SELECT node_idFROM orchestration_v2_projection_nodes@@ -3404,7 +3407,8 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =FROM orchestration_v2_projection_subagentsWHERE thread_id = ${threadId}AND provider_thread_id IS NOT NULL- )+ ))+ ${filter?.providerThreadIds === undefined ? sql`` : sql`AND provider_thread_id IN (SELECT value FROM json_each(${encodeIdList(filter.providerThreadIds)}))`}ORDER BY COALESCE(first_run_ordinal, 0), provider_thread_id ASC`: sql<PayloadRow>`@@ -3416,13 +3420,15 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =AND provider_thread_id = ${latestTodoList?.provider_thread_id ?? null})ORDER BY COALESCE(first_run_ordinal, 0), provider_thread_id ASC`,- fields !== undefined && !fields.includes("providerTurns")+ (fields !== undefined && !fields.includes("providerTurns")) ||+ (window === undefined && matchesNothing(filter?.providerTurnAttemptIds))? Effect.succeed([]): window === undefined? sql<PayloadRow>`SELECT payload_jsonFROM orchestration_v2_projection_provider_turnsWHERE thread_id = ${threadId}+ ${filter?.providerTurnAttemptIds === undefined ? sql`` : sql`AND run_attempt_id IN (SELECT value FROM json_each(${encodeIdList(filter.providerTurnAttemptIds)}))`}ORDER BY provider_thread_id ASC, ordinal ASC`: sql<PayloadRow>`