deltafold 0.0.1 → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "deltafold",
3
- "version": "0.0.1",
3
+ "version": "0.1.0",
4
4
  "description": "Model version history, resolve migration instructions between versions, and generate changelogs.",
5
5
  "keywords": [
6
6
  "changelog",
@@ -7,8 +7,10 @@ import {
7
7
  Effect,
8
8
  Equal,
9
9
  Exit,
10
+ Fiber,
10
11
  Layer,
11
12
  Option,
13
+ Scope,
12
14
  } from "effect";
13
15
 
14
16
  import type * as Action from "../../foundation/action.ts";
@@ -46,11 +48,12 @@ export type Outcome<E = unknown> =
46
48
  }
47
49
  /** Not started because execution stopped first. */
48
50
  | { readonly _tag: "Unattempted" }
51
+ /** `evaluated`: whether a prepare phase ran and decided to apply. */
49
52
  | { readonly _tag: "WouldExecute"; readonly evaluated: boolean }
50
53
  | { readonly _tag: "WouldSkip"; readonly reason: string }
51
54
  | { readonly _tag: "Undetermined"; readonly reason: string }
52
55
  | {
53
- readonly _tag: "PreconditionFailed";
56
+ readonly _tag: "PreparationFailed";
54
57
  readonly error: E | undefined;
55
58
  readonly cause: Cause.Cause<E>;
56
59
  };
@@ -77,7 +80,10 @@ export type Report<A extends Action.Any = Action.Any, E = unknown> = {
77
80
  readonly route: string;
78
81
  /** Every occurrence in plan order. */
79
82
  readonly occurrences: ReadonlyArray<OccurrenceReport<A, E>>;
80
- /** Whether any action body started. A started body may have partially changed state. */
83
+ /**
84
+ * Whether any apply phase started. A started apply phase may have partially changed
85
+ * state.
86
+ */
81
87
  readonly bodiesStarted: boolean;
82
88
  /** Progress is not persisted. Rerunning the plan repeats completed actions. */
83
89
  readonly persistence: "none";
@@ -106,10 +112,10 @@ export type CoverageIssue = {
106
112
  const HandlerCoverageBase = Data.TaggedError("HandlerCoverageError");
107
113
 
108
114
  /**
109
- * Handler coverage failed before any precondition or body ran. Every occurrence needs
110
- * exactly one handler, for the same action definition: the same identifier, kind, and
111
- * payload. For an occurrence that a rule produced, the issue names the rule and the
112
- * occurrences it replaced.
115
+ * Handler coverage failed before any handler phase ran. Every occurrence needs exactly
116
+ * one handler, for the same action definition: the same identifier, kind, and payload.
117
+ * For an occurrence that a rule produced, the issue names the rule and the occurrences
118
+ * it replaced.
113
119
  *
114
120
  * @since @next
115
121
  */
@@ -237,14 +243,15 @@ export type Requirements<H> = Handler.Services<H>;
237
243
  export type Options<H extends Handler.Any> = {
238
244
  readonly handlers?: ReadonlyArray<H>;
239
245
  /**
240
- * Evaluate preconditions without running any action body. A precondition that may
241
- * depend on an earlier action is reported `Undetermined`, because the dry run does not
242
- * apply that action.
246
+ * Run prepare phases without running any apply phase. A prepare phase that may
247
+ * depend on an earlier action is reported `Undetermined`, because the dry run does
248
+ * not apply that action.
243
249
  */
244
250
  readonly dryRun?: boolean;
245
251
  /**
246
- * Per-occurrence limit for a precondition or body. Exceeding it interrupts that action
247
- * and stops admitting new ones. It applies to dry-run preconditions too.
252
+ * Limit for each phase of an occurrence: the prepare phase and the apply phase each
253
+ * get the full limit. Exceeding it interrupts that action and stops admitting new
254
+ * ones. It applies to dry-run prepare phases too.
248
255
  */
249
256
  readonly timeout?: Duration.Input;
250
257
  /**
@@ -336,6 +343,19 @@ const failureOf = <E>(cause: Cause.Cause<E>) => ({
336
343
  cause,
337
344
  });
338
345
 
346
+ /** The exit an occurrence's scope closes with, so finalizers see how it ended. */
347
+ const exitOf = <E>(outcome: Outcome<E> | undefined): Exit.Exit<void, E> => {
348
+ switch (outcome?._tag) {
349
+ case "Failed":
350
+ case "PreparationFailed":
351
+ return Exit.failCause(outcome.cause);
352
+ case "Interrupted":
353
+ return Exit.interrupt();
354
+ default:
355
+ return Exit.void;
356
+ }
357
+ };
358
+
339
359
  const forEachBranch = <R>(
340
360
  branches: ReadonlyArray<Node>,
341
361
  concurrency: Action.Concurrency,
@@ -345,6 +365,12 @@ const forEachBranch = <R>(
345
365
  /** Registers a callback that cancels the execution. Only `runPromise` uses it. */
346
366
  type Subscribe = (cancel: () => void) => void;
347
367
 
368
+ /**
369
+ * Receives the fiber that closes an occurrence scope after an interrupted Promise
370
+ * settles, so the caller can keep the services it built open until then.
371
+ */
372
+ type Retain = (fiber: Fiber.Fiber<void>) => void;
373
+
348
374
  type StopReason = "failure" | InterruptReason;
349
375
 
350
376
  type PhaseResult<T, E> =
@@ -357,6 +383,13 @@ type PhaseResult<T, E> =
357
383
 
358
384
  type ControlOptions = Pick<Options<never>, "timeout" | "settleTimeout">;
359
385
 
386
+ /**
387
+ * Logs a cleanup failure that the report cannot carry, with the occurrence or the
388
+ * services layer that owned the resources.
389
+ */
390
+ const logCleanupFailure = (owner: Record<string, string>) => (cause: Cause.Cause<unknown>) =>
391
+ Effect.logError("deltafold: cleanup failed", cause).pipe(Effect.annotateLogs(owner));
392
+
360
393
  /** Admission state, cancellation, and timeouts shared by real and dry runs. */
361
394
  const makeControl = (options: ControlOptions, subscribe: Subscribe | undefined) =>
362
395
  Effect.gen(function* () {
@@ -372,17 +405,22 @@ const makeControl = (options: ControlOptions, subscribe: Subscribe | undefined)
372
405
  Deferred.doneUnsafe(cancelled, Exit.succeed("cancelled"));
373
406
  });
374
407
 
375
- /** Runs one precondition or body, racing it against cancellation and the timeout. */
408
+ /**
409
+ * Runs one phase, racing it against cancellation and its own timeout. An
410
+ * interrupted Promise that outlives the settlement grace period goes to `unsettled`.
411
+ */
376
412
  const runPhase = <T, E, R>(
377
413
  work: Effect.Effect<T, E, R>,
414
+ unsettled: Array<Promise<void>>,
378
415
  ): Effect.Effect<PhaseResult<T, E>, never, R> =>
379
416
  Effect.gen(function* () {
380
417
  let settled = true;
381
418
  const tracked = work.pipe(
382
419
  Effect.provideService(SettlementReference, {
383
420
  grace: settleTimeout,
384
- record: (value) => {
385
- settled = value;
421
+ unsettled: (promise) => {
422
+ settled = false;
423
+ unsettled.push(promise);
386
424
  },
387
425
  }),
388
426
  );
@@ -410,6 +448,45 @@ const makeControl = (options: ControlOptions, subscribe: Subscribe | undefined)
410
448
  return { halt, stop, runPhase };
411
449
  });
412
450
 
451
+ /**
452
+ * Runs one occurrence in its own scope, which both phases share. `use` returns the
453
+ * exit to close the scope with. The scope closes as soon as the occurrence ends, and
454
+ * a failing finalizer goes to `onCleanupFailure`. If an interrupted Promise has not
455
+ * settled, the scope stays open until it does, possibly forever; a failing
456
+ * finalizer is then logged, because the report may already have been returned.
457
+ */
458
+ const inScope = <E, R>(
459
+ retain: Retain,
460
+ occurrenceId: string,
461
+ use: (
462
+ scope: Scope.Scope,
463
+ unsettled: Array<Promise<void>>,
464
+ ) => Effect.Effect<Exit.Exit<void, E>, never, R>,
465
+ onCleanupFailure: (cause: Cause.Cause<never>) => Effect.Effect<void>,
466
+ ): Effect.Effect<void, never, R> =>
467
+ Effect.uninterruptibleMask((restore) =>
468
+ Effect.gen(function* () {
469
+ const scope = yield* Scope.make();
470
+ const unsettled: Array<Promise<void>> = [];
471
+ const used = yield* Effect.exit(restore(use(scope, unsettled)));
472
+ const end = Exit.isSuccess(used) ? used.value : used;
473
+ if (unsettled.length > 0) {
474
+ const fiber = yield* Effect.forkDetach(
475
+ Effect.promise(() => Promise.all(unsettled)).pipe(
476
+ Effect.andThen(Scope.close(scope, end)),
477
+ Effect.catchCause(logCleanupFailure({ occurrence: occurrenceId })),
478
+ ),
479
+ );
480
+ retain(fiber);
481
+ } else {
482
+ const closed = yield* Effect.exit(Scope.close(scope, end));
483
+ if (Exit.isFailure(closed)) yield* onCleanupFailure(closed.cause);
484
+ }
485
+
486
+ return yield* used;
487
+ }),
488
+ ).pipe(Effect.asVoid);
489
+
413
490
  const interrupted = <A extends Action.Any, E>(
414
491
  plan: Plan.Plan<A, Plan.Coverage>,
415
492
  mode: Report["mode"],
@@ -422,108 +499,119 @@ const interrupted = <A extends Action.Any, E>(
422
499
  report: report(plan, mode, "interrupted", outcomes, bodiesStarted),
423
500
  });
424
501
 
502
+ /**
503
+ * The outcome of a phase that did not succeed. `undefined` when it succeeded. An Effect
504
+ * handler that interrupted itself stops admission.
505
+ */
506
+ const unsuccessful = <T, E>(
507
+ phase: Handler.Phase,
508
+ result: PhaseResult<T, E>,
509
+ stop: (reason: StopReason) => void,
510
+ ): Outcome<E> | undefined => {
511
+ if (result._tag === "Interrupted") {
512
+ return {
513
+ _tag: "Interrupted",
514
+ phase,
515
+ reason: result.reason,
516
+ settled: result.settled,
517
+ };
518
+ }
519
+ if (Exit.isFailure(result.exit) && Cause.hasInterruptsOnly(result.exit.cause)) {
520
+ stop("handler");
521
+
522
+ return { _tag: "Interrupted", phase, reason: "handler", settled: true };
523
+ }
524
+
525
+ return undefined;
526
+ };
527
+
425
528
  const execute = <A extends Action.Any, E, R>(
426
529
  plan: Plan.Plan<A, Plan.Coverage>,
427
530
  resolved: Resolved<E, R>,
428
531
  options: ControlOptions,
429
532
  subscribe: Subscribe | undefined,
533
+ retain: Retain,
430
534
  ): Effect.Effect<Report<A, E>, ExecutionFailed<A, E> | ExecutionInterrupted<A, E>, R> =>
431
535
  Effect.gen(function* () {
432
536
  const outcomes = new Map<string, Outcome<E>>();
433
537
  const { halt, stop, runPhase } = yield* makeControl(options, subscribe);
434
538
  let bodiesStarted = false;
435
539
 
436
- const runOccurrence = (occurrence: Occurrence) =>
437
- Effect.gen(function* () {
438
- if (halt.reason !== undefined) return;
439
-
440
- const handler = resolved.get(occurrence.id);
441
- if (handler === undefined) return;
442
-
443
- if (handler.precondition !== undefined) {
444
- const checked = yield* runPhase(handler.precondition);
445
- if (checked._tag === "Interrupted") {
446
- outcomes.set(occurrence.id, {
447
- _tag: "Interrupted",
448
- phase: "precondition",
449
- reason: checked.reason,
450
- settled: checked.settled,
451
- });
452
-
453
- return;
540
+ const runOccurrence = (occurrence: Occurrence) => {
541
+ if (halt.reason !== undefined) return Effect.void;
542
+
543
+ const handler = resolved.get(occurrence.id);
544
+ if (handler === undefined) return Effect.void;
545
+
546
+ let phase: Handler.Phase = "prepare";
547
+ const end = (outcome: Outcome<E>) => {
548
+ outcomes.set(occurrence.id, outcome);
549
+
550
+ return exitOf(outcome);
551
+ };
552
+ const fail = (cause: Cause.Cause<E>) => {
553
+ stop("failure");
554
+
555
+ return end({ _tag: "Failed", phase, ...failureOf(cause) });
556
+ };
557
+
558
+ const use = (scope: Scope.Scope, unsettled: Array<Promise<void>>) =>
559
+ Effect.gen(function* () {
560
+ let step: Handler.Step<E, R>;
561
+ if (handler.prepares) {
562
+ const preparation = yield* runPhase(handler.prepare(scope), unsettled);
563
+ const stopped = unsuccessful("prepare", preparation, stop);
564
+ if (stopped !== undefined) return end(stopped);
565
+ if (preparation._tag !== "Done") return Exit.void;
566
+ if (Exit.isFailure(preparation.exit)) return fail(preparation.exit.cause);
567
+ step = preparation.exit.value;
568
+ // The occurrence has started, so a sibling failure or timeout lets it
569
+ // finish. Cancellation that arrived while preparing keeps it from
570
+ // applying, and the prepared value is discarded.
571
+ if (step._tag === "Apply" && halt.reason === "cancelled") return Exit.void;
572
+ } else {
573
+ const started = yield* Effect.exit(handler.prepare(scope));
574
+ if (Exit.isFailure(started)) return fail(started.cause);
575
+ step = started.value;
454
576
  }
455
- if (
456
- Exit.isFailure(checked.exit) &&
457
- Cause.hasInterruptsOnly(checked.exit.cause)
458
- ) {
459
- stop("handler");
460
- outcomes.set(occurrence.id, {
461
- _tag: "Interrupted",
462
- phase: "precondition",
463
- reason: "handler",
464
- settled: true,
465
- });
466
-
467
- return;
468
- }
469
- if (Exit.isFailure(checked.exit)) {
470
- stop("failure");
471
- outcomes.set(occurrence.id, {
472
- _tag: "Failed",
473
- phase: "precondition",
474
- ...failureOf(checked.exit.cause),
475
- });
476
-
477
- return;
577
+ if (step._tag === "Skip") return end({ _tag: "Skipped", reason: step.reason });
578
+
579
+ phase = "apply";
580
+ bodiesStarted = true;
581
+ const applied = yield* runPhase(step.apply, unsettled);
582
+ const stopped = unsuccessful("apply", applied, stop);
583
+ if (stopped !== undefined) return end(stopped);
584
+ if (applied._tag !== "Done") return Exit.void;
585
+ if (Exit.isFailure(applied.exit)) return fail(applied.exit.cause);
586
+
587
+ return end({ _tag: "Completed" });
588
+ });
589
+
590
+ // A finalizer that fails before the report is part of the execution: it fails an
591
+ // occurrence that otherwise ended normally. An interrupted occurrence keeps its
592
+ // outcome, and the failure is logged.
593
+ const onCleanupFailure = (cause: Cause.Cause<never>) =>
594
+ Effect.suspend(() => {
595
+ const outcome = outcomes.get(occurrence.id);
596
+ if (outcome?._tag === "Interrupted") {
597
+ return logCleanupFailure({ occurrence: occurrence.id })(cause);
478
598
  }
479
- if (!checked.exit.value) {
480
- outcomes.set(occurrence.id, {
481
- _tag: "Skipped",
482
- reason: handler.skipReason,
483
- });
484
-
485
- return;
486
- }
487
- // The occurrence has started, so a sibling failure lets it finish.
488
- // Cancellation that arrived during the precondition keeps the body from starting.
489
- if (halt.reason === "cancelled") return;
490
- }
491
-
492
- bodiesStarted = true;
493
- const ran = yield* runPhase(handler.body);
494
- if (ran._tag === "Interrupted") {
495
- outcomes.set(occurrence.id, {
496
- _tag: "Interrupted",
497
- phase: "body",
498
- reason: ran.reason,
499
- settled: ran.settled,
500
- });
501
-
502
- return;
503
- }
504
- if (Exit.isFailure(ran.exit) && Cause.hasInterruptsOnly(ran.exit.cause)) {
505
- stop("handler");
506
- outcomes.set(occurrence.id, {
507
- _tag: "Interrupted",
508
- phase: "body",
509
- reason: "handler",
510
- settled: true,
511
- });
512
-
513
- return;
514
- }
515
- if (Exit.isFailure(ran.exit)) {
516
599
  stop("failure");
517
600
  outcomes.set(occurrence.id, {
518
601
  _tag: "Failed",
519
- phase: "body",
520
- ...failureOf(ran.exit.cause),
602
+ phase,
603
+ ...failureOf(
604
+ outcome?._tag === "Failed"
605
+ ? Cause.combine(outcome.cause, cause)
606
+ : cause,
607
+ ),
521
608
  });
522
609
 
523
- return;
524
- }
525
- outcomes.set(occurrence.id, { _tag: "Completed" });
526
- });
610
+ return Effect.void;
611
+ });
612
+
613
+ return inScope(retain, occurrence.id, use, onCleanupFailure);
614
+ };
527
615
 
528
616
  const runNode = (node: Node): Effect.Effect<void, never, R> => {
529
617
  switch (node._tag) {
@@ -562,12 +650,65 @@ const dryRun = <A extends Action.Any, E, R>(
562
650
  resolved: Resolved<E, R>,
563
651
  options: ControlOptions,
564
652
  subscribe: Subscribe | undefined,
653
+ retain: Retain,
565
654
  ): Effect.Effect<Report<A, E>, ExecutionInterrupted<A, E>, R> =>
566
655
  Effect.gen(function* () {
567
656
  const outcomes = new Map<string, Outcome<E>>();
568
657
  const { halt, stop, runPhase } = yield* makeControl(options, subscribe);
569
658
  let failedAt: string | undefined;
570
659
 
660
+ /** Runs a prepare phase in the occurrence's scope and records what it predicts. */
661
+ const prepare = (id: string, handler: Internal<E, R>) => {
662
+ const end = (outcome: Outcome<E>) => {
663
+ outcomes.set(id, outcome);
664
+
665
+ return exitOf(outcome);
666
+ };
667
+ const use = (scope: Scope.Scope, unsettled: Array<Promise<void>>) =>
668
+ Effect.gen(function* () {
669
+ const preparation = yield* runPhase(handler.prepare(scope), unsettled);
670
+ const stopped = unsuccessful("prepare", preparation, stop);
671
+ if (stopped !== undefined) return end(stopped);
672
+ if (preparation._tag !== "Done") return Exit.void;
673
+ if (Exit.isFailure(preparation.exit)) {
674
+ failedAt = id;
675
+
676
+ return end({
677
+ _tag: "PreparationFailed",
678
+ ...failureOf(preparation.exit.cause),
679
+ });
680
+ }
681
+ // A dry run never applies: the prepared value is discarded.
682
+ const step = preparation.exit.value;
683
+
684
+ return end(
685
+ step._tag === "Skip"
686
+ ? { _tag: "WouldSkip", reason: step.reason }
687
+ : { _tag: "WouldExecute", evaluated: true },
688
+ );
689
+ });
690
+ const onCleanupFailure = (cause: Cause.Cause<never>) =>
691
+ Effect.suspend(() => {
692
+ const outcome = outcomes.get(id);
693
+ if (outcome?._tag === "Interrupted") {
694
+ return logCleanupFailure({ occurrence: id })(cause);
695
+ }
696
+ failedAt ??= id;
697
+ outcomes.set(id, {
698
+ _tag: "PreparationFailed",
699
+ ...failureOf(
700
+ outcome?._tag === "PreparationFailed"
701
+ ? Cause.combine(outcome.cause, cause)
702
+ : cause,
703
+ ),
704
+ });
705
+
706
+ return Effect.void;
707
+ });
708
+
709
+ return inScope(retain, id, use, onCleanupFailure);
710
+ };
711
+
571
712
  /** Returns whether the node would or might change state. */
572
713
  const visit = (node: Node, dirty: boolean): Effect.Effect<boolean, never, R> =>
573
714
  Effect.gen(function* () {
@@ -592,12 +733,12 @@ const dryRun = <A extends Action.Any, E, R>(
592
733
  if (failedAt !== undefined) {
593
734
  outcomes.set(node.id, {
594
735
  _tag: "Undetermined",
595
- reason: `Execution would stop at the failed precondition of "${failedAt}".`,
736
+ reason: `Execution would stop at the failed preparation of "${failedAt}".`,
596
737
  });
597
738
 
598
739
  return true;
599
740
  }
600
- if (handler.precondition === undefined) {
741
+ if (!handler.prepares) {
601
742
  outcomes.set(node.id, { _tag: "WouldExecute", evaluated: false });
602
743
 
603
744
  return true;
@@ -605,51 +746,15 @@ const dryRun = <A extends Action.Any, E, R>(
605
746
  if (dirty) {
606
747
  outcomes.set(node.id, {
607
748
  _tag: "Undetermined",
608
- reason: "The precondition depends on earlier actions that a dry run does not apply.",
749
+ reason: "The prepare phase depends on earlier actions that a dry run does not apply.",
609
750
  });
610
751
 
611
752
  return true;
612
753
  }
613
754
 
614
- const checked = yield* runPhase(handler.precondition);
615
- if (checked._tag === "Interrupted") {
616
- outcomes.set(node.id, {
617
- _tag: "Interrupted",
618
- phase: "precondition",
619
- reason: checked.reason,
620
- settled: checked.settled,
621
- });
622
-
623
- return true;
624
- }
625
- if (Exit.isFailure(checked.exit) && Cause.hasInterruptsOnly(checked.exit.cause)) {
626
- stop("handler");
627
- outcomes.set(node.id, {
628
- _tag: "Interrupted",
629
- phase: "precondition",
630
- reason: "handler",
631
- settled: true,
632
- });
755
+ yield* prepare(node.id, handler);
633
756
 
634
- return true;
635
- }
636
- if (Exit.isFailure(checked.exit)) {
637
- failedAt = node.id;
638
- outcomes.set(node.id, {
639
- _tag: "PreconditionFailed",
640
- ...failureOf(checked.exit.cause),
641
- });
642
-
643
- return true;
644
- }
645
- if (!checked.exit.value) {
646
- outcomes.set(node.id, { _tag: "WouldSkip", reason: handler.skipReason });
647
-
648
- return false;
649
- }
650
- outcomes.set(node.id, { _tag: "WouldExecute", evaluated: true });
651
-
652
- return true;
757
+ return outcomes.get(node.id)?._tag !== "WouldSkip";
653
758
  });
654
759
 
655
760
  // Later migrations conservatively depend on every earlier migration.
@@ -673,6 +778,7 @@ const run = <A extends Action.Any, C extends Plan.Coverage, H extends Handler.An
673
778
  plan: Plan.Plan<A, C>,
674
779
  options: Options<H>,
675
780
  subscribe: Subscribe | undefined,
781
+ retain: Retain,
676
782
  ): Effect.Effect<Report<A, Errors<H>>, ExecutionError<A, Errors<H>>, Requirements<H>> => {
677
783
  // Handlers are covariant in their errors and services, and `Errors<H>` and
678
784
  // `Requirements<H>` collect them from each handler in `H`, so every handler fits this
@@ -695,16 +801,21 @@ const run = <A extends Action.Any, C extends Plan.Coverage, H extends Handler.An
695
801
  }
696
802
 
697
803
  return options.dryRun === true
698
- ? yield* dryRun(plan, checked.resolved, options, subscribe)
699
- : yield* execute(plan, checked.resolved, options, subscribe);
804
+ ? yield* dryRun(plan, checked.resolved, options, subscribe, retain)
805
+ : yield* execute(plan, checked.resolved, options, subscribe, retain);
700
806
  });
701
807
  };
702
808
 
703
809
  /**
704
- * Runs a plan as an Effect. Coverage is checked before any precondition or body runs.
705
- * Steps are sequential barriers; parallel groups run their branches concurrently. On
706
- * failure, no new action starts, and actions already running settle before the effect
707
- * fails with the partial report.
810
+ * Runs a plan as an Effect. Coverage is checked before any handler phase runs. Steps
811
+ * are sequential barriers; parallel groups run their branches concurrently. On failure,
812
+ * no new action starts, and actions already running settle before the effect fails
813
+ * with the partial report.
814
+ *
815
+ * Each occurrence has its own scope, shared by its phases and closed when it ends. An
816
+ * interrupted Promise that has not settled keeps its occurrence's scope open until it
817
+ * settles, after the effect has ended. Services that the caller provides stay the
818
+ * caller's to release.
708
819
  *
709
820
  * To cancel, interrupt the fiber. Interruption reaches running actions and aborts the
710
821
  * signal passed to Promise callbacks. The effect then ends as interrupted, without a
@@ -720,7 +831,7 @@ export const effect = <
720
831
  plan: Plan.Plan<A, C>,
721
832
  options: Options<H> & CoverageCheck<A, H, C>,
722
833
  ): Effect.Effect<Report<A, Errors<H>>, ExecutionError<A, Errors<H>>, Requirements<H>> =>
723
- run(plan, options, undefined);
834
+ run(plan, options, undefined, () => {});
724
835
 
725
836
  type ServicesOption<R, LE> = [R] extends [never]
726
837
  ? {
@@ -747,10 +858,12 @@ export type PromiseOptions<H extends Handler.Any> = Options<H> & {
747
858
  * Building a supplied services layer can also reject with the layer's own error,
748
859
  * without a report.
749
860
  *
750
- * A services layer is built for this run and finalized when the run ends. A services
751
- * context stays owned by the caller. A Promise callback that ignores its signal can keep
752
- * running after cancellation or a timeout, beyond `settleTimeout`, and so after the
753
- * run's layer resources are finalized; the report marks it as possibly still running.
861
+ * A services layer is built for this run. A services context stays owned by the
862
+ * caller. A Promise callback that ignores its signal can keep running after
863
+ * cancellation or a timeout, beyond `settleTimeout`; the report marks it as possibly
864
+ * still running. Its occurrence's scope and the run's services layer then stay open
865
+ * until it settles, possibly forever, and close in that order. A cleanup failure after
866
+ * the Promise resolved is logged through Effect.
754
867
  *
755
868
  * @since @next
756
869
  */
@@ -793,16 +906,45 @@ export const runPromise = <
793
906
  cancelRun = cancel;
794
907
  if (signal.aborted) cancel();
795
908
  };
796
- const program = run(plan, options, subscribe);
909
+ const retained: Array<Fiber.Fiber<void>> = [];
910
+ const program = run(plan, options, subscribe, (fiber) => retained.push(fiber));
797
911
  const services: Context.Context<never> | Layer.Layer<never, LE> | undefined = options.services;
798
912
  const provided =
799
913
  services === undefined
800
914
  ? program
801
915
  : Context.isContext(services)
802
916
  ? Effect.provideContext(program, services)
803
- : // runPromise is the entry point: the caller's layer is built for this one run.
804
- // oxlint-disable-next-line effecttsgo/strict-effect-provide
805
- Effect.provide(program, services);
917
+ : // runPromise is the entry point: the caller's layer is built for this one run,
918
+ // in a scope that outlives the run while retained occurrence scopes are open.
919
+ Effect.uninterruptibleMask((restore) =>
920
+ Effect.gen(function* () {
921
+ const scope = yield* Scope.make();
922
+ const built = yield* Effect.exit(
923
+ restore(Layer.buildWithScope(services, scope)),
924
+ );
925
+ if (Exit.isFailure(built)) {
926
+ yield* Scope.close(scope, built);
927
+
928
+ return yield* built;
929
+ }
930
+ const exit = yield* Effect.exit(
931
+ restore(Effect.provideContext(program, built.value)),
932
+ );
933
+ if (retained.length === 0) yield* Scope.close(scope, exit);
934
+ else {
935
+ yield* Effect.forkDetach(
936
+ Fiber.awaitAll(retained).pipe(
937
+ Effect.andThen(Scope.close(scope, exit)),
938
+ Effect.catchCause(
939
+ logCleanupFailure({ owner: "services layer" }),
940
+ ),
941
+ ),
942
+ );
943
+ }
944
+
945
+ return yield* exit;
946
+ }),
947
+ );
806
948
  const cancellable =
807
949
  signal === undefined
808
950
  ? provided