TypeScript
fix(server): preserve settled runs during delegated acknowledgements (#25672)
Julius Marminge32bf48f42820
diff --git a/apps/server/src/orchestration-v2/DelegatedCompletionDelivery.test.ts b/apps/server/src/orchestration-v2/DelegatedCompletionDelivery.test.tsindex 3bf563c1f79..e426eece006 100644--- a/apps/server/src/orchestration-v2/DelegatedCompletionDelivery.test.ts+++ b/apps/server/src/orchestration-v2/DelegatedCompletionDelivery.test.ts@@ -974,6 +974,104 @@ it.layer(layerTest)("delegated completion delivery repairs", (it) => {);}),);++ it.effect.each([+ { before: "running", after: "failed", capture: false },+ { before: "waiting", after: "completed", capture: true },+ ] as const)(+ "keeps a $after run that settled between task_status's acknowledge read and commit",+ ({ before, after, capture }) =>+ Effect.gen(function* () {+ const orchestrator = yield* Orchestrator.OrchestratorV2;+ const sink = yield* EventSink.EventSinkV2;+ const now = yield* DateTime.now;+ const threadId = ThreadId.make(`thread:ack-settle-race-${after}`);+ const runId = RunId.make(`run:ack-settle-race-${after}`);+ const taskId = NodeId.make(`node:ack-settle-race-${after}-task`);+ const checkpointId = CheckpointId.make(`checkpoint:ack-settle-race-${after}`);+ yield* seedParentWithTerminalTask({+ threadId,+ projectId: ProjectId.make(`project:ack-settle-race-${after}`),+ runId,+ rootNodeId: NodeId.make(`node:ack-settle-race-${after}-root`),+ taskId,+ deliveryState: "claimed",+ deliveryTaskIds: [taskId],+ now,+ });+ const parent = (yield* orchestrator.getThreadProjection(threadId)).runs[0]!;+ yield* sink.write({+ events: [+ {+ id: EventId.make(`event:ack-settle-race-${after}-before`),+ type: "run.updated",+ threadId,+ runId,+ occurredAt: now,+ payload: { ...parent, status: before },+ },+ ],+ });+ const { delegatedCompletion: _cohort, ...settledRun } = parent;+ const commit = sink.commitCommand;+ let settled = false;+ yield* Effect.acquireUseRelease(+ Effect.sync(() =>+ vi.spyOn(sink, "commitCommand").mockImplementation((input) =>+ Effect.gen(function* () {+ if (+ !settled &&+ input.commandType === "delegated_task.completion-delivery.acknowledge"+ ) {+ settled = true;+ // The provider turn ends (or its checkpoint lands) after acknowledge read the run.+ yield* commit({+ commandId: CommandId.make(`command:ack-settle-race-${after}`),+ threadId,+ commandType: capture ? "checkpoint.capture" : "provider.event",+ acceptedAt: now,+ effects: [],+ events: [+ {+ id: EventId.make(`event:ack-settle-race-${after}-settled`),+ type: "run.updated",+ threadId,+ runId,+ occurredAt: now,+ payload: {+ ...settledRun,+ status: after,+ completedAt: now,+ checkpointId: capture ? checkpointId : null,+ },+ },+ ],+ });+ }+ return yield* commit(input);+ }),+ ),+ ),+ () =>+ orchestrator.dispatch({+ type: "delegated_task.completion-delivery.acknowledge",+ commandId: CommandId.make(`command:ack-settle-race-${after}:task-status`),+ parentThreadId: threadId,+ taskId,+ observedByRunId: runId,+ }),+ (spy) => Effect.sync(() => spy.mockRestore()),+ );+ assert.isTrue(settled);+ const run = (yield* orchestrator.getThreadProjection(threadId)).runs.find(+ (candidate) => candidate.id === runId,+ )!;+ assert.deepEqual(+ { status: run.status, completedAt: run.completedAt, checkpointId: run.checkpointId },+ { status: after, completedAt: now, checkpointId: capture ? checkpointId : null },+ );+ }),+ );});const reconcileCommandId = (name: string) => CommandId.make(`command:runtime-reconcile:${name}`);diff --git a/apps/server/src/orchestration-v2/EventSink.ts b/apps/server/src/orchestration-v2/EventSink.tsindex af8fa5a95af..b210d3c9840 100644--- a/apps/server/src/orchestration-v2/EventSink.ts+++ b/apps/server/src/orchestration-v2/EventSink.ts@@ -146,6 +146,8 @@ export interface EventSinkV2Shape {readonly effectTypes: ReadonlyArray<EffectOutbox.OrchestrationEffectRequestV2["type"]>;readonly reason: string;};+ /** Like writeWithEffects' updateDelegatedCompletionOnly, for this run's run.updated only. */+ readonly updateDelegatedCompletionOnlyRunId?: RunId;}) => Effect.Effect<{readonly receipt: CommandReceiptStore.CommandReceiptV2;@@ -383,6 +385,28 @@ const layerBase: Layer.Layer<return yield* runOutcomes.prepare(storedEvents);});+ // The enclosing write or commit span already traces this per-event projection merge.+ const updateDelegatedCompletionOnly = Effect.fnUntraced(function* (+ events: ReadonlyArray<OrchestrationV2DomainEvent>,+ includesRun: (runId: RunId) => boolean,+ ) {+ return yield* Effect.forEach(events, (event) =>+ Effect.gen(function* () {+ if (event.type !== "run.updated" || !includesRun(event.payload.id)) return event;+ const { runs } = yield* projectionStore.getThreadRecords(event.threadId, ["runs"], {+ runIds: [event.payload.id],+ });+ const current = runs[0];+ return current === undefined+ ? event+ : {+ ...event,+ payload: { ...current, delegatedCompletion: event.payload.delegatedCompletion },+ };+ }),+ );+ });+const writeEffect = Effect.fn("orchestrationV2.EventSink.write")(function* (input: Parameters<EventSinkV2Shape["writeWithEffects"]>[0],) {@@ -411,26 +435,7 @@ const layerBase: Layer.Layer<// Checkpoint capture can finish after a cohort writer reads its parent run.// Merge in this transaction so the event log and projection keep that completion.const events = input.updateDelegatedCompletionOnly- ? yield* Effect.forEach(input.events, (event) =>- Effect.gen(function* () {- if (event.type !== "run.updated") return event;- const { runs } = yield* projectionStore.getThreadRecords(- event.threadId,- ["runs"],- { runIds: [event.payload.id] },- );- const current = runs[0];- return current === undefined- ? event- : {- ...event,- payload: {- ...current,- delegatedCompletion: event.payload.delegatedCompletion,- },- };- }),- )+ ? yield* updateDelegatedCompletionOnly(input.events, () => true): input.events;const normalized = yield* normalizeEvents(input.guardPendingUserInputCancellations === true@@ -646,7 +651,12 @@ const layerBase: Layer.Layer<return { ...existing, committed: false as const, cancelledEffectIds: [] };}- const normalized = yield* normalizeEvents(input.events);+ const runId = input.updateDelegatedCompletionOnlyRunId;+ const normalized = yield* normalizeEvents(+ runId === undefined+ ? input.events+ : yield* updateDelegatedCompletionOnly(input.events, (id) => id === runId),+ );const storedEvents = yield* eventStore.append({commandId: input.commandId,events: normalized,diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.tsindex 0c6ca268f1e..ee8ab83b952 100644--- a/apps/server/src/orchestration-v2/Orchestrator.ts+++ b/apps/server/src/orchestration-v2/Orchestrator.ts@@ -2358,7 +2358,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functiorun: deliveryRun,now,});- return;+ return parentRun.id;}const message = completionDeliveryMessage(projection, delivery);if (message !== undefined) {@@ -2382,6 +2382,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio});}}+ return parentRun.id;});const disposeDelegatedCompletionCohort = Effect.fn(@@ -11752,6 +11753,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functioreadonly effectTypes: ReadonlyArray<OrchestrationEffectRequestV2["type"]>;readonly reason: string;};+ readonly updateDelegatedCompletionOnlyRunId?: RunId;},OrchestratorV2Error> {@@ -11769,6 +11771,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functioreadonly reason: string;}| undefined;+ let updateDelegatedCompletionOnlyRunId: RunId | undefined;switch (command.type) {case "thread.create":yield* dispatchThreadCreate(command, events);@@ -12080,7 +12083,8 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functiobreak;case "delegated_task.completion-delivery.acknowledge":case "delegated_task.completion-delivery.dispose":- yield* dispatchDelegatedTaskCompletionDeliveryResolution(command, events);+ updateDelegatedCompletionOnlyRunId =+ yield* dispatchDelegatedTaskCompletionDeliveryResolution(command, events);break;case "thread.created.record":yield* dispatchCreatedThreadRecord(command, events);@@ -12095,6 +12099,9 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functioevents: yield* Ref.get(events),effects: yield* Ref.get(effects),...(cancelUnsettledEffects === undefined ? {} : { cancelUnsettledEffects }),+ ...(updateDelegatedCompletionOnlyRunId === undefined+ ? {}+ : { updateDelegatedCompletionOnlyRunId }),};});@@ -12271,6 +12278,9 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio...(plan.cancelUnsettledEffects === undefined? {}: { cancelUnsettledEffects: plan.cancelUnsettledEffects }),+ ...(plan.updateDelegatedCompletionOnlyRunId === undefined+ ? {}+ : { updateDelegatedCompletionOnlyRunId: plan.updateDelegatedCompletionOnlyRunId }),}).pipe(Effect.mapError(