import { assert, describe, it } from "@effect/vitest"; import type { AttemptId } from "@usine/core/attempt"; import { InfraFailure } from "@usine/core/attempt/failure"; import { StepCompletion } from "@usine/core/step/result"; import { LoopName } from "@usine/core/loop"; import { WorkerName } from "@usine/core/worker"; import { Context, Deferred, Effect, Exit, Layer, Option, Ref, Result, Schedule, Scope, TxRef, } from "effect"; import { RunEngine, Submission } from "../src/engine/engine.ts"; import { LoopControl } from "../src/loop-control/loop-control.ts"; import { StepExecutor } from "../src/step-executor.ts"; import { type AttemptPlan, engineLayer, slottedExecutor, stepResult, submission, waitFor, withInstance, } from "./support.ts"; const otherLoop = LoopName.make("other"); /** Returns a one-slot executor over `plans` that counts its `reserve` calls in `reserves`. */ const countingExecutor = Effect.fn("test.countingExecutor")(function* ( plans: ReadonlyArray, ) { const worker = yield* slottedExecutor(plans); const reserves = yield* Ref.make(0); const executor = Layer.effect( StepExecutor, Effect.gen(function* () { const scripted = yield* StepExecutor; return StepExecutor.of({ ...scripted, reserve: (...args) => Ref.update(reserves, (count) => count + 1).pipe( Effect.andThen(scripted.reserve(...args)), ), }); }), ).pipe(Layer.provide(worker.executor)); return { ...worker, reserves, executor }; }); /** Returns an executor on Worker `local` whose parent tasks the test scripts. */ const parentExecutor = (parents: Pick) => Layer.succeed(StepExecutor)({ workers: Effect.succeed([WorkerName.make("local")]), recover: () => Effect.succeed("found" as const), intervene: () => Effect.void, interrupt: () => Effect.void, occupy: (worker) => Effect.succeed({ worker, kind: "local", release: Effect.void }), sweep: Effect.void, discard: () => Effect.void, reserve: () => Effect.succeed({ worker: WorkerName.make("local"), kind: "local", release: Effect.void }), ...parents, }); /** Builds the engine on `runtime` in a new scope that the caller closes. */ const start = Effect.fn("test.start")(function* (runtime: ReturnType) { const scope = yield* Scope.make(); const services = yield* Scope.provide(Layer.build(runtime), scope); return { scope, engine: Context.get(services, RunEngine), controls: Context.get(services, LoopControl), }; }); const until = (read: Effect.Effect, done: (value: A) => boolean) => Effect.repeat(read, { until: done, schedule: Schedule.spaced("10 millis"), times: 500 }); describe("loop pause", () => { it.live( "holds a Run queued for a worker when its Loop pauses and a slot frees, and starts it after the unpause", () => withInstance((directory) => Effect.gen(function* () { const gate = yield* Deferred.make(); const worker = yield* countingExecutor([ Deferred.await(gate).pipe(Effect.as(stepResult("running before the pause"))), Effect.succeed(stepResult("held until the unpause")), ]); yield* Effect.gen(function* () { const engine = yield* RunEngine; const controls = yield* LoopControl; const running = yield* engine.submit(submission({ number: 1, item: "running" })); assert(running._tag === "Claimed"); yield* waitFor(engine, running.runId, ({ attempts }) => attempts.length === 1); const queued = yield* engine.submit(submission({ number: 2, item: "queued" })); assert(queued._tag === "Claimed"); // The queued Run waits for the only slot. yield* until(Ref.get(worker.reserves), (count) => count === 2); yield* controls.pause(submission({ number: 2 }).loop); yield* Deferred.succeed(gate, undefined); // The running Attempt finishes, and the queued Run gives back the slot it got. yield* waitFor(engine, running.runId, ({ run }) => run.state._tag === "Succeeded"); yield* until(TxRef.get(worker.leased), (count) => count === 0); yield* Effect.sleep("100 millis"); const waiting = yield* engine.inspect(queued.runId); const leased = yield* TxRef.get(worker.leased); const reserves = yield* Ref.get(worker.reserves); assert.isEmpty(waiting.attempts); assert.strictEqual(leased, 0); assert.strictEqual(reserves, 2, "the held Run reserves no slot again"); yield* controls.unpause(submission({ number: 2 }).loop); const started = yield* waitFor( engine, queued.runId, ({ run }) => run.state._tag === "Succeeded", ); assert.lengthOf(started.attempts, 1); }).pipe(Effect.provide(engineLayer(directory, worker.executor))); }), ), ); it.live( "holds a Run of a paused Loop before it reserves a slot, starts a Run of another Loop meanwhile, and starts the held Run after the unpause", () => withInstance((directory) => Effect.gen(function* () { const worker = yield* countingExecutor([ Effect.succeed(stepResult("runs while the other Loop is paused")), Effect.succeed(stepResult("held until the unpause")), ]); yield* Effect.gen(function* () { const engine = yield* RunEngine; const controls = yield* LoopControl; const held = submission({ number: 3, item: "held" }); yield* controls.pause(held.loop); const accepted = yield* engine.submit(held); assert(accepted._tag === "Claimed"); const other = yield* engine.submit( Submission.make({ ...submission({ number: 4, item: "other" }), loop: otherLoop }), ); assert(other._tag === "Claimed"); // Only the Run of the paused Loop is held. const ran = yield* waitFor( engine, other.runId, ({ run }) => run.state._tag === "Succeeded", ); assert.lengthOf(ran.attempts, 1); yield* Effect.sleep("100 millis"); const waiting = yield* engine.inspect(accepted.runId); const reserves = yield* Ref.get(worker.reserves); assert.isEmpty(waiting.attempts); assert.strictEqual(reserves, 1, "only the Run of the unpaused Loop reserves a slot"); yield* controls.unpause(held.loop); yield* waitFor(engine, accepted.runId, ({ run }) => run.state._tag === "Succeeded"); const after = yield* Ref.get(worker.reserves); assert.strictEqual(after, 2); }).pipe(Effect.provide(engineLayer(directory, worker.executor))); }), ), ); it.live( "holds a Run waiting to retry a failed Attempt while its Loop is paused, and retries it after the unpause", () => withInstance((directory) => Effect.gen(function* () { const gate = yield* Deferred.make(); const worker = yield* countingExecutor([ Deferred.await(gate).pipe( Effect.andThen( Effect.fail(InfraFailure.make({ message: "Lost the parent task", cause: "test" })), ), ), Effect.succeed(stepResult("retried after the unpause")), ]); yield* Effect.gen(function* () { const engine = yield* RunEngine; const controls = yield* LoopControl; const retried = submission({ number: 5, item: "retried" }); const accepted = yield* engine.submit(retried); assert(accepted._tag === "Claimed"); yield* waitFor(engine, accepted.runId, ({ attempts }) => attempts.length === 1); yield* controls.pause(retried.loop); yield* Deferred.succeed(gate, undefined); yield* waitFor(engine, accepted.runId, ({ attempts }) => attempts.every(({ outcome }) => Option.isSome(outcome)), ); yield* until(TxRef.get(worker.leased), (count) => count === 0); yield* Effect.sleep("100 millis"); const waiting = yield* engine.inspect(accepted.runId); const reserves = yield* Ref.get(worker.reserves); assert.strictEqual(waiting.run.state._tag, "Running"); assert.lengthOf(waiting.attempts, 1); assert.strictEqual(reserves, 1, "the held retry reserves no slot"); yield* controls.unpause(retried.loop); const finished = yield* waitFor( engine, accepted.runId, ({ run }) => run.state._tag === "Succeeded", ); assert.lengthOf(finished.attempts, 2); }).pipe(Effect.provide(engineLayer(directory, worker.executor))); }), ), ); it.live( "reattaches an Attempt whose parent task outlived a restart while its Loop is paused, and records its result", () => withInstance((directory) => Effect.gen(function* () { const executions = yield* Ref.make>([]); const live = yield* Ref.make>(new Set()); const runtime = engineLayer( directory, parentExecutor({ isLive: (attemptId) => Ref.get(live).pipe(Effect.map((ids) => ids.has(attemptId))), outcome: () => Effect.succeedNone, // The first parent task outlives the restart; the reattached one then finishes. execute: (execution) => Ref.updateAndGet(executions, (seen) => [ ...seen, [execution.attempt.id, execution.reattach] as const, ]).pipe( Effect.flatMap((seen) => seen.length === 1 ? Ref.update(live, (ids) => new Set([...ids, execution.attempt.id])).pipe( Effect.andThen(Effect.never), ) : Effect.succeed( StepCompletion.fromResult( stepResult("finished by the reattached parent"), ), ), ), ), }), ); const running = submission({ number: 6, item: "reattached" }); const before = yield* start(runtime); const accepted = yield* before.engine.submit(running); assert(accepted._tag === "Claimed"); yield* until(Ref.get(executions), (seen) => seen.length === 1); yield* before.controls.pause(running.loop); yield* Scope.close(before.scope, Exit.void); const after = yield* start(runtime); const finished = yield* waitFor( after.engine, accepted.runId, ({ run }) => run.state._tag === "Succeeded", ); const paused = yield* after.controls.isPaused(running.loop); const seen = yield* Ref.get(executions); const [attempt] = finished.attempts; assert(attempt !== undefined && finished.attempts.length === 1); assert.isTrue(paused); assert.deepStrictEqual(seen, [ [attempt.id, false], [attempt.id, true], ]); yield* Scope.close(after.scope, Exit.void); }), ), ); it.live( "records the stored result of an Attempt whose parent task finished before a restart while its Loop is paused", () => withInstance((directory) => Effect.gen(function* () { const executions = yield* Ref.make(0); const stored = yield* Ref.make< ReadonlyMap> >(new Map()); const runtime = engineLayer( directory, parentExecutor({ isLive: () => Effect.succeed(false), outcome: (attemptId) => Ref.get(stored).pipe( Effect.map((results) => Option.fromUndefinedOr(results.get(attemptId))), ), // The parent stores its result, then the process stops before the Run records it. execute: (execution) => Ref.update(executions, (count) => count + 1).pipe( Effect.andThen( Ref.update(stored, (results) => new Map(results).set( execution.attempt.id, Result.succeed( StepCompletion.fromResult(stepResult("finished before the restart")), ), ), ), ), Effect.andThen(Effect.never), ), }), ); const finishing = submission({ number: 7, item: "stored" }); const before = yield* start(runtime); const accepted = yield* before.engine.submit(finishing); assert(accepted._tag === "Claimed"); yield* until(Ref.get(stored), (results) => results.size === 1); yield* before.controls.pause(finishing.loop); yield* Scope.close(before.scope, Exit.void); const after = yield* start(runtime); const finished = yield* waitFor( after.engine, accepted.runId, ({ run }) => run.state._tag === "Succeeded", ); const paused = yield* after.controls.isPaused(finishing.loop); const started = yield* Ref.get(executions); assert.isTrue(paused); assert.lengthOf(finished.attempts, 1); assert.strictEqual(started, 1, "no new Attempt starts"); yield* Scope.close(after.scope, Exit.void); }), ), ); it.live( "fails an Attempt that a restart interrupted while its Loop is paused, holds the Run, and starts it again after the unpause", () => withInstance((directory) => Effect.gen(function* () { const executions = yield* Ref.make(0); const runtime = engineLayer( directory, parentExecutor({ // The first parent task doesn't survive the restart and stores no result. isLive: () => Effect.succeed(false), outcome: () => Effect.succeedNone, execute: () => Ref.updateAndGet(executions, (count) => count + 1).pipe( Effect.flatMap((count) => count === 1 ? Effect.never : Effect.succeed( StepCompletion.fromResult(stepResult("started again after the unpause")), ), ), ), }), ); const interrupted = submission({ number: 8, item: "interrupted" }); const before = yield* start(runtime); const accepted = yield* before.engine.submit(interrupted); assert(accepted._tag === "Claimed"); yield* until(Ref.get(executions), (count) => count === 1); yield* before.controls.pause(interrupted.loop); yield* Scope.close(before.scope, Exit.void); const after = yield* start(runtime); // The Run shows no running Attempt while it is held. const held = yield* waitFor(after.engine, accepted.runId, ({ attempts }) => attempts.every(({ outcome }) => Option.isSome(outcome)), ); yield* Effect.sleep("100 millis"); const waiting = yield* after.engine.inspect(accepted.runId); const [failed] = held.attempts; assert(failed !== undefined && held.attempts.length === 1); assert(Option.isSome(failed.outcome) && failed.outcome.value._tag === "Failed"); assert.strictEqual(failed.outcome.value.failure._tag, "InfraFailure"); assert.strictEqual(waiting.run.state._tag, "Running"); assert.lengthOf(waiting.attempts, 1, "no Attempt starts while the Loop is paused"); const started = yield* Ref.get(executions); assert.strictEqual(started, 1); yield* after.controls.unpause(interrupted.loop); const finished = yield* waitFor( after.engine, accepted.runId, ({ run }) => run.state._tag === "Succeeded", ); const restarted = finished.attempts[1]; assert(restarted !== undefined && finished.attempts.length === 2); assert.deepStrictEqual( Option.map(restarted.start, ({ _tag }) => _tag), Option.some("AfterRestart"), ); yield* Scope.close(after.scope, Exit.void); }), ), ); });