fix(orchestrator): schedule effects from durable deadlines (#4656)

Co-authored-by: codex <[email protected]>
This commit is contained in:
Julius Marmingeandcodex committed 2026-08-15 16:50:12 +02:00
1 parent 50030b4e61
commit 6ef497fc24
6 files changed
+569 -49

No files matched your search

+12
View File
@@ -42,6 +42,18 @@ export const orchestrationEventsProcessedTotal = Metric.counter(
},
);
export const orchestrationEffectClaimsTotal = Metric.counter(
"t3_orchestration_effect_claims_total",
{
description: "Total completed orchestration effect outbox claim attempts by result.",
},
);
export const orchestrationEffectQueueWait = Metric.timer("t3_orchestration_effect_queue_wait", {
description:
"Time from an orchestration effect's temporal availability until claim, including same-thread blocking.",
});
export const providerSessionsTotal = Metric.counter("t3_provider_sessions_total", {
description: "Total provider session lifecycle operations.",
});
@@ -159,7 +159,8 @@ const isEffectOutboxError = Schema.is(EffectOutboxError);
export interface EffectOutboxV2Shape {
readonly awaitAvailable: Effect.Effect<void>;
readonly notifyAvailable: Effect.Effect<void>;
readonly notifyAvailable: (count?: number) => Effect.Effect<void>;
/** Persist rows only. Notify workers after the surrounding transaction commits. */
readonly enqueue: (
effects: ReadonlyArray<PendingOrchestrationEffectV2>,
) => Effect.Effect<void, EffectOutboxError>;
@@ -185,6 +186,7 @@ export interface EffectOutboxV2Shape {
readonly workerId: string;
readonly leaseDurationMs: number;
}) => Effect.Effect<Option.Option<OrchestrationEffectV2>, EffectOutboxError>;
readonly nextClaimableAt: Effect.Effect<Option.Option<DateTime.Utc>, EffectOutboxError>;
readonly succeed: (input: {
readonly effectId: string;
readonly workerId: string;
@@ -258,6 +260,26 @@ export const layer: Layer.Layer<EffectOutboxV2, never, SqlClient.SqlClient> = La
// for distinct threads without allowing notifications to grow unbounded.
const available = yield* Queue.dropping<void>(64);
const cancellationSignals = new Map<string, Deferred.Deferred<void>>();
const notifyAvailable = (count = 1) =>
Queue.offerAll(
available,
Array.from({ length: Math.min(64, Math.max(0, Math.floor(count))) }, () => undefined),
).pipe(Effect.asVoid);
const claimableCandidatePredicate = (availableBefore?: string) =>
sql`
${
availableBefore === undefined
? sql`1 = 1`
: sql`candidate.available_at <= ${availableBefore}`
}
AND candidate.status = 'pending'
AND NOT EXISTS (
SELECT 1
FROM orchestration_v2_effect_outbox AS active
WHERE active.thread_id = candidate.thread_id
AND active.status = 'running'
)
`;
const cancellationSignal = (effectId: string) => {
const existing = cancellationSignals.get(effectId);
@@ -308,12 +330,9 @@ export const layer: Layer.Layer<EffectOutboxV2, never, SqlClient.SqlClient> = La
`,
{ concurrency: 1, discard: true },
);
if (effects.length > 0) {
yield* Queue.offerAll(
available,
Array.from({ length: Math.min(effects.length, 64) }, () => undefined),
);
}
// Do not signal here: callers enqueue inside a larger transaction,
// and workers must only observe availability after that transaction
// commits. EventSink owns the corresponding post-commit notification.
}).pipe(Effect.mapError((cause) => new EffectOutboxError({ operation: "enqueue", cause }))),
get: (effectId) =>
sql<EffectRow>`
@@ -331,7 +350,7 @@ export const layer: Layer.Layer<EffectOutboxV2, never, SqlClient.SqlClient> = La
Effect.mapError((cause) => new EffectOutboxError({ operation: "get", effectId, cause })),
),
awaitAvailable: Queue.take(available),
notifyAvailable: Queue.offer(available, undefined).pipe(Effect.asVoid),
notifyAvailable,
listByCommandId: (commandId) =>
sql<EffectRow>`
SELECT *
@@ -371,14 +390,20 @@ export const layer: Layer.Layer<EffectOutboxV2, never, SqlClient.SqlClient> = La
),
),
signalCancellations: (effectIds) =>
Effect.forEach(
effectIds,
(effectId) => {
const signal = cancellationSignals.get(effectId);
return signal === undefined ? Effect.void : Deferred.succeed(signal, undefined);
},
{ discard: true },
),
Effect.gen(function* () {
yield* Effect.forEach(
effectIds,
(effectId) => {
const signal = cancellationSignals.get(effectId);
return signal === undefined ? Effect.void : Deferred.succeed(signal, undefined);
},
{ discard: true },
);
// Cancellation can unblock other pending work on the same thread.
// This method is deliberately post-commit, so it is also the safe
// place to wake claimers after the durable status change.
if (effectIds.length > 0) yield* notifyAvailable(effectIds.length);
}),
awaitCancellation: (effectId) => Deferred.await(cancellationSignal(effectId)),
clearCancellation: (effectId) =>
Effect.sync(() => {
@@ -412,7 +437,7 @@ export const layer: Layer.Layer<EffectOutboxV2, never, SqlClient.SqlClient> = La
AND effect_type IN ${sql.in(REPLAY_SAFE_EFFECT_TYPES_AFTER_PROCESS_LOSS)}
RETURNING effect_id
`;
if (requeuedRows.length > 0) yield* Queue.offer(available, undefined);
if (requeuedRows.length > 0) yield* notifyAvailable(requeuedRows.length);
return { requeued: requeuedRows.length, cancelled: cancelledRows.length };
}).pipe(
Effect.mapError(
@@ -426,7 +451,10 @@ export const layer: Layer.Layer<EffectOutboxV2, never, SqlClient.SqlClient> = La
const leaseExpiresAt = DateTime.formatIso(
DateTime.add(now, { milliseconds: Math.max(1, leaseDurationMs) }),
);
const rows = yield* sql<EffectRow>`
// Empty safety claims are expected while the daemon is idle. Tracing
// this query records the full SQL text on every poll and can dominate
// the local trace without adding actionable information.
const claimStatement = sql<EffectRow>`
UPDATE orchestration_v2_effect_outbox
SET
status = 'running',
@@ -438,24 +466,41 @@ export const layer: Layer.Layer<EffectOutboxV2, never, SqlClient.SqlClient> = La
WHERE effect_id = (
SELECT candidate.effect_id
FROM orchestration_v2_effect_outbox AS candidate
WHERE candidate.available_at <= ${nowIso}
AND candidate.status = 'pending'
AND NOT EXISTS (
SELECT 1
FROM orchestration_v2_effect_outbox AS active
WHERE active.thread_id = candidate.thread_id
AND active.status = 'running'
)
WHERE ${claimableCandidatePredicate(nowIso)}
ORDER BY candidate.available_at ASC, candidate.created_at ASC, candidate.effect_id ASC
LIMIT 1
)
RETURNING *
`;
const rows = yield* claimStatement.pipe(Effect.withTracerEnabled(false));
const row = rows[0];
if (row === undefined) return Option.none();
cancellationSignals.set(row.effect_id, Deferred.makeUnsafe<void>());
return Option.some(yield* rowToEffect(row));
}).pipe(Effect.mapError((cause) => new EffectOutboxError({ operation: "claim", cause }))),
nextClaimableAt: Effect.gen(function* () {
const rows = yield* sql<{ readonly available_at: string | null }>`
SELECT MIN(candidate.available_at) AS available_at
FROM orchestration_v2_effect_outbox AS candidate
WHERE ${claimableCandidatePredicate()}
`.pipe(Effect.withTracerEnabled(false));
const availableAt = rows[0]?.available_at;
if (availableAt === undefined || availableAt === null) return Option.none();
const parsed = DateTime.make(availableAt);
if (Option.isNone(parsed)) {
return yield* new EffectOutboxError({
operation: "next-claimable",
cause: `Invalid available_at timestamp: ${availableAt}`,
});
}
return parsed;
}).pipe(
Effect.mapError((cause) =>
isEffectOutboxError(cause)
? cause
: new EffectOutboxError({ operation: "next-claimable", cause }),
),
),
succeed: ({ effectId, workerId }) =>
Effect.gen(function* () {
const now = DateTime.formatIso(yield* DateTime.now);
@@ -473,7 +518,10 @@ export const layer: Layer.Layer<EffectOutboxV2, never, SqlClient.SqlClient> = La
AND lease_owner = ${workerId}
RETURNING effect_id
`;
if (rows.length === 1) cancellationSignals.delete(effectId);
if (rows.length === 1) {
cancellationSignals.delete(effectId);
yield* notifyAvailable();
}
return rows.length === 1;
}).pipe(
Effect.mapError(
@@ -501,7 +549,10 @@ export const layer: Layer.Layer<EffectOutboxV2, never, SqlClient.SqlClient> = La
AND lease_owner = ${workerId}
RETURNING effect_id
`;
if (rows.length === 1) cancellationSignals.delete(effectId);
if (rows.length === 1) {
cancellationSignals.delete(effectId);
yield* notifyAvailable();
}
return rows.length === 1;
}).pipe(
Effect.mapError(
@@ -525,7 +576,10 @@ export const layer: Layer.Layer<EffectOutboxV2, never, SqlClient.SqlClient> = La
AND lease_owner = ${workerId}
RETURNING effect_id
`;
if (rows.length === 1) cancellationSignals.delete(effectId);
if (rows.length === 1) {
cancellationSignals.delete(effectId);
yield* notifyAvailable();
}
return rows.length === 1;
}).pipe(
Effect.mapError((cause) => new EffectOutboxError({ operation: "fail", effectId, cause })),
@@ -13,7 +13,9 @@ import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Queue from "effect/Queue";
import * as Ref from "effect/Ref";
import * as TestClock from "effect/testing/TestClock";
import { CheckpointRollbackServiceV2 } from "./CheckpointRollbackService.ts";
import type { OrchestrationEffectV2 } from "./EffectOutbox.ts";
@@ -21,6 +23,9 @@ import {
executorLayer,
isNonRetryableProviderTurnControlFailure,
OrchestrationEffectExecutorV2,
OrchestrationEffectWorkerError,
OrchestrationEffectWorkerV2,
runDaemonWithOptions,
} from "./EffectWorker.ts";
import { RunFinalizationService } from "./RunFinalizationService.ts";
import { ProviderSessionManagerV2 } from "./ProviderSessionManager.ts";
@@ -171,6 +176,112 @@ it("does not retry pure interrupt races where the turn is already gone", () => {
);
});
it.effect("uses durable deadlines, notifications, and a slow liveness poll", () =>
Effect.gen(function* () {
const attempts = yield* Ref.make(0);
const available = yield* Queue.unbounded<void>();
const now = yield* DateTime.now;
const nextClaimableAt = yield* Ref.make<Option.Option<DateTime.Utc>>(
Option.some(DateTime.add(now, { milliseconds: 100 })),
);
const worker = OrchestrationEffectWorkerV2.of({
awaitWork: Queue.take(available),
runOnce: Effect.gen(function* () {
const count = yield* Ref.updateAndGet(attempts, (current) => current + 1);
if (count === 2) {
yield* Ref.set(nextClaimableAt, Option.some(DateTime.add(now, { milliseconds: 5_000 })));
}
if (count === 3) yield* Ref.set(nextClaimableAt, Option.none());
return false;
}),
nextClaimableAt: Ref.get(nextClaimableAt),
drain: () => Effect.succeed(0),
});
const awaitAttempts = Effect.fnUntraced(function* (expected: number) {
while ((yield* Ref.get(attempts)) < expected) {
yield* Effect.yieldNow;
}
});
yield* runDaemonWithOptions({
concurrency: 1,
livenessPollIntervalMs: 1_000,
}).pipe(Effect.provideService(OrchestrationEffectWorkerV2, worker), Effect.forkScoped);
yield* awaitAttempts(1);
yield* TestClock.adjust("99 millis");
assert.equal(yield* Ref.get(attempts), 1);
yield* TestClock.adjust("1 millis");
yield* awaitAttempts(2);
yield* TestClock.adjust("999 millis");
assert.equal(yield* Ref.get(attempts), 2);
yield* Queue.offer(available, undefined);
yield* awaitAttempts(3);
yield* TestClock.adjust("999 millis");
assert.equal(yield* Ref.get(attempts), 3);
yield* TestClock.adjust("1 millis");
yield* awaitAttempts(4);
}).pipe(Effect.provide(TestClock.layer())),
);
it.effect("does not hot-loop when a claim fails", () =>
Effect.gen(function* () {
const attempts = yield* Ref.make(0);
const now = yield* DateTime.now;
const worker = OrchestrationEffectWorkerV2.of({
awaitWork: Effect.never,
runOnce: Ref.update(attempts, (count) => count + 1).pipe(
Effect.andThen(
new OrchestrationEffectWorkerError({
operation: "claim",
cause: "simulated database failure",
}),
),
),
nextClaimableAt: Effect.succeed(Option.some(now)),
drain: () => Effect.succeed(0),
});
yield* runDaemonWithOptions({
concurrency: 1,
livenessPollIntervalMs: 1_000,
}).pipe(Effect.provideService(OrchestrationEffectWorkerV2, worker), Effect.forkScoped);
while ((yield* Ref.get(attempts)) < 1) yield* Effect.yieldNow;
yield* TestClock.adjust("999 millis");
assert.equal(yield* Ref.get(attempts), 1);
yield* TestClock.adjust("1 millis");
while ((yield* Ref.get(attempts)) < 2) yield* Effect.yieldNow;
}).pipe(Effect.provide(TestClock.layer())),
);
it.effect("backs off briefly when a due deadline loses a claim race", () =>
Effect.gen(function* () {
const attempts = yield* Ref.make(0);
const now = yield* DateTime.now;
const worker = OrchestrationEffectWorkerV2.of({
awaitWork: Effect.never,
runOnce: Ref.update(attempts, (count) => count + 1).pipe(Effect.as(false)),
nextClaimableAt: Effect.succeed(Option.some(now)),
drain: () => Effect.succeed(0),
});
yield* runDaemonWithOptions({
concurrency: 1,
livenessPollIntervalMs: 1_000,
}).pipe(Effect.provideService(OrchestrationEffectWorkerV2, worker), Effect.forkScoped);
while ((yield* Ref.get(attempts)) < 1) yield* Effect.yieldNow;
yield* TestClock.adjust("24 millis");
assert.equal(yield* Ref.get(attempts), 1);
yield* TestClock.adjust("1 millis");
while ((yield* Ref.get(attempts)) < 2) yield* Effect.yieldNow;
}).pipe(Effect.provide(TestClock.layer())),
);
it.effect("detaches a handed-off session only after the old turn terminalizes", () =>
Effect.gen(function* () {
const now = yield* DateTime.now;
@@ -1,12 +1,20 @@
import * as Cause from "effect/Cause";
import * as Context from "effect/Context";
import * as DateTime from "effect/DateTime";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit";
import * as Layer from "effect/Layer";
import * as Metric from "effect/Metric";
import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
import {
increment,
metricAttributes,
orchestrationEffectClaimsTotal,
orchestrationEffectQueueWait,
} from "../observability/Metrics.ts";
import { RunFinalizationService } from "./RunFinalizationService.ts";
import { ResourceCleanupService } from "./ResourceCleanupService.ts";
import { EffectOutboxV2, type OrchestrationEffectV2 } from "./EffectOutbox.ts";
@@ -298,6 +306,10 @@ const isOrchestrationEffectWorkerError = Schema.is(OrchestrationEffectWorkerErro
export interface OrchestrationEffectWorkerV2Shape {
readonly awaitWork: Effect.Effect<void>;
readonly runOnce: Effect.Effect<boolean, OrchestrationEffectWorkerError>;
readonly nextClaimableAt: Effect.Effect<
Option.Option<DateTime.Utc>,
OrchestrationEffectWorkerError
>;
readonly drain: (maxEffects?: number) => Effect.Effect<number, OrchestrationEffectWorkerError>;
}
@@ -338,11 +350,32 @@ export const layerWithOptions = (
);
const runOnce = Effect.gen(function* () {
const claimed = yield* outbox.claimNext({ workerId, leaseDurationMs });
const claimExit = yield* Effect.exit(outbox.claimNext({ workerId, leaseDurationMs }));
yield* increment(orchestrationEffectClaimsTotal, {
result: Exit.isFailure(claimExit)
? "error"
: Option.isNone(claimExit.value)
? "empty"
: "claimed",
});
if (Exit.isFailure(claimExit)) return yield* Effect.failCause(claimExit.cause);
const claimed = claimExit.value;
if (Option.isNone(claimed)) {
return false;
}
const effect = claimed.value;
const claimedAt = DateTime.toEpochMillis(yield* DateTime.now);
const eligibleAt = Math.max(
DateTime.toEpochMillis(DateTime.makeUnsafe(effect.createdAt)),
DateTime.toEpochMillis(DateTime.makeUnsafe(effect.availableAt)),
);
yield* Metric.update(
Metric.withAttributes(
orchestrationEffectQueueWait,
metricAttributes({ effect_type: effect.request.type }),
),
Duration.millis(Math.max(0, claimedAt - eligibleAt)),
);
// Cancellation can commit after the durable claim but before the
// process-local Deferred is registered. Re-read the authoritative row
// once before starting external work; later cancellations use the
@@ -415,6 +448,15 @@ export const layerWithOptions = (
return OrchestrationEffectWorkerV2.of({
awaitWork: outbox.awaitAvailable,
runOnce,
nextClaimableAt: outbox.nextClaimableAt.pipe(
Effect.mapError(
(cause) =>
new OrchestrationEffectWorkerError({
operation: "next-claimable",
cause,
}),
),
),
drain: (maxEffects = Number.MAX_SAFE_INTEGER) =>
Effect.gen(function* () {
let completed = 0;
@@ -431,9 +473,11 @@ export const layer = layerWithOptions();
export interface OrchestrationEffectDaemonOptions {
readonly concurrency?: number;
readonly livenessPollIntervalMs?: number;
}
export const DEFAULT_EFFECT_WORKER_CONCURRENCY = 4;
export const DEFAULT_EFFECT_WORKER_LIVENESS_POLL_INTERVAL_MS = 30_000;
export const runDaemonWithOptions = (options: OrchestrationEffectDaemonOptions = {}) =>
Effect.scoped(
@@ -443,22 +487,58 @@ export const runDaemonWithOptions = (options: OrchestrationEffectDaemonOptions =
const concurrency = Number.isFinite(requestedConcurrency)
? Math.max(1, Math.floor(requestedConcurrency))
: DEFAULT_EFFECT_WORKER_CONCURRENCY;
// Notifications only reduce latency; the durable outbox remains authoritative.
// Every slot polls after a bounded delay so a missed or coalesced wakeup can
// never strand committed work. Consuming the outbox signal directly also
// avoids lifecycle coupling between a separate fan-out fiber and subscribers.
const runWorker = Effect.forever(
worker.runOnce.pipe(
Effect.catchCause((cause) =>
Effect.logWarning("Orchestration effect worker failed", cause).pipe(Effect.as(false)),
),
Effect.flatMap((worked) =>
worked
? Effect.yieldNow
: Effect.raceFirst(worker.awaitWork, Effect.sleep(Duration.millis(50))),
),
),
);
const requestedLivenessPollIntervalMs =
options.livenessPollIntervalMs ?? DEFAULT_EFFECT_WORKER_LIVENESS_POLL_INTERVAL_MS;
const livenessPollIntervalMs = Number.isFinite(requestedLivenessPollIntervalMs)
? Math.max(1, Math.floor(requestedLivenessPollIntervalMs))
: DEFAULT_EFFECT_WORKER_LIVENESS_POLL_INTERVAL_MS;
// Post-commit notifications are the low-latency path. `availableAt` is the
// durable retry schedule, and the long liveness poll only recovers from a
// missed in-process notification or work inserted by another process.
const runWorker = Effect.gen(function* () {
while (true) {
const outcome = yield* worker.runOnce.pipe(
Effect.map((worked) => (worked ? ("worked" as const) : ("idle" as const))),
Effect.catchCause((cause) =>
Effect.logWarning("Orchestration effect worker failed", cause).pipe(
Effect.as("failed" as const),
),
),
);
if (outcome === "worked") {
yield* Effect.yieldNow;
continue;
}
if (outcome === "failed") {
// A due row can remain visible when a claim UPDATE fails. Do not
// feed that past deadline back into the scheduler and retry at the
// one-millisecond floor; let transient database failures cool off.
yield* Effect.sleep(Duration.millis(Math.min(1_000, livenessPollIntervalMs)));
continue;
}
const nextClaimableAt = yield* worker.nextClaimableAt.pipe(
Effect.catchCause((cause) =>
Effect.logWarning(
"Failed to read the next orchestration effect deadline",
cause,
).pipe(Effect.as(Option.none<DateTime.Utc>())),
),
);
const now = DateTime.toEpochMillis(yield* DateTime.now);
const sleepMs = Option.match(nextClaimableAt, {
onNone: () => livenessPollIntervalMs,
onSome: (availableAt) => {
const untilAvailable = DateTime.toEpochMillis(availableAt) - now;
return Math.min(livenessPollIntervalMs, untilAvailable > 0 ? untilAvailable : 25);
},
});
yield* Effect.raceFirst(
worker.awaitWork.pipe(Effect.as("notified" as const)),
Effect.sleep(Duration.millis(sleepMs)).pipe(Effect.as("scheduled" as const)),
);
}
});
return yield* Effect.all(
Array.from({ length: concurrency }, () => runWorker),
@@ -240,7 +240,7 @@ const baseLayer: Layer.Layer<
}),
);
if (input.effects.length > 0) {
yield* effectOutbox.notifyAvailable;
yield* effectOutbox.notifyAvailable(input.effects.length);
}
yield* eventStore.publishCommitted(storedEvents);
yield* PubSub.publishAll(liveEvents, storedEvents);
@@ -367,8 +367,8 @@ const baseLayer: Layer.Layer<
}),
);
yield* effectOutbox.signalCancellations(result.cancelledEffectIds);
if (input.effects.length > 0) {
yield* effectOutbox.notifyAvailable;
if (result.committed && input.effects.length > 0) {
yield* effectOutbox.notifyAvailable(input.effects.length);
}
if (result.committed) {
yield* eventStore.publishCommitted(result.storedEvents);
@@ -30,6 +30,8 @@ import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Ref from "effect/Ref";
import * as Stream from "effect/Stream";
import * as TestClock from "effect/testing/TestClock";
import * as Tracer from "effect/Tracer";
import * as SqlClient from "effect/unstable/sql/SqlClient";
import { SqlitePersistenceMemory } from "../persistence/Layers/Sqlite.ts";
@@ -38,6 +40,7 @@ import { CommandReceiptStoreV2, layer as commandReceiptStoreLayer } from "./Comm
import { EffectOutboxV2, layer as effectOutboxLayer } from "./EffectOutbox.ts";
import {
layerWithOptions as effectWorkerLayerWithOptions,
OrchestrationEffectExecutionError,
OrchestrationEffectExecutorV2,
OrchestrationEffectWorkerV2,
runDaemonWithOptions as runEffectWorkerDaemonWithOptions,
@@ -578,6 +581,45 @@ it.layer(TestLayer)("orchestration V2 foundation persistence", (it) => {
}),
);
it.effect("does not wake claimers for effects from an idempotent command retry", () =>
Effect.gen(function* () {
const eventSink = yield* EventSinkV2;
const outbox = yield* EffectOutboxV2;
const now = yield* DateTime.now;
const commandId = CommandId.make("command:foundation-idempotent-wakeup");
const threadId = ThreadId.make("thread:foundation-idempotent-wakeup");
const input = {
commandId,
threadId,
commandType: "foundation.idempotent-wakeup",
acceptedAt: now,
events: [
threadCreatedEvent({
id: "event:foundation-idempotent-wakeup",
thread: makeThread(threadId, now),
now,
}),
],
effects: [
{
id: "effect:foundation-idempotent-wakeup",
commandId,
threadId,
request: { type: "terminal.cleanup" as const },
},
],
};
assert.isTrue((yield* eventSink.commitCommand(input)).committed);
yield* outbox.awaitAvailable;
assert.isFalse((yield* eventSink.commitCommand(input)).committed);
const unexpectedWake = yield* outbox.awaitAvailable.pipe(Effect.forkChild);
yield* Effect.yieldNow;
assert.isUndefined(unexpectedWake.pollUnsafe());
}).pipe(Effect.provide(Layer.fresh(TestLayer))),
);
it.effect("does not publish a stale provider start after an interrupt wins", () =>
Effect.gen(function* () {
const eventSink = yield* EventSinkV2;
@@ -887,6 +929,224 @@ it.layer(TestLayer)("orchestration V2 foundation persistence", (it) => {
}),
);
it.effect("ignores deadlines blocked by a running effect on the same thread", () =>
Effect.gen(function* () {
const outbox = yield* EffectOutboxV2;
const now = yield* DateTime.now;
const future = DateTime.add(now, { seconds: 10 });
const commandId = CommandId.make("command:foundation-next-claimable");
const blockedThreadId = ThreadId.make("thread:foundation-next-claimable:blocked");
yield* outbox.enqueue([
{
id: "effect:foundation-next-claimable:a1",
commandId,
threadId: blockedThreadId,
request: { type: "terminal.cleanup" },
},
{
id: "effect:foundation-next-claimable:a2",
commandId,
threadId: blockedThreadId,
request: { type: "terminal.cleanup" },
},
{
id: "effect:foundation-next-claimable:b1",
commandId,
threadId: ThreadId.make("thread:foundation-next-claimable:future"),
request: { type: "terminal.cleanup" },
availableAt: future,
},
]);
const claimed = yield* outbox.claimNext({
workerId: "next-claimable-worker",
leaseDurationMs: 30_000,
});
assert.isTrue(Option.isSome(claimed));
if (Option.isNone(claimed)) return;
assert.equal(claimed.value.id, "effect:foundation-next-claimable:a1");
const whileBlocked = yield* outbox.nextClaimableAt;
assert.isTrue(Option.isSome(whileBlocked));
if (Option.isSome(whileBlocked)) {
assert.equal(DateTime.toEpochMillis(whileBlocked.value), DateTime.toEpochMillis(future));
}
yield* outbox.succeed({
effectId: claimed.value.id,
workerId: "next-claimable-worker",
});
const afterCompletion = yield* outbox.nextClaimableAt;
assert.isTrue(Option.isSome(afterCompletion));
if (Option.isSome(afterCompletion)) {
assert.isAtMost(DateTime.toEpochMillis(afterCompletion.value), DateTime.toEpochMillis(now));
}
const unblocked = yield* outbox.claimNext({
workerId: "next-claimable-worker",
leaseDurationMs: 30_000,
});
assert.isTrue(Option.isSome(unblocked));
if (Option.isSome(unblocked)) {
assert.equal(unblocked.value.id, "effect:foundation-next-claimable:a2");
yield* outbox.succeed({
effectId: unblocked.value.id,
workerId: "next-claimable-worker",
});
}
yield* outbox.cancelUnsettled({
threadId: ThreadId.make("thread:foundation-next-claimable:future"),
effectTypes: ["terminal.cleanup"],
reason: "Test cleanup.",
});
}),
);
it.effect("does not emit a SQL span for an empty safety claim", () =>
Effect.gen(function* () {
const outbox = yield* EffectOutboxV2;
const spans: Array<string> = [];
const tracer = Tracer.make({
span: (options) => {
const span = new Tracer.NativeSpan(options);
const end = span.end.bind(span);
span.end = (endTime, exit) => {
end(endTime, exit);
spans.push(span.name);
};
return span;
},
});
const claim = yield* outbox
.claimNext({ workerId: "idle-safety-worker", leaseDurationMs: 30_000 })
.pipe(Effect.withTracer(tracer));
assert.isTrue(Option.isNone(claim));
assert.notInclude(spans, "sql.execute");
}).pipe(Effect.provide(Layer.fresh(effectOutboxProvided))),
);
it.effect("wakes claimers when cancellation unblocks same-thread work", () =>
Effect.gen(function* () {
const outbox = yield* EffectOutboxV2;
const commandId = CommandId.make("command:foundation-cancellation-wakeup");
const threadId = ThreadId.make("thread:foundation-cancellation-wakeup");
yield* outbox.enqueue([
{
id: "effect:foundation-cancellation-wakeup:a-running",
commandId,
threadId,
request: {
type: "provider-turn.start",
runId: RunId.make("run:foundation-cancellation-wakeup"),
},
},
{
id: "effect:foundation-cancellation-wakeup:b-pending",
commandId,
threadId,
request: { type: "terminal.cleanup" },
},
]);
const running = yield* outbox.claimNext({
workerId: "cancellation-wakeup-worker",
leaseDurationMs: 30_000,
});
assert.isTrue(Option.isSome(running));
if (Option.isNone(running)) return;
assert.equal(running.value.request.type, "provider-turn.start");
const cancelledEffectIds = yield* outbox.cancelUnsettled({
threadId,
effectTypes: ["provider-turn.start"],
reason: "Test cancellation wakeup.",
});
yield* outbox.signalCancellations(cancelledEffectIds);
const wake = yield* outbox.awaitAvailable.pipe(Effect.forkChild);
yield* Effect.yieldNow;
assert.isDefined(wake.pollUnsafe());
const unblocked = yield* outbox.claimNext({
workerId: "cancellation-wakeup-worker",
leaseDurationMs: 30_000,
});
assert.isTrue(Option.isSome(unblocked));
if (Option.isSome(unblocked)) {
assert.equal(unblocked.value.request.type, "terminal.cleanup");
yield* outbox.succeed({
effectId: unblocked.value.id,
workerId: "cancellation-wakeup-worker",
});
}
}).pipe(Effect.provide(Layer.fresh(effectOutboxProvided))),
);
it.effect("executes a retry at its durable deadline instead of the liveness interval", () =>
Effect.gen(function* () {
const outbox = yield* EffectOutboxV2;
const effectId = "effect:foundation-durable-retry-deadline";
const commandId = CommandId.make("command:foundation-durable-retry-deadline");
const threadId = ThreadId.make("thread:foundation-durable-retry-deadline");
const executions = yield* Ref.make(0);
const completed = yield* Deferred.make<void>();
const executorLayer = Layer.succeed(
OrchestrationEffectExecutorV2,
OrchestrationEffectExecutorV2.of({
execute: () =>
Effect.gen(function* () {
const attempt = yield* Ref.updateAndGet(executions, (count) => count + 1);
if (attempt === 1) {
return yield* new OrchestrationEffectExecutionError({
effectId,
effectType: "terminal.cleanup",
cause: "simulated retry",
});
}
yield* Deferred.succeed(completed, undefined);
}),
}),
);
const workerLayer = effectWorkerLayerWithOptions({
workerId: "durable-retry-deadline-worker",
}).pipe(Layer.provide(Layer.merge(Layer.succeed(EffectOutboxV2, outbox), executorLayer)));
yield* Effect.gen(function* () {
yield* runEffectWorkerDaemonWithOptions({
concurrency: 1,
livenessPollIntervalMs: 30_000,
}).pipe(Effect.forkScoped);
yield* outbox.enqueue([
{
id: effectId,
commandId,
threadId,
request: { type: "terminal.cleanup" },
},
]);
yield* outbox.notifyAvailable();
let retryScheduled = false;
while (!retryScheduled) {
const effect = yield* outbox.get(effectId);
retryScheduled =
Option.isSome(effect) &&
effect.value.status === "pending" &&
effect.value.attemptCount === 1;
if (!retryScheduled) yield* Effect.yieldNow;
}
yield* TestClock.adjust("99 millis");
assert.equal(yield* Ref.get(executions), 1);
yield* TestClock.adjust("1 millis");
yield* Deferred.await(completed);
assert.equal(yield* Ref.get(executions), 2);
}).pipe(Effect.provide(workerLayer), Effect.scoped);
}).pipe(Effect.provide(TestClock.layer())),
);
it.effect("runs distinct threads concurrently while serializing effects within a thread", () =>
Effect.gen(function* () {
const outbox = yield* EffectOutboxV2;
@@ -957,6 +1217,7 @@ it.layer(TestLayer)("orchestration V2 foundation persistence", (it) => {
},
},
]);
yield* outbox.notifyAvailable(3);
yield* Effect.all([Deferred.await(startedA1), Deferred.await(startedB1)]);
assert.isFalse(yield* Deferred.isDone(startedA2));
@@ -1161,6 +1422,7 @@ it.layer(TestLayer)("orchestration V2 foundation persistence", (it) => {
OrchestrationEffectWorkerV2.of({
awaitWork: Effect.void,
runOnce: Effect.succeed(false),
nextClaimableAt: Effect.succeed(Option.none()),
drain: () => Effect.succeed(0),
}),
),
@@ -1359,6 +1621,7 @@ it.live("keeps claiming new work after repeated idle periods", () =>
request: { type: "terminal.cleanup" },
},
]);
yield* outbox.notifyAvailable();
const observed = yield* Deferred.await(completion).pipe(Effect.timeoutOption("2 seconds"));
assert.isTrue(Option.isSome(observed), `worker stopped before idle wave ${wave}`);
}