TypeScript
fix(server): publish committed events before writer cancellation (#24836)
Yash Singh30fd973de3ed
diff --git a/apps/server/src/orchestration-v2/DelegatedCompletionDelivery.test.ts b/apps/server/src/orchestration-v2/DelegatedCompletionDelivery.test.tsindex 883a28f95c6..ecea6544f15 100644--- a/apps/server/src/orchestration-v2/DelegatedCompletionDelivery.test.ts+++ b/apps/server/src/orchestration-v2/DelegatedCompletionDelivery.test.ts@@ -2335,6 +2335,72 @@ it.layer(layerTest)("delegated tasks across a server restart", (it) => {}),);+ it.effect(+ "recovers an unpublished child failure after its completion delivery was disposed",+ () =>+ Effect.gen(function* () {+ const orchestrator = yield* Orchestrator.OrchestratorV2;+ const eventSink = yield* EventSink.EventSinkV2;+ const now = yield* DateTime.now;+ const threadId = ThreadId.make("thread:unpublished-failure-parent");+ const projectId = ProjectId.make("project:unpublished-failure-parent");+ const runId = RunId.make("run:unpublished-failure-parent");+ const rootNodeId = NodeId.make("node:unpublished-failure-parent-root");+ yield* seedParentWithTerminalTask({+ threadId,+ projectId,+ runId,+ rootNodeId,+ taskId: NodeId.make("node:unpublished-failure-parent-settled"),+ deliveryState: "delivered",+ now,+ });+ const child = yield* seedRestartCancelledChild({+ parentThreadId: threadId,+ projectId,+ parentRunId: runId,+ rootNodeId,+ name: "unpublished-failure-child",+ completionWake: "always",+ continuationPending: false,+ now,+ });+ // Skip the live terminal listener to model a committed failure whose+ // publication was interrupted. task_cancel then disposed its delivery.+ yield* eventSink.write({+ commandId: reconcileCommandId("unpublished-failure"),+ events: [+ runEvent({+ threadId: child.childThreadId,+ runId: child.childRunId,+ ordinal: 1,+ status: "failed",+ now,+ }),+ ],+ });+ yield* orchestrator.dispatch({+ type: "delegated_task.completion-delivery.dispose",+ commandId: CommandId.make("command:unpublished-failure-dispose"),+ parentThreadId: threadId,+ taskId: child.taskId,+ });+ yield* orchestrator.recoverDelegatedTasks;+ const recovered = yield* orchestrator.getThreadProjection(threadId);+ const task = recovered.subagents.find((row) => row.id === child.taskId);+ assert.equal(task?.status, "failed");+ assert.equal(task?.result, "Child task ended with status failed.");+ assert.equal(task?.completionDelivery?.state, "disposed");+ assert.lengthOf(recovered.runs, 1);+ assert.lengthOf(+ recovered.contextTransfers.filter((transfer) => transfer.type === "subagent_result"),+ 1,+ );+ yield* orchestrator.recoverDelegatedTasks;+ assert.deepEqual(yield* orchestrator.getThreadProjection(threadId), recovered);+ }),+ );+it.effect("wakes the parent for a settled_only task once its spawning turn ended", () =>Effect.gen(function* () {const orchestrator = yield* Orchestrator.OrchestratorV2;diff --git a/apps/server/src/orchestration-v2/EventSink.ts b/apps/server/src/orchestration-v2/EventSink.tsindex 939b8047578..af8fa5a95af 100644--- a/apps/server/src/orchestration-v2/EventSink.ts+++ b/apps/server/src/orchestration-v2/EventSink.ts@@ -258,7 +258,7 @@ const layerBase: Layer.Layer<transaction: Effect.Effect<A, E, R>,publish: (committed: A) => Effect.Effect<void>,) =>- Effect.suspend(() => {+ Effect.uninterruptibleMask((restore) => {let holdsLane = false;const takeLane = publishLane.take(1).pipe(Effect.andThen(@@ -268,8 +268,11 @@ const layerBase: Layer.Layer<),Effect.uninterruptible,);+ // Cancellation may roll back the transaction's work. Once it commits,+ // every subscriber must hear about it before this writer can exit.+ // Otherwise a failed child run can leave its parent's task running.return sql- .withTransaction(Effect.tap(transaction, () => takeLane))+ .withTransaction(Effect.tap(restore(transaction), () => takeLane)).pipe(Effect.tap(publish),Effect.ensuring(diff --git a/apps/server/src/orchestration-v2/FoundationPersistence.test.ts b/apps/server/src/orchestration-v2/FoundationPersistence.test.tsindex 0cc9fdbe3d0..93af17983c7 100644--- a/apps/server/src/orchestration-v2/FoundationPersistence.test.ts+++ b/apps/server/src/orchestration-v2/FoundationPersistence.test.ts@@ -3295,3 +3295,107 @@ it.effect("loads a shell snapshot while the writer connection is occupied", () =}).pipe(Effect.provide(projectionLayer));}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),);++it.effect.each(["cancel transaction", "fail transaction", "cancel publication"] as const)(+ "preserves event consistency and allows later writes after %s",+ (scenario) =>+ Effect.gen(function* () {+ const paused = yield* Deferred.make<void>();+ const release = yield* Deferred.make<void>();+ const committed = scenario === "cancel publication";+ const pause = Deferred.succeed(paused, undefined).pipe(+ Effect.andThen(Deferred.await(release)),+ );+ const layerPausingOutbox = Layer.effect(+ EffectOutbox.EffectOutboxV2,+ Effect.gen(function* () {+ const delegate = yield* EffectOutbox.EffectOutboxV2;+ return EffectOutbox.EffectOutboxV2.of({+ ...delegate,+ enqueue: (effects) =>+ delegate+ .enqueue(effects)+ .pipe(+ Effect.andThen(!committed && effects.length > 0 ? pause : Effect.void),+ Effect.andThen(+ scenario === "fail transaction" && effects.length > 0+ ? Effect.die("Injected transaction failure")+ : Effect.void,+ ),+ ),+ notifyAvailable: (count) =>+ (committed ? pause : Effect.void).pipe(+ Effect.andThen(delegate.notifyAvailable(count)),+ ),+ });+ }),+ ).pipe(Layer.provide(layerEffectOutboxProvided));+ const layerEventSink = EventSink.layerFromStores.pipe(+ Layer.provide(+ Layer.mergeAll(+ layerStoresProvided,+ layerPausingOutbox,+ layerCommandReceiptStoreProvided,+ ProjectStore.layer.pipe(Layer.provide(layerDatabase)),+ TurnItemPositionStore.layer.pipe(Layer.provide(layerDatabase)),+ ),+ ),+ );++ yield* Effect.gen(function* () {+ const eventSink = yield* EventSink.EventSinkV2;+ const projections = yield* ProjectionStore.ProjectionStoreV2;+ const outbox = yield* EffectOutbox.EffectOutboxV2;+ const now = yield* DateTime.now;+ const first = makeThread(ThreadId.make("thread:interrupted-publish:first"), now);+ const marker = makeThread(ThreadId.make("thread:interrupted-publish:marker"), now);+ const published = yield* eventSink+ .stream({ afterSequence: yield* eventSink.latestSequence() })+ .pipe(+ Stream.takeUntil((stored) => stored.event.threadId === marker.id),+ Stream.runCollect,+ Effect.forkScoped({ startImmediately: true }),+ );+ const writer = yield* eventSink+ .writeWithEffects({+ events: [+ threadCreatedEvent({ id: "event:interrupted-publish:first", thread: first, now }),+ ],+ effects: [+ {+ id: "effect:interrupted-publish:first",+ commandId: CommandId.make("command:interrupted-publish:first"),+ threadId: first.id,+ request: { type: "terminal.cleanup" },+ },+ ],+ })+ .pipe(Effect.forkScoped);+ yield* Deferred.await(paused);+ if (scenario !== "fail transaction") writer.interruptUnsafe();+ if (scenario !== "cancel transaction") yield* Deferred.succeed(release, undefined);+ assert.equal((yield* Fiber.await(writer))._tag, "Failure");+ assert.equal(+ (yield* projections.getThreadShell(first.id))?.id ?? null,+ committed ? first.id : null,+ );+ assert.equal(+ Option.isSome(yield* outbox.get("effect:interrupted-publish:first")),+ committed,+ );+ yield* eventSink.write({+ events: [+ threadCreatedEvent({ id: "event:interrupted-publish:marker", thread: marker, now }),+ ],+ });+ assert.deepEqual(+ Array.from(yield* Fiber.join(published), (stored) => stored.event.threadId),+ committed ? [first.id, marker.id] : [marker.id],+ );+ }).pipe(+ Effect.provide(+ Layer.mergeAll(layerEventSink, layerStoresProvided, layerEffectOutboxProvided),+ ),+ );+ }).pipe(Effect.provide(layerDatabase)),+);