Skip to content

Commit 8f1e61c

Browse files
perf(server): avoid unused history when acknowledging tasks (#27803)
Co-authored-by: maria-rcks <[email protected]>
1 parent 9fda652 commit 8f1e61c

3 files changed

Lines changed: 168 additions & 6 deletions

File tree

‎apps/server/src/mcp/OrchestratorMcpService.ts‎

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1703,7 +1703,17 @@ const make = Effect.gen(function* () {
17031703
task.completionDelivery?.state !== "acknowledged" &&
17041704
task.completionDelivery?.state !== "disposed"
17051705
) {
1706-
const parentProjection = yield* loadProjection(scope.thread.threadId);
1706+
const parentThreadId = scope.thread.threadId;
1707+
const parentProjection = yield* threadManagement
1708+
.getThreadRecords(parentThreadId, ["runs"])
1709+
.pipe(
1710+
Effect.mapError((error) =>
1711+
failure(
1712+
"orchestration_error",
1713+
`Unable to read thread ${parentThreadId}: ${errorMessage(error)}`,
1714+
),
1715+
),
1716+
);
17071717
const observingRun = ThreadManagementService.latestActiveRun(parentProjection);
17081718
yield* threadManagement
17091719
.dispatch({

‎apps/server/src/orchestration-v2/Orchestrator.ts‎

Lines changed: 15 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2378,8 +2378,8 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
23782378
const projection = yield* projectionStore
23792379
.getThreadRecords(
23802380
command.parentThreadId,
2381-
["subagents", "runs", "messages", "nodes", "attempts", "turnItems"],
2382-
{ turnItemTypes: [], messageRoles: ["user"] },
2381+
["subagents", "runs", "nodes", "attempts", "turnItems"],
2382+
{ turnItemTypes: [] },
23832383
)
23842384
.pipe(
23852385
Effect.mapError(
@@ -2467,8 +2467,19 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
24672467
return;
24682468
}
24692469

2470+
const { messages } = yield* projectionStore
2471+
.getThreadRecords(command.parentThreadId, ["messages"], {
2472+
messageRoles: ["user"],
2473+
messageIds: [delivery.messageId],
2474+
})
2475+
.pipe(
2476+
Effect.mapError(
2477+
(cause) => new OrchestratorProjectionError({ threadId: command.parentThreadId, cause }),
2478+
),
2479+
);
2480+
const deliveryProjection = { ...projection, messages };
24702481
const remainingTaskIds = delivery.taskIds.filter((taskId) => taskId !== task.id);
2471-
const deliveryRun = completionDeliveryRun(projection, delivery);
2482+
const deliveryRun = completionDeliveryRun(deliveryProjection, delivery);
24722483
const clearDelivery =
24732484
remainingTaskIds.length === 0 &&
24742485
(deliveryRun === undefined || deliveryRun.status === "queued");
@@ -2505,7 +2516,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
25052516
});
25062517
return parentRun.id;
25072518
}
2508-
const message = completionDeliveryMessage(projection, delivery);
2519+
const message = completionDeliveryMessage(deliveryProjection, delivery);
25092520
if (message !== undefined) {
25102521
yield* emitEvent({
25112522
type: "message.updated",

‎apps/server/src/peer/RemoteDelegation.test.ts‎

Lines changed: 142 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@ import * as Queue from "effect/Queue";
2929
import * as Ref from "effect/Ref";
3030
import * as Schedule from "effect/Schedule";
3131
import * as Stream from "effect/Stream";
32+
import * as Tracer from "effect/Tracer";
3233
import * as SubscriptionRef from "effect/SubscriptionRef";
3334
import type * as SqlClient from "effect/sql/SqlClient";
3435
import { McpSchema, McpServer } from "effect/ai";
@@ -845,15 +846,155 @@ it.effect("a task delegated to the box wakes the laptop's parent when it ends th
845846
);
846847
expect(Option.isSome(offered)).toBe(true);
847848

848-
const status = yield* a.call("task_status", { taskId: delegated.taskId });
849+
const messageReads: Array<string> = [];
850+
const tracer = Tracer.make({
851+
span(options) {
852+
const span = new Tracer.NativeSpan(options);
853+
const end = span.end.bind(span);
854+
span.end = (endTime, exit) => {
855+
end(endTime, exit);
856+
const query = span.attributes.get("db.query.text");
857+
if (
858+
typeof query === "string" &&
859+
/SELECT[\s\S]*FROM orchestration_v2_projection_messages/i.test(query)
860+
) {
861+
messageReads.push(query);
862+
}
863+
};
864+
return span;
865+
},
866+
});
867+
const status = yield* a
868+
.call("task_status", { taskId: delegated.taskId })
869+
.pipe(Effect.withTracer(tracer));
849870
expect(status.structuredContent).toMatchObject({
850871
status: "completed",
851872
summary: "All 412 tests pass on the box.",
852873
});
874+
// Delivery validation still reads messages; choosing the observer does not need another read.
875+
expect(messageReads).toHaveLength(2);
876+
expect(messageReads.filter((query) => !/\bmessage_id\s+IN\b/i.test(query))).toHaveLength(1);
877+
const acknowledged = yield* a.projections.getThreadRecords(parentThreadId, ["subagents"], {
878+
subagentIds: [delegated.taskId],
879+
});
880+
expect(acknowledged.subagents[0]?.completionDelivery).toEqual({
881+
state: "acknowledged",
882+
observedByRunId: parentRunId,
883+
});
853884
}),
854885
).pipe(Effect.provide(NodeHttpServer.layerTest)),
855886
);
856887

888+
it.effect.each(["no active parent run", "a newer run owned by another provider"] as const)(
889+
"preserves remote observation guards with %s",
890+
(observer) =>
891+
Effect.scoped(
892+
Effect.gen(function* () {
893+
const thread = yield* makeBoxThread;
894+
const b = yield* serveBox(thread);
895+
const offers = yield* SubscriptionRef.make<
896+
ReadonlyArray<ProviderContinuationRequests.ProviderContinuationRequest>
897+
>([]);
898+
const database = yield* SqlitePersistence.layerMemory.pipe(Layer.build);
899+
const a = yield* makeLaptop(database, offers);
900+
yield* linkTo(a.links, b, "full-access");
901+
yield* seedParent(a);
902+
const delegated = yield* delegateToBox(a);
903+
904+
yield* Ref.set(thread.reply, "Remote result remains available.");
905+
yield* Ref.set(thread.status, "completed");
906+
yield* Deferred.succeed(thread.finished, undefined);
907+
yield* taskResult(a, delegated.taskId);
908+
yield* SubscriptionRef.changes(offers).pipe(
909+
Stream.filter((seen) => seen.some((offer) => offer.threadId === parentThreadId)),
910+
Stream.runHead,
911+
);
912+
913+
const parent = yield* a.projections.getThreadRecords(
914+
parentThreadId,
915+
["runs", "subagents"],
916+
{
917+
subagentIds: [delegated.taskId],
918+
},
919+
);
920+
expect(parent.subagents[0]?.completionDelivery?.state).not.toBe("acknowledged");
921+
const parentRun = parent.runs.find((run) => run.id === parentRunId);
922+
if (parentRun === undefined) return yield* Effect.die("The parent run was not seeded.");
923+
const now = yield* DateTime.now;
924+
const otherInstanceId = ProviderInstanceId.make("codex-other");
925+
const observingRun: OrchestrationV2Run =
926+
observer === "no active parent run"
927+
? { ...parentRun, status: "completed", completedAt: now }
928+
: {
929+
id: RunId.make("run:laptop-other-provider"),
930+
threadId: parentThreadId,
931+
ordinal: parentRun.ordinal + 1,
932+
providerInstanceId: otherInstanceId,
933+
modelSelection: { instanceId: otherInstanceId, model: "gpt-5.4" },
934+
providerThreadId: null,
935+
userMessageId: MessageId.make("message:laptop-other-provider"),
936+
rootNodeId: null,
937+
activeAttemptId: null,
938+
status: "preparing",
939+
requestedAt: now,
940+
startedAt: null,
941+
completedAt: null,
942+
checkpointId: null,
943+
contextHandoffId: null,
944+
};
945+
yield* a.sink.write({
946+
commandId: CommandId.make("command:change-remote-result-observer"),
947+
events: [
948+
{
949+
id: EventId.make("event:change-remote-result-observer"),
950+
type: "run.updated",
951+
threadId: parentThreadId,
952+
runId: observingRun.id,
953+
providerInstanceId: observingRun.providerInstanceId,
954+
occurredAt: now,
955+
payload: observingRun,
956+
},
957+
],
958+
});
959+
960+
const status = yield* a.call("task_status", { taskId: delegated.taskId });
961+
if (observer === "no active parent run") {
962+
expect(status.isError).toBe(true);
963+
expect(status.content).toEqual([
964+
{
965+
type: "text",
966+
text: JSON.stringify({
967+
_tag: "OrchestratorMcpFailure",
968+
code: "parent_not_active",
969+
message: "The calling provider no longer owns an active thread run.",
970+
}),
971+
},
972+
]);
973+
const unacknowledged = yield* a.projections.getThreadRecords(
974+
parentThreadId,
975+
["subagents"],
976+
{ subagentIds: [delegated.taskId] },
977+
);
978+
expect(unacknowledged.subagents[0]?.result).toBe("Remote result remains available.");
979+
expect(unacknowledged.subagents[0]?.completionDelivery?.state).not.toBe("acknowledged");
980+
return;
981+
}
982+
expect(status.isError, JSON.stringify(status.content)).not.toBe(true);
983+
expect(status.structuredContent).toMatchObject({
984+
status: "completed",
985+
summary: "Remote result remains available.",
986+
});
987+
const acknowledged = yield* a.projections.getThreadRecords(parentThreadId, ["subagents"], {
988+
subagentIds: [delegated.taskId],
989+
});
990+
expect(acknowledged.subagents[0]?.completionDelivery).toEqual({
991+
state: "acknowledged",
992+
observedByRunId: null,
993+
});
994+
}),
995+
).pipe(Effect.provide(NodeHttpServer.layerTest)),
996+
);
997+
857998
it.effect(
858999
"with the beta off here, a task already running there still ends, and no new one starts",
8591000
() =>

0 commit comments

Comments
 (0)