diff --git a/lib/src/core/cache.dart b/lib/src/core/cache.dart index ead4f17..3880029 100644 --- a/lib/src/core/cache.dart +++ b/lib/src/core/cache.dart @@ -196,7 +196,7 @@ final class Cache { .map((fiber) { entry.fiber = fiber; if (entry.cancelling) fiber.requestCancel(reason: entry.stopReason); - listenFiber(fiber, (exit) { + fiber.onExit((exit) { _finish(entry, TaskEvaluation(exit, fiberFailureEvents(fiber))); }); }) @@ -225,7 +225,7 @@ final class Cache { ExitFailure(:final cause) => Cause.combine([cause, defect]), _ => defect, }), - [...result.events, FailureEvent(defect, Object())], + [...result.events, FailureEvent(defect, FailureSource())], ); keep = false; } @@ -319,7 +319,10 @@ final class Cache { cleanup.isEmpty ? const Exit.success(null) : Exit.failure(Cause.combine(cleanup)), - result.events, + [ + for (final event in result.events) + if (event.cause is CauseDefect) event, + ], ), ); }); diff --git a/lib/src/core/fiber.dart b/lib/src/core/fiber.dart index e3d08fb..903be74 100644 --- a/lib/src/core/fiber.dart +++ b/lib/src/core/fiber.dart @@ -4,6 +4,7 @@ import 'cancellation.dart'; import 'cause.dart'; import 'context.dart'; import 'exit.dart'; +import 'internal/completion.dart'; import 'internal/execution_mode.dart'; import 'option.dart'; import 'scope.dart'; @@ -25,45 +26,55 @@ import 'task_local.dart'; /// more than once. Cancelling a waiter leaves the fiber running; use [cancel] to /// stop it and wait, or [requestCancel] to request cancellation without waiting. final class Fiber { - Fiber._(this._scope, this._report); + Fiber._(this._scope, this._report, this._reportFailure); final Scope _scope; final void Function(Cause) _report; final _controller = CancellationController(); - final _completion = Completer>(); - final _listeners = )>{}; + final _completion = Completion>(); final _zone = Zone.current; late final List _finalEvents; late final List _cleanupCancellations; - Exit? _exit; + Exit? get _exit => _completion.value; var _active = true; - var _observed = false; - var _pendingObservations = 0; - var _reportReady = false; - var _defectsHandledByOwner = false; + bool _reportFailure; + var _cleanupOwned = false; /// Returns the completed exit, or [OptionNone] if the fiber is still running. /// - /// A fiber remains running until its cleanup finishes. Returning [OptionSome] - /// counts as observing the result for unhandled-failure reporting. - Option> poll() { - final exit = _exit; - if (exit == null) return const Option.none(); - _observed = true; - return Option.some(exit); - } + /// Completion includes owned cleanup. Polling does not change how the + /// execution's owner propagates or reports failures. + Option> poll() => switch (_exit) { + null => const Option.none(), + final exit => Option.some(exit), + }; + + /// Calls [listener] once when execution and owned cleanup have finished. + /// + /// If this fiber has already completed, the callback runs immediately. The + /// returned function removes only this registration and can be called more + /// than once; it does not cancel the fiber. + /// + /// Callbacks run in their registration [Zone]. A callback exception is reported + /// to that zone without changing the exit or preventing other callbacks. Like + /// [poll], listening does not change the owner's failure handling. + /// + /// ```dart + /// final stopWatching = fiber.onExit((exit) => print(exit)); + /// // Remove this listener when its UI or observer no longer needs updates. + /// stopWatching(); + /// ``` + void Function() onExit(void Function(Exit) listener) => + _completion.listen(listener); /// Returns a task that waits for this fiber's value or failure as an [Exit]. /// - /// Cancelling the wait leaves the fiber running and does not mark an undelivered - /// result as observed. The result is observed when a continuation receives it - /// or the waiting execution returns it. Waiting on oneself, or on work that - /// must wait for the caller, fails with a [StateError] defect instead of - /// deadlocking. + /// Cancelling the wait leaves the fiber and its resource leases running. + /// Waiting does not change the execution owner's failure reporting. Use + /// [cancel] to stop the target itself. /// - /// The target's owner retains its work and resource leases after a waiter - /// cancels. An undelivered failure remains eligible for the owner's unhandled- - /// failure reporting. Use [cancel] to stop the target itself. + /// Waiting on oneself, or on work that must wait for the caller, fails with a + /// [StateError] defect instead of deadlocking. Task, Never> awaitExit() => awaitFiberTask(this); /// Returns a task that waits for this fiber and adopts its value or failure. @@ -88,58 +99,40 @@ final class Fiber { Task, Never> cancel({Object? reason}) => awaitFiberTask(this, cancel: true, reason: reason); - void Function() _listen( - void Function(Exit) listener, { - required bool observe, - }) { - void notify(Exit exit) { - if (observe) _observed = true; - listener(exit); - } - - final exit = _exit; - if (exit != null) { - notify(exit); - return () {}; - } - final token = Object(); - _listeners[token] = Zone.current.bindUnaryCallbackGuarded(notify); - return () => _listeners.remove(token); - } - void _finish(TaskEvaluation result) { - final exit = result.exit; _finalEvents = result.events; _cleanupCancellations = result.cleanupCancellations; _active = false; - _exit = exit; - _completion.complete(exit); - for (final token in _listeners.keys.toList()) { - final listener = _listeners.remove(token); - if (listener != null) listener(exit); - } - - if (exit case ExitFailure(:final cause)) { - final reasons = _reasons(cause); - if (!reasons.any((reason) => reason is! CauseCancelled)) return; - _zone.run(() { - Timer.run(() { - _reportReady = true; - _reportUnhandled(); - }); - }); + _completion.complete(result.exit); + if (_reportFailure && _finalEvents.isNotEmpty) { + _zone.run(() => Timer.run(_reportIndependentFailure)); } } - void _reportUnhandled() { - if (!_reportReady || _observed || _pendingObservations != 0) return; - _reportReady = false; - final reasons = _reasons((_exit as ExitFailure).cause); - final unhandled = _defectsHandledByOwner - ? reasons.whereType>().toList() - : reasons; - if (unhandled.isEmpty) return; - _zone.runGuarded(() => _report(Cause.combine(unhandled))); + void _reportIndependentFailure() { + final failures = >[]; + final events = _finalEvents.iterator; + final cause = (_exit as ExitFailure).cause; + var hasFailure = false; + for (final reason in switch (cause) { + CauseGroup(:final causes) => causes, + _ => [cause], + }) { + if (reason is CauseCancelled) { + if (!_cleanupOwned) failures.add(reason); + continue; + } + events.moveNext(); + final event = events.current; + // Scope shutdown receives cleanup defects through its own result. + if (_cleanupOwned && reason is CauseDefect) continue; + if (!event.source.reportedTo.add(_report)) continue; + hasFailure = true; + failures.add(reason); + } + if (hasFailure) { + _zone.runGuarded(() => _report(Cause.combine(failures))); + } } } @@ -160,6 +153,7 @@ Fiber startFiber( required Context context, Map, Object?> locals = const {}, required void Function(Cause cause) report, + required bool reportFailure, bool inheritHost = true, bool deferStart = false, bool interruptible = true, @@ -171,6 +165,7 @@ Fiber startFiber( final fiber = Fiber._( createScope(runtimeId: scopeRuntimeId(owner)), report, + reportFailure, ); attachScopeFiber(owner, fiber); final void Function()? releaseBorrow; @@ -253,8 +248,9 @@ Fiber startFiber( Fiber completedFiber( Exit exit, { required void Function(Cause cause) report, + required bool reportFailure, }) { - final fiber = Fiber._(createScope(), report); + final fiber = Fiber._(createScope(), report, reportFailure); final closing = closeScope(fiber._scope, exit); if (closing is Future?>) unawaited(closing); fiber._finish(TaskEvaluation.fresh(exit)); @@ -277,36 +273,15 @@ List fiberCleanupCancellations(Fiber fiber) => List> currentFibers() => Zone.current[_currentFibers] as List>? ?? const []; -// Captured exits can defer observation until their consumer accepts delivery. -void Function() listenFiber( - Fiber fiber, - void Function(Exit exit) listener, { - bool observe = true, -}) => fiber._listen(listener, observe: observe); - -// Delay reporting while an exit is being handed to a cancellable consumer. -// Commit only when consumed; abandoning the last delivery releases the report. -void Function(bool) reserveFiberObservation(Fiber fiber) { - fiber._pendingObservations++; - var pending = true; - return (observed) { - if (!pending) return; - pending = false; - if (observed) fiber._observed = true; - fiber._pendingObservations--; - fiber._reportUnhandled(); - }; +// Runtime.runSync transfers an unfinished execution to runtime supervision. +void superviseFiber(Fiber fiber) { + fiber._reportFailure = true; } -Future> fiberCompletion( - Fiber fiber, { - bool observe = true, -}) { - if (!observe) return fiber._completion.future; - return fiber._completion.future.then((exit) { - fiber._observed = true; - return exit; - }); +Future> fiberCompletion(Fiber fiber) { + final completion = Completer>(); + fiber.onExit(completion.complete); + return completion.future; } // Stops owned work and retains defects without converting business failures. @@ -314,21 +289,25 @@ FutureOr> stopFiber( Fiber fiber, { Object? reason, }) { - fiber._defectsHandledByOwner = true; + fiber._cleanupOwned = true; fiber.requestCancel(reason: reason); - if (fiber._exit != null) return fiber._finalEvents; - return fiberCompletion(fiber, observe: false).then((_) => fiber._finalEvents); + List defects() => [ + for (final event in fiber._finalEvents) + if (event.cause is CauseDefect) event, + ]; + if (fiber._exit != null) return defects(); + return fiberCompletion(fiber).then((_) => defects()); } -// One defect occurrence retained across internal ownership boundaries. +// One failure occurrence retained across execution and ownership boundaries. final class FailureEvent { const FailureEvent(this.cause, this.source); - final CauseDefect cause; - final Object source; + final Cause cause; + final FailureSource source; } -List> _reasons(Cause cause) => switch (cause) { - CauseGroup(:final causes) => causes, - _ => [cause], -}; +// Only explicit reporting marks an occurrence. Reads and listeners never do. +final class FailureSource { + final reportedTo = )>{}; +} diff --git a/lib/src/core/flow.dart b/lib/src/core/flow.dart index 6d1c58e..0b7462e 100644 --- a/lib/src/core/flow.dart +++ b/lib/src/core/flow.dart @@ -790,14 +790,14 @@ final class _StreamSource { } void _fault(Object error, StackTrace stackTrace) { - _faults.add(FailureEvent(CauseDefect(error, stackTrace), Object())); + _faults.add(FailureEvent(CauseDefect(error, stackTrace), FailureSource())); _ended = true; } Task _failure() => taskFromEvaluation( TaskEvaluation( Exit.failure( - Cause.combine(_faults.map((event) => event.cause)), + Cause.combine(_faults.map((event) => event.cause as CauseDefect)), ), List.unmodifiable(_faults), ), @@ -1048,7 +1048,7 @@ final class _Buffered { inheritHost: true, ).withError().flatMap((fiber) { _driver = fiber; - listenFiber(fiber, (exit) { + fiber.onExit((exit) { _terminal = TaskEvaluation( exit, fiberFailureEvents(fiber), @@ -1182,7 +1182,10 @@ final class _Buffered { _stop(); _current = null; _values.clear(); - final events = _terminal?.events ?? const []; + final events = [ + for (final event in _terminal?.events ?? const []) + if (event.cause is CauseDefect) event, + ]; final cancellations = [..._explicitCancellation]; final cleanups = [...?_terminal?.cleanupCancellations]; final causes = >[]; @@ -1291,7 +1294,7 @@ final class _ConcurrentMap { inheritHost: true, ).withError().flatMap((fiber) { _driver = fiber; - listenFiber(fiber, (exit) { + fiber.onExit((exit) { _driverDone = true; if (exit is ExitFailure) { _recordFailure(fiber, exit, cancellations); @@ -1401,7 +1404,7 @@ final class _ConcurrentMap { ).withError().flatMap((fiber) { _active.add(fiber); if (_stopping) fiber.requestCancel(reason: _stopReason); - listenFiber(fiber, (exit) { + fiber.onExit((exit) { _active.remove(fiber); final result = TaskEvaluation( exit, @@ -1514,13 +1517,13 @@ final class _ConcurrentMap { final causes = >[]; final events = []; final cleanupCancellations = []; - final seen = {}; + final seen = {}; for (final failure in _failures) { final result = failure.result; final cancellations = [...failure.cancellations]; final cleanups = [...result.cleanupCancellations]; if (result.exit case ExitFailure(:final cause)) { - final sources = Map>.identity(); + final sources = Map, Queue>.identity(); for (final event in result.events) { (sources[event.cause] ??= Queue()).addLast(event); } @@ -1533,7 +1536,12 @@ final class _ConcurrentMap { events.add(event); } case CauseFailure(:final error): - if (!defectsOnly) causes.add(Cause.failure(error as F)); + final event = sources[reason]!.removeFirst(); + if (!defectsOnly && seen.add(event.source)) { + final failure = Cause.failure(error as F); + causes.add(failure); + events.add(FailureEvent(failure, event.source)); + } case CauseCancelled(): if ((!defectsOnly || (!_failureDelivered && cancellations.remove(reason))) && diff --git a/lib/src/core/flow_aggregation.dart b/lib/src/core/flow_aggregation.dart index 6a5612a..bb28888 100644 --- a/lib/src/core/flow_aggregation.dart +++ b/lib/src/core/flow_aggregation.dart @@ -312,7 +312,7 @@ final class _TimedAggregation { inheritHost: true, ).map((fiber) { _active = fiber; - listenFiber(fiber, (exit) { + fiber.onExit((exit) { _active = null; final result = TaskEvaluation( exit, @@ -459,7 +459,10 @@ final class _TimedAggregation { causes.isEmpty ? const Exit.success(null) : Exit.failure(Cause.combine(causes)), - _failure?.events ?? const [], + [ + for (final event in _failure?.events ?? const []) + if (event.cause is CauseDefect) event, + ], cleanupCancellations: [ for (final cause in causes) if (cause is CauseCancelled && cleanups.remove(cause)) cause, diff --git a/lib/src/core/flow_combination.dart b/lib/src/core/flow_combination.dart index fdb711b..19e6e93 100644 --- a/lib/src/core/flow_combination.dart +++ b/lib/src/core/flow_combination.dart @@ -203,7 +203,7 @@ final class _Readers { input.fiber = fiber; _active.add(fiber); if (stopping) fiber.requestCancel(reason: _stopReason); - listenFiber(fiber, (exit) { + fiber.onExit((exit) { input.fiber = null; _active.remove(fiber); if (exit is ExitFailure) { @@ -284,13 +284,13 @@ final class _Readers { final causes = >[]; final events = []; final cleanupCancellations = []; - final seen = {}; + final seen = {}; for (final failure in _failures) { final result = failure.result; final cancellations = [...failure.explicitCancellation]; final cleanups = [...result.cleanupCancellations]; if (result.exit case ExitFailure(:final cause)) { - final sources = Map>.identity(); + final sources = Map, Queue>.identity(); for (final event in result.events) { (sources[event.cause] ??= Queue()).addLast(event); } @@ -303,7 +303,12 @@ final class _Readers { events.add(event); } case CauseFailure(:final error): - if (!defectsOnly) causes.add(Cause.failure(error as F)); + final event = sources[reason]!.removeFirst(); + if (!defectsOnly && seen.add(event.source)) { + final failure = Cause.failure(error as F); + causes.add(failure); + events.add(FailureEvent(failure, event.source)); + } case CauseCancelled(): if ((!defectsOnly || (!_failureDelivered && cancellations.remove(reason))) && diff --git a/lib/src/core/flow_sharing.dart b/lib/src/core/flow_sharing.dart index 399043b..b704749 100644 --- a/lib/src/core/flow_sharing.dart +++ b/lib/src/core/flow_sharing.dart @@ -105,7 +105,7 @@ final class _SharedFlow { final _subscriptions = <_SharedSubscription>{}; final _waiting = {}; final _failures = <_SharedFailure>[]; - final _defects = {}; + final _failureSources = {}; late final FlowProducer _lifetime; late final void Function() _removeResources; late final void Function() _removeWork; @@ -195,10 +195,11 @@ final class _SharedFlow { context: environment.context, locals: environment.locals, report: environment.report, + reportFailure: false, inheritHost: false, deferStart: true, ); - listenFiber(_driver!, (exit) => unawaited(_driverEnded(exit))); + _driver!.onExit((exit) => unawaited(_driverEnded(exit))); } Future _driverEnded(Exit exit) async { @@ -292,10 +293,10 @@ final class _SharedFlow { var removedStop = false; for (final cause in _causes(cause)) { FailureEvent? event; - if (cause is CauseDefect) { + if (cause is CauseFailure || cause is CauseDefect) { events.moveNext(); event = events.current; - if (!_defects.add(event.source)) continue; + if (!_failureSources.add(event.source)) continue; } if (stop && !removedStop && diff --git a/lib/src/core/internal/flow_cursor.dart b/lib/src/core/internal/flow_cursor.dart index 2502eb3..414303a 100644 --- a/lib/src/core/internal/flow_cursor.dart +++ b/lib/src/core/internal/flow_cursor.dart @@ -102,10 +102,10 @@ TaskEvaluation mergeFlowEvaluations( final causes = >[]; final events = []; final cleanupCancellations = []; - final seen = {}; + final seen = {}; for (final result in results) { if (result.exit case ExitFailure(:final cause)) { - final sources = Map>.identity(); + final sources = Map, Queue>.identity(); for (final event in result.events) { (sources[event.cause] ??= Queue()).addLast(event); } diff --git a/lib/src/core/internal/shared_resource_state.dart b/lib/src/core/internal/shared_resource_state.dart index 714e708..38d8380 100644 --- a/lib/src/core/internal/shared_resource_state.dart +++ b/lib/src/core/internal/shared_resource_state.dart @@ -119,10 +119,11 @@ final class SharedResourceState { context: _environment.context, locals: _environment.locals, report: _environment.report, + reportFailure: false, inheritHost: false, deferStart: true, ); - listenFiber(fiber, (exit) { + fiber.onExit((exit) { _loaded(generation, TaskEvaluation(exit, fiberFailureEvents(fiber))); }); } catch (error, stackTrace) { @@ -159,7 +160,7 @@ final class SharedResourceState { return true; } catch (error, stackTrace) { generation.faults.add( - FailureEvent(CauseDefect(error, stackTrace), Object()), + FailureEvent(CauseDefect(error, stackTrace), FailureSource()), ); return false; } @@ -250,7 +251,7 @@ final class SharedResourceState { return Task.succeed(null); } catch (error, stackTrace) { generation.faults.add( - FailureEvent(CauseDefect(error, stackTrace), Object()), + FailureEvent(CauseDefect(error, stackTrace), FailureSource()), ); return _await(_beginClose(generation, exit)); } @@ -428,12 +429,14 @@ TaskEvaluation _defects(Iterable events) { final seen = {}; final unique = [ for (final event in events) - if (seen.add(event.source)) event, + if (event.cause is CauseDefect && seen.add(event.source)) event, ]; return TaskEvaluation( unique.isEmpty ? const Exit.success(null) - : Exit.failure(Cause.combine(unique.map((event) => event.cause))), + : Exit.failure( + Cause.combine(unique.map((event) => event.cause as CauseDefect)), + ), unique, ); } diff --git a/lib/src/core/internal/task_concurrency.dart b/lib/src/core/internal/task_concurrency.dart index 573148a..bbc9796 100644 --- a/lib/src/core/internal/task_concurrency.dart +++ b/lib/src/core/internal/task_concurrency.dart @@ -153,7 +153,7 @@ final class _Run { ).flatMap((fiber) { active[index] = fiber; if (stopping) fiber.requestCancel(reason: stopReason); - listenFiber(fiber, (exit) { + fiber.onExit((exit) { active.remove(index); exits[index] = exit; final completion = _Completion( @@ -229,7 +229,7 @@ final class _Run { final keepCause = !defectsOnly && include(completion); final keepDefects = defectsOnly || mode != _Mode.settled || stopping || keepCause; - final sources = Map>.identity(); + final sources = Map, List>.identity(); for (final event in completion.result.events.reversed) { (sources[event.cause] ??= []).add(event); } @@ -249,7 +249,12 @@ final class _Run { reasons.add(Cause.cancelled(reason)); } case CauseFailure(:final error): - if (keepCause) reasons.add(Cause.failure(error as F)); + if (!keepCause) continue; + final event = sources[reason]!.removeLast(); + if (!seen.add(event.source)) continue; + final mapped = Cause.failure(error as F); + reasons.add(mapped); + events.add(FailureEvent(mapped, event.source)); case CauseGroup(): throw StateError('Cause groups must be flat.'); } @@ -263,7 +268,9 @@ final class _Run { List.unmodifiable(events), pendingFailures: reasons.isEmpty && mode == _Mode.settled && !defectsOnly ? List.unmodifiable([ - for (final completion in completed) ...completion.result.events, + for (final completion in completed) + for (final event in completion.result.events) + if (event.cause is CauseDefect) event, ]) : const [], ); diff --git a/lib/src/core/layer.dart b/lib/src/core/layer.dart index 493dc21..24a1d40 100644 --- a/lib/src/core/layer.dart +++ b/lib/src/core/layer.dart @@ -1,5 +1,3 @@ -import 'dart:async'; - import 'context.dart'; import 'exit.dart'; import 'fiber.dart'; @@ -181,10 +179,6 @@ final class _BuildSession { owner, resourceScope: scope, ).exit().withError().flatMap((started) { - if (started case ExitSuccess(:final value)) { - // The build session owns the result even if every waiter left. - unawaited(fiberCompletion(value)); - } entry.ready.complete(started); return restore(entry.wait()); }); diff --git a/lib/src/core/request_resolver.dart b/lib/src/core/request_resolver.dart index cb91694..7fdac94 100644 --- a/lib/src/core/request_resolver.dart +++ b/lib/src/core/request_resolver.dart @@ -347,10 +347,11 @@ final class _Run { context: environment.context, locals: environment.locals, report: environment.report, + reportFailure: false, deferStart: true, ); batch.fiber = fiber; - listenFiber(fiber, (exit) { + fiber.onExit((exit) { finish(batch, TaskEvaluation(exit, fiberFailureEvents(fiber))); }); } catch (error, stackTrace) { @@ -475,57 +476,64 @@ final class _Call { var detached = false; final stopped = <_Batch>{}; - Task>, E>, Never> - awaitResults() => Task.fromCallback((complete) { - void check() { - if (entries.any((entry) => entry.result == null)) return; - wake = null; - final failures = >{}; - for (final entry in entries) { - if (entry.result!.exit is ExitFailure) { - failures[entry.batch ?? entry] = entry; - } - } - if (failures.isEmpty) { - complete( - Exit.success( - TaskEvaluation( + Task>, E>, Never> awaitResults() => + Task.fromCallback((complete) { + void check() { + if (entries.any((entry) => entry.result == null)) return; + wake = null; + final failures = >{}; + for (final entry in entries) { + if (entry.result!.exit is ExitFailure) { + failures[entry.batch ?? entry] = entry; + } + } + if (failures.isEmpty) { + complete( Exit.success( - List>.unmodifiable([ - for (final entry in entries) - (entry.result!.exit as ExitSuccess, E>).value, - ]), + TaskEvaluation( + Exit.success( + List>.unmodifiable([ + for (final entry in entries) + (entry.result!.exit as ExitSuccess, E>) + .value, + ]), + ), + const [], + ), ), - const [], - ), - ), - ); - } else { - final ordered = failures.values.toList() - ..sort((a, b) => a.order.compareTo(b.order)); - final events = _uniqueEvents( - ordered.expand((entry) => entry.result!.events), - ); - complete( - Exit.success( - TaskEvaluation( - Exit.failure( - Cause.combine([ - for (final entry in ordered) - (entry.result!.exit as ExitFailure, E>).cause, - ]), + ); + } else { + final ordered = failures.values.toList() + ..sort((a, b) => a.order.compareTo(b.order)); + final reasons = >[]; + final events = []; + final seen = {}; + for (final entry in ordered) { + final result = entry.result!; + final sources = result.events.iterator; + final cause = (result.exit as ExitFailure, E>).cause; + for (final reason in _reasons(cause)) { + if (reason is! CauseCancelled) { + sources.moveNext(); + final event = sources.current; + if (!seen.add(event.source)) continue; + events.add(event); + } + reasons.add(reason); + } + } + complete( + Exit.success( + TaskEvaluation(Exit.failure(Cause.combine(reasons)), events), ), - events, - ), - ), - ); - } - } + ); + } + } - wake = check; - check(); - return detach; - }); + wake = check; + check(); + return detach; + }); void detach() { if (detached) return; @@ -573,7 +581,9 @@ final class _Call { }; var stoppedCancellationRemoved = false; final evaluation = entry.result!; - final sources = evaluation.events.iterator; + final sources = evaluation.events + .where((event) => event.cause is CauseDefect) + .iterator; final cause = (evaluation.exit as ExitFailure, E>).cause; for (final reason in _reasons(cause)) { switch (reason) { @@ -630,14 +640,6 @@ bool _localsIdentical( return true; } -List _uniqueEvents(Iterable events) { - final seen = {}; - return [ - for (final event in events) - if (seen.add(event.source)) event, - ]; -} - List> _reasons(Cause cause) => switch (cause) { CauseGroup(:final causes) => causes, _ => [cause], diff --git a/lib/src/core/runtime.dart b/lib/src/core/runtime.dart index 141dbd6..fb06be9 100644 --- a/lib/src/core/runtime.dart +++ b/lib/src/core/runtime.dart @@ -53,8 +53,10 @@ final class Runtime { /// logging, tracing, and metrics default to no-ops. Supplied service objects keep /// their caller-managed lifetime. /// - /// [onUnhandledError] receives business failures and defects that remain - /// unobserved on the next event-loop turn. Each failure is reported once; + /// [onUnhandledError] receives independent failures from [start] and public + /// forks on the next event-loop turn. Reading their results does not suppress + /// reporting. [run] and synchronous results go directly to their caller. Each + /// failure occurrence is reported once; /// cancellation alone is not reported. Without a handler, a [TaskException] /// is reported to the creating [Zone]. Exceptions thrown by the handler are /// also reported to that zone and cannot interrupt cleanup. @@ -110,8 +112,9 @@ final class Runtime { context: context, onUnhandledError: onUnhandledError, ); - final building = runtime.start( + final building = runtime._start( buildLayer(services, runtime._scope), + reportFailure: false, signal: signal, ); final unsubscribe = signal?.onCancel((reason) { @@ -147,8 +150,9 @@ final class Runtime { /// Starts [task] and returns a handle to its independent execution. /// /// [signal] can cancel this execution without affecting other roots. The fiber - /// completes after its child work and resource cleanup. Observe its result with - /// [Fiber.join], [Fiber.awaitExit], or [Fiber.poll] to handle failures directly. + /// completes after its child work and resource cleanup. Failures go to this + /// runtime's handler, independently of [Fiber.onExit], [Fiber.poll], or waiting + /// for the result. Use [run] to receive a result without a background report. /// /// To let a page stop waiting without cancelling native work, pass the page's /// signal to a separate [run] of [Fiber.join]. Acquire leases inside the owned @@ -188,12 +192,13 @@ final class Runtime { /// A closing or closed runtime returns a completed fiber with a [RuntimeClosed] /// defect; the task does not start. Fiber start(Task task, {CancellationSignal? signal}) => - _start(task, signal: signal); + _start(task, signal: signal, reportFailure: true); Fiber _start( Task task, { CancellationSignal? signal, ExecutionMode? mode, + required bool reportFailure, }) { if (_closing != null) { return completedFiber( @@ -201,12 +206,14 @@ final class Runtime { Cause.defect(const RuntimeClosed(), StackTrace.current), ), report: _report, + reportFailure: reportFailure, ); } return startFiber( task, owner: _scope, report: _report, + reportFailure: reportFailure, signal: signal, context: _context, mode: mode, @@ -215,19 +222,18 @@ final class Runtime { /// Runs [task] and returns its value or complete failure as an [Exit]. /// - /// The result includes child completion and resource cleanup, and counts as an - /// observed fiber result for failure reporting. + /// The result includes child completion and resource cleanup. This entry sends + /// the result to its caller without also reporting it as a background failure. /// /// [signal] cancels only this execution. An already cancelled signal prevents /// the task from starting. Cancellation waits for any in-flight, /// non-cancellable [Future] to settle before returning. /// /// Applying [Future.timeout] to the returned Future does not cancel this task. - /// This entry still observes its eventual exit, even if the host abandons that - /// Future. Use [start] and a separately cancellable [Fiber.join] when work must + /// The eventual exit remains on that Future, even if the host abandons it. Use [start] and a separately cancellable [Fiber.join] when work must /// remain supervised after its caller stops waiting. Future> run(Task task, {CancellationSignal? signal}) => - fiberCompletion(start(task, signal: signal)); + fiberCompletion(_start(task, signal: signal, reportFailure: false)); /// Runs [task] and returns its value, throwing [TaskException] on failure. /// @@ -254,7 +260,8 @@ final class Runtime { /// callback that delivers its result during registration can finish synchronously. /// /// At an asynchronous boundary, cancellation is requested and this runtime - /// continues supervising the original execution. The exception's + /// continues supervising and reporting failures from the original execution. + /// Reading the exception's completion does not change that responsibility. Its /// [AsyncTaskException.completion] exposes its eventual exit. Effects already /// performed are not repeated or rolled back; cancellation still respects /// masks and waits for non-cancellable work and cleanup. @@ -266,11 +273,12 @@ final class Runtime { final mode = ExecutionMode(automaticYield: false); final Fiber fiber; try { - fiber = _start(task, signal: signal, mode: mode); + fiber = _start(task, signal: signal, mode: mode, reportFailure: false); } finally { mode.automaticYield = true; } if (fiber.poll() case OptionSome(:final value)) return value; + superviseFiber(fiber); fiber.requestCancel(); throw AsyncTaskException._(fiber); } @@ -370,9 +378,8 @@ final class AsyncTaskException implements Exception { /// The original execution's exit after owned work and cleanup finish. /// - /// Reading this property observes the eventual result for unhandled-failure - /// reporting, as [Runtime.run] does. Ignoring the exception leaves reporting - /// with its runtime. A non-cancellable operation can delay completion. + /// The runtime reports independent failures whether or not this property is + /// read. A non-cancellable operation can delay completion. Future> get completion => fiberCompletion(_fiber); @override diff --git a/lib/src/core/scope.dart b/lib/src/core/scope.dart index 62c93cf..5b13b85 100644 --- a/lib/src/core/scope.dart +++ b/lib/src/core/scope.dart @@ -321,7 +321,9 @@ FutureOr _closeClaimed( void recordEvents(Scope scope, Iterable events) { for (final event in events) { - _record(scope, event.cause, owner, source: event.source); + if (event.cause case final CauseDefect cause) { + _record(scope, cause, owner, source: event.source); + } } } @@ -468,7 +470,7 @@ void _recordEvaluation( }; final defects = result.events.iterator; for (final reason in reasons) { - Object? source; + FailureSource? source; if (reason is CauseDefect) { defects.moveNext(); source = defects.current.source; @@ -480,7 +482,12 @@ void _recordEvaluation( // Record each cleanup event once in every ancestor owned by the same close. // Child completion does not merge the same cause into those ancestors again. -void _record(Scope scope, Cause cause, Object owner, {Object? source}) { +void _record( + Scope scope, + Cause cause, + Object owner, { + FailureSource? source, +}) { final events = switch (cause) { CauseGroup(:final causes) => [ for (final item in causes) _CleanupEvent(item), @@ -540,13 +547,14 @@ final class _Closing { FutureOr?> get result => completion.isCompleted ? cause : completion.future; final events = <_CleanupEvent>[]; - final sources = {}; + final sources = {}; } final class _CleanupEvent { - _CleanupEvent(this.cause, [Object? source]) : source = source ?? Object(); + _CleanupEvent(this.cause, [FailureSource? source]) + : source = source ?? FailureSource(); final Cause cause; - final Object source; + final FailureSource source; } final class _Finalizer { diff --git a/lib/src/core/task.dart b/lib/src/core/task.dart index 13458c7..0cfe1d6 100644 --- a/lib/src/core/task.dart +++ b/lib/src/core/task.dart @@ -502,17 +502,19 @@ extension TaskOperations on Task { /// resources available to the parent. Parent completion cancels and waits for /// unfinished children; closing the borrowed scope also stops them first. /// - /// Use [Fiber.join] to propagate the child's value or business failure. An - /// unobserved failure is reported by the runtime; starting a child does not by - /// itself make its business failure the parent's result. - Task, Never> fork() => forkTask(this); + /// Use [Fiber.join] to propagate the child's value or failure. The runtime + /// reports independent failures even if the result is read or joined; starting + /// a child does not by itself make its business failure the parent's result. + /// Owning combinators such as [Task.all] receive their workers' results directly. + Task, Never> fork() => forkTask(this, reportFailure: true); /// Starts a fiber whose lifetime belongs to an explicit [scope]. /// /// Use this when the owner should outlive the task that starts the fiber. The /// scope must be open and belong to the same runtime. New resources belong to /// that scope; closing it cancels the fiber before releasing them. - /// Cancellation of the creating task does not cancel the fiber. + /// Cancellation of the creating task does not cancel the fiber. Independent + /// failures are reported as with [fork], regardless of listeners or reads. /// Captured objects and service bindings retain their original lifetimes. /// /// A shorter-lived caller can wait with [Fiber.join] and cancel only its wait. @@ -535,6 +537,7 @@ extension TaskOperations on Task { context: context, locals: locals, report: fiberReport(parent), + reportFailure: true, mode: mode, ); }), @@ -610,6 +613,7 @@ extension TaskOperations on Task { _mapErrors(cause, (error) => transform(error as E), signal), events, cleanups, + preserveOrder: true, ), ), ), @@ -654,11 +658,14 @@ extension TaskOperations on Task { _Continue( _node, _Frame( - failure: (cause, events, cleanups, _) => _preserveFailure( - transform(_typedCause(cause)), - events, - cleanups, - ), + failure: (cause, events, cleanups, _) { + final typed = _typedCause(cause); + return _preserveFailure( + transform(typed), + identical(typed, cause) ? events : _retagEvents(typed, events), + cleanups, + ); + }, ), ), ); @@ -693,6 +700,7 @@ extension TaskOperations on Task { _defects(cause, StackTrace.current), events, cleanups, + preserveOrder: true, ), ), ), @@ -756,7 +764,7 @@ FutureOr> evaluateTask( ); FutureOr> finish(_EvaluationResult evaluated) { - var (result, cancellationObserved, observed, observation) = evaluated; + var (result, cancellationObserved, handledSources, pendingExit) = evaluated; if (interruptible && !cancellationObserved && (signal?.isCancelled ?? false)) { @@ -770,16 +778,16 @@ FutureOr> evaluateTask( TaskEvaluation complete() { final excluded = { - ...observed, + ...handledSources, for (final event in result.events) event.source, }; var cleanup = scopeCleanupFor(ownedScope, { ...excluded, - ...?observation?.sources, + ...?pendingExit?.sources, }); // Pending exits can be returned only if cleanup and cancellation preserve // the successful value. Otherwise retain their defects in owner cleanup. - if (observation != null && + if (pendingExit != null && (result.exit is ExitFailure || cleanup.exit is ExitFailure || (interruptible && (signal?.isCancelled ?? false)))) { @@ -798,10 +806,9 @@ FutureOr> evaluateTask( if (result.exit is ExitFailure) { result = _prependPendingCleanup( result, - observation?.cleanup ?? const [], + pendingExit?.cleanup ?? const [], ); } - observation?.complete(result.exit is ExitSuccess); return result; } @@ -894,6 +901,7 @@ Task inTaskScope(Task task, Scope scope) => Task, Never> forkTask( Task task, { bool inheritCancellation = false, + bool reportFailure = false, }) => Task._( _Fork( ( @@ -916,6 +924,7 @@ Task, Never> forkTask( context: context, locals: locals, report: fiberReport(parent), + reportFailure: reportFailure, mode: mode, ), ), @@ -939,6 +948,7 @@ Task, Never> forkTaskIn( context: context, locals: locals, report: fiberReport(parent), + reportFailure: false, mode: mode, ), ), @@ -983,17 +993,13 @@ Task taskFromEvaluation(TaskEvaluation result) => ), }); -typedef _FiberObservation = ({ - Set sources, - List cleanup, - void Function(bool) complete, -}); +typedef _PendingExit = ({Set sources, List cleanup}); typedef _EvaluationResult = ( TaskEvaluation, bool, Set, - _FiberObservation?, + _PendingExit?, ); FutureOr<_EvaluationResult> _evaluate( @@ -1011,12 +1017,12 @@ FutureOr<_EvaluationResult> _evaluate( }) { var current = task._node; final frames = <_Frame>[]; - // Observation affects automatic cleanup merging within this execution only. + // Accepted results affect cleanup merging within this execution only. // Finalizers have independent executions, even when they belong to this fiber. - final observed = {}; + final handledSources = {}; // A captured fiber exit is still only a pending value until a continuation // consumes it, or the execution returns it after cleanup. - _FiberObservation? observation; + _PendingExit? pendingExit; var evaluating = true; var currentScope = resourceScope; var currentOwnedScope = scope; @@ -1029,11 +1035,11 @@ FutureOr<_EvaluationResult> _evaluate( var remaining = 2048; var cancellationObserved = false; - void finishObservation(bool consumed) { - final pending = observation; + void finishPendingExit(bool consumed) { + final pending = pendingExit; if (pending == null) return; if (consumed) { - observed.addAll(pending.sources); + handledSources.addAll(pending.sources); } else { final completed = _prependPendingCleanup( TaskEvaluation( @@ -1050,8 +1056,7 @@ FutureOr<_EvaluationResult> _evaluate( events = completed.events; cleanupCancellations = completed.cleanupCancellations; } - pending.complete(consumed); - observation = null; + pendingExit = null; } late FutureOr<_EvaluationResult> Function() run; @@ -1096,8 +1101,9 @@ FutureOr<_EvaluationResult> _evaluate( while (true) { final effectiveSignal = interruptible ? signal : null; if (!cancellationObserved && (effectiveSignal?.isCancelled ?? false)) { - finishObservation(false); + finishPendingExit(false); failure = _cancelled(failure, effectiveSignal!.reason); + events = _failureEvents(failure!, events); cancellationObserved = true; // Completion frames already removed from the stack still have to run. current = switch (current) { @@ -1207,24 +1213,20 @@ FutureOr<_EvaluationResult> _evaluate( var delivered = const []; var deliveredCleanups = const []; if (!join) { - observation = ( - sources: {}, - cleanup: [], - complete: reserveFiberObservation(target), - ); + pendingExit = (sources: {}, cleanup: []); } final pending = _runCallback( - (complete) => listenFiber(target, (exit) { + (complete) => target.onExit((exit) { delivered = fiberFailureEvents(target); deliveredCleanups = fiberCleanupCancellations(target); final sources = delivered.map((event) => event.source); if (join) { - observed.addAll(sources); + handledSources.addAll(sources); } else { - observation!.sources.addAll(sources); + pendingExit!.sources.addAll(sources); } complete(join ? exit : Exit.success(exit)); - }, observe: join), + }), effectiveSignal, ); final suspended = waitFor(pending, (exit) { @@ -1244,10 +1246,9 @@ FutureOr<_EvaluationResult> _evaluate( if (suspended != null) return suspended; case _Success(value: final result, :final pendingFailures): if (pendingFailures.isNotEmpty) { - observation = ( + pendingExit = ( sources: {for (final event in pendingFailures) event.source}, cleanup: [...pendingFailures], - complete: (_) {}, ); } value = result; @@ -1451,7 +1452,7 @@ FutureOr<_EvaluationResult> _evaluate( } events = completed.events; cleanupCancellations = completed.cleanupCancellations; - if (failure != null) finishObservation(false); + if (failure != null) finishPendingExit(false); evaluating = false; }); if (suspended != null) return suspended; @@ -1494,19 +1495,19 @@ FutureOr<_EvaluationResult> _evaluate( _, ) { final excluded = { - ...observed, + ...handledSources, for (final event in bodyEvents) event.source, }; final fullCleanup = scopeCleanupFor(scope, excluded); final filteredCleanup = scopeCleanupFor(scope, { ...excluded, - ...?observation?.sources, + ...?pendingExit?.sources, }); final canDeliver = exit is ExitSuccess && filteredCleanup.exit is ExitSuccess && !(effectiveSignal?.isCancelled ?? false); - if (observation case final pending? when canDeliver) { + if (pendingExit case final pending? when canDeliver) { // This scope detaches after closing. Keep the excluded occurrences // until delivery so a later cancellation or failure can retain them. pending.cleanup.addAll( @@ -1532,7 +1533,7 @@ FutureOr<_EvaluationResult> _evaluate( } events = completed.events; cleanupCancellations = completed.cleanupCancellations; - if (!canDeliver) finishObservation(false); + if (!canDeliver) finishPendingExit(false); evaluating = false; }); if (suspended != null) return suspended; @@ -1561,7 +1562,7 @@ FutureOr<_EvaluationResult> _evaluate( }; events = completed.events; cleanupCancellations = completed.cleanupCancellations; - observed.addAll(events.map((event) => event.source)); + handledSources.addAll(events.map((event) => event.source)); value = null; evaluating = false; }); @@ -1574,6 +1575,10 @@ FutureOr<_EvaluationResult> _evaluate( final Exit exit = failure == null ? Exit.success(value as T) : Exit.failure(_typedCause(failure!)); + if (exit case ExitFailure(:final cause) + when !identical(cause, failure)) { + events = _retagEvents(cause, events); + } return ( TaskEvaluation( exit, @@ -1581,8 +1586,8 @@ FutureOr<_EvaluationResult> _evaluate( cleanupCancellations: cleanupCancellations, ), cancellationObserved, - observed, - observation, + handledSources, + pendingExit, ); } @@ -1608,7 +1613,7 @@ FutureOr<_EvaluationResult> _evaluate( if (failure case final cause?) { final resume = frame.failure; if (resume == null) continue; - finishObservation(false); + finishPendingExit(false); current = resume( failure ?? cause, events, @@ -1618,7 +1623,7 @@ FutureOr<_EvaluationResult> _evaluate( } else { final resume = frame.success; if (resume == null) continue; - if (frame.consumesValue) finishObservation(true); + if (frame.consumesValue) finishPendingExit(true); current = resume(value); } // A continuation has already produced this failure. Record it before the @@ -1672,7 +1677,7 @@ List _failureEvents( Cause cause, [ Iterable previous = const [], ]) { - final available = Map>.identity(); + final available = Map, List>.identity(); for (final event in previous.toList().reversed) { (available[event.cause] ??= []).add(event); } @@ -1682,14 +1687,37 @@ List _failureEvents( }; return List.unmodifiable([ for (final reason in reasons) - if (reason is CauseDefect) + if (reason is! CauseCancelled) if (available[reason] case final candidates? when candidates.isNotEmpty) candidates.removeLast() else - FailureEvent(reason, Object()), + FailureEvent(reason, FailureSource()), ]); } +// Type casts, mapError, and orDie keep the same ordered failure occurrences. +List _retagEvents( + Cause cause, + List previous, +) { + final sources = previous.iterator; + final events = []; + for (final reason in switch (cause) { + CauseGroup(:final causes) => causes, + _ => [cause], + }) { + if (reason is CauseCancelled) continue; + sources.moveNext(); + final event = sources.current; + events.add( + identical(reason, event.cause) + ? event + : FailureEvent(reason, event.source), + ); + } + return List.unmodifiable(events); +} + List _cancellations(Cause cause) => switch (cause) { CauseCancelled() => [cause], CauseGroup(:final causes) => causes.whereType().toList(), @@ -1699,13 +1727,17 @@ List _cancellations(Cause cause) => switch (cause) { _Failure _preserveFailure( Cause cause, List events, - List cleanupCancellations, -) { + List cleanupCancellations, { + bool preserveOrder = false, +}) { + final retained = preserveOrder + ? _retagEvents(cause, events) + : _failureEvents(cause, events); if (cleanupCancellations.isEmpty) { - return _Failure(cause, _failureEvents(cause, events)); + return _Failure(cause, retained); } final available = [...cleanupCancellations]; - return _Failure(cause, _failureEvents(cause, events), [ + return _Failure(cause, retained, [ for (final cancellation in _cancellations(cause)) if (available.remove(cancellation)) cancellation, ]); @@ -1719,13 +1751,13 @@ TaskEvaluation _prependPendingCleanup( final sources = {for (final event in result.events) event.source}; final events = [ for (final event in pending) - if (sources.add(event.source)) event, + if (event.cause is CauseDefect && sources.add(event.source)) event, ]; if (events.isEmpty) return result; return TaskEvaluation( Exit.failure( Cause.combine([ - for (final event in events) event.cause, + for (final event in events) event.cause as CauseDefect, if (result.exit case ExitFailure(:final cause)) cause, ]), ), @@ -1847,7 +1879,7 @@ typedef _RegisterCallback = _CancelCallback Function( ); Cause _typedCause(Cause cause) => - cause.mapError((error) => error as E); + cause is Cause ? cause : cause.mapError((error) => error as E); Exit _typedExit(Exit exit) => switch (exit) { ExitSuccess(:final value) => Exit.success(value as T), diff --git a/test/core/fiber_failure_routing_test.dart b/test/core/fiber_failure_routing_test.dart new file mode 100644 index 0000000..5a66733 --- /dev/null +++ b/test/core/fiber_failure_routing_test.dart @@ -0,0 +1,202 @@ +import 'dart:async'; + +import 'package:any/any.dart'; +import 'package:test/test.dart'; + +void main() { + late Runtime runtime; + late List> reports; + + setUp(() { + reports = []; + runtime = Runtime(onUnhandledError: reports.add); + }); + tearDown(() => runtime.close()); + + for (final read in ['none', 'poll', 'listener', 'awaitExit', 'join']) { + test('$read does not change an independent failure report', () async { + final fiber = runtime.start(Task.fail('failed')); + switch (read) { + case 'poll': + expect(fiber.poll(), isA>>()); + fiber.poll(); + case 'listener': + fiber.onExit((exit) => expect(exit, isA())); + case 'awaitExit': + await runtime.run(fiber.awaitExit()); + await runtime.run(fiber.awaitExit()); + case 'join': + await runtime.run(fiber.join()); + await runtime.run(fiber.join()); + } + await _reportsTurn(); + expect(reports, hasLength(1)); + expect((reports.single as CauseFailure).error, 'failed'); + }); + } + + test('result-returning entries do not add a fallback report', () async { + expect(await runtime.run(Task.fail('run')), isA()); + expect(runtime.runSync(Task.fail('sync')), isA()); + await expectLater( + runtime.runOrThrow(Task.fail('throw')), + throwsA(isA()), + ); + await _reportsTurn(); + expect(reports, isEmpty); + }); + + for (final observerFirst in [false, true]) { + test('joining from another runtime preserves both reporting routes ' + '(observer reports first: $observerFirst)', () async { + final order = []; + final ownerReports = >[]; + final observerReports = >[]; + final ownerReported = Completer(); + final observerReported = Completer(); + final owner = Runtime( + onUnhandledError: (cause) { + ownerReports.add(cause); + order.add('owner'); + if (!ownerReported.isCompleted) ownerReported.complete(); + }, + ); + final observer = Runtime( + onUnhandledError: (cause) { + observerReports.add(cause); + order.add('observer'); + if (!observerReported.isCompleted) observerReported.complete(); + }, + ); + addTearDown(owner.close); + addTearDown(observer.close); + late void Function(Exit) complete; + final fiber = owner.start( + Task.fromCallback((callback) { + complete = callback; + return () {}; + }), + ); + late Fiber joined; + if (observerFirst) { + // The reentrant root completes before the owner queues its report. + fiber.onExit((_) => joined = observer.start(fiber.join())); + } + complete(const Exit.failure(Cause.failure('owned failure'))); + if (!observerFirst) { + await ownerReported.future; + joined = observer.start(fiber.join()); + } + await Future.wait([ownerReported.future, observerReported.future]); + + expect( + order, + observerFirst ? ['observer', 'owner'] : ['owner', 'observer'], + ); + for (var i = 0; i < 2; i++) { + expect(fiber.poll(), isA>>()); + expect(joined.poll(), isA>>()); + fiber.onExit((exit) => expect(exit, isA>())); + await owner.run(fiber.awaitExit()); + await observer.run(fiber.join()); + await owner.run(joined.join()); + await observer.run(joined.awaitExit()); + } + await _reportsTurn(); + + expect(ownerReports, hasLength(1)); + expect(observerReports, hasLength(1)); + expect((ownerReports.single as CauseFailure).error, 'owned failure'); + expect((observerReports.single as CauseFailure).error, 'owned failure'); + }); + } + + for (final conversion in ['none', 'mapError', 'orDie']) { + test( + 'a public child joined into a reported root reports once (conversion: $conversion)', + () async { + final task = Task.fail('child') + .fork() + .withError() + .flatMap((fiber) { + final joined = fiber.join(); + return switch (conversion) { + 'mapError' => joined.mapError((error) => 'mapped $error'), + 'orDie' => joined.orDie(), + _ => joined, + }; + }); + final root = runtime.start(task); + await runtime.run(root.awaitExit()); + await _reportsTurn(); + expect(reports, hasLength(1)); + }, + ); + } + + test('independent executions of the same cause still report twice', () async { + const cause = Cause.failure('same object'); + runtime.start(Task.failCause(cause)); + runtime.start(Task.failCause(cause)); + await _reportsTurn(); + expect(reports, hasLength(2)); + }); + + test('owning combinators receive failures without worker reports', () async { + final all = await runtime.run( + Task.all([Task.fail('first'), Task.fail('second')], concurrency: 2), + ); + expect(all, isA()); + final settled = await runtime.runOrThrow( + Task.allSettled([Task.fail('settled')], concurrency: 1), + ); + expect(settled.single, isA()); + await _reportsTurn(); + expect(reports, isEmpty); + }); + + for (final read in [false, true]) { + test( + 'runSync async failure remains supervised (completion read: $read)', + () async { + final release = Completer(); + addTearDown(() { + if (!release.isCompleted) release.complete(); + }); + final defect = Cause.defect( + StateError('cleanup'), + StackTrace.current, + ); + final task = Task.fromCallback((_) => () {}).ensuring( + Task.fromFuture( + () => release.future, + onError: Error.throwWithStackTrace, + ).flatMap((_) => Task.failCause(defect)), + ); + late AsyncTaskException pending; + try { + runtime.runSync(task); + fail('The pending callback requires an asynchronous boundary.'); + } on AsyncTaskException catch (error) { + pending = error; + } + final completion = read ? pending.completion : null; + release.complete(); + if (completion != null) expect(await completion, isA()); + await _reportsTurn(); + expect((reports.single as CauseGroup).causes.whereType(), [ + same(defect), + ]); + expect( + (reports.single as CauseGroup).causes.whereType(), + hasLength(1), + ); + }, + ); + } +} + +Future _reportsTurn() async { + await Future.delayed(Duration.zero); + await Future.delayed(Duration.zero); +} diff --git a/test/core/fiber_listener_test.dart b/test/core/fiber_listener_test.dart new file mode 100644 index 0000000..112b921 --- /dev/null +++ b/test/core/fiber_listener_test.dart @@ -0,0 +1,200 @@ +import 'dart:async'; + +import 'package:any/any.dart'; +import 'package:test/test.dart'; + +void main() { + late Runtime runtime; + + setUp(() { + runtime = Runtime(); + addTearDown(runtime.close); + }); + + test('notifies after execution and owned cleanup finish', () async { + late void Function(Exit) complete; + final cleaning = Completer(); + final release = Completer(); + addTearDown(() { + if (!release.isCompleted) release.complete(); + }); + final events = []; + final seen = >[]; + final fiber = runtime.start( + Task.fromCallback((callback) { + complete = callback; + return () {}; + }).ensuring( + Task.fromFuture( + () { + events.add('cleaning'); + cleaning.complete(); + return release.future; + }, + onError: Error.throwWithStackTrace, + ).map((_) => events.add('cleaned')), + ), + ); + fiber.onExit((exit) { + seen.add(exit); + expect((fiber.poll() as OptionSome>).value, same(exit)); + events.add('notified'); + }); + + complete(const Exit.success(42)); + await cleaning.future; + expect(seen, isEmpty); + expect(fiber.poll(), isA>>()); + release.complete(); + final exit = await runtime.runOrThrow(fiber.awaitExit()); + + expect(events, ['cleaning', 'cleaned', 'notified']); + expect(seen, [same(exit)]); + expect((exit as ExitSuccess).value, 42); + }); + + test('late registration notifies before returning and only once', () { + final fiber = runtime.start(Task.succeed(42)); + final exit = (fiber.poll() as OptionSome>).value; + final events = []; + final seen = >[]; + + final remove = fiber.onExit((result) { + seen.add(result); + events.add('notified'); + }); + events.add('returned'); + remove(); + remove(); + fiber.requestCancel(); + + expect(events, ['notified', 'returned']); + expect(seen, [same(exit)]); + expect((fiber.poll() as OptionSome>).value, same(exit)); + }); + + test( + 'unsubscribe is idempotent and leaves other registrations and work', + () async { + late void Function(Exit) complete; + var cancellations = 0; + var notifications = 0; + final fiber = runtime.start( + Task.fromCallback((callback) { + complete = callback; + return () { + cancellations++; + }; + }), + ); + void listener(Exit exit) => notifications++; + final remove = fiber.onExit(listener); + fiber.onExit(listener); + + remove(); + remove(); + expect(fiber.poll(), isA>>()); + expect(cancellations, 0); + complete(const Exit.success(42)); + expect(await runtime.runOrThrow(fiber.join()), 42); + remove(); + + expect(notifications, 1); + expect(cancellations, 0); + }, + ); + + test( + 'a callback can remove another and register an immediate listener', + () async { + late void Function(Exit) complete; + late void Function() removeSecond; + final events = []; + final fiber = runtime.start( + Task.fromCallback((callback) { + complete = callback; + return () {}; + }), + ); + fiber.onExit((exit) { + events.add('first'); + removeSecond(); + final removeNested = fiber.onExit((nested) { + expect(nested, same(exit)); + events.add('nested'); + }); + removeNested(); + events.add('first returned'); + }); + removeSecond = fiber.onExit((_) => events.add('second')); + fiber.onExit((_) => events.add('third')); + + complete(const Exit.success(42)); + await runtime.runOrThrow(fiber.awaitExit()); + + expect(events, ['first', 'nested', 'first returned', 'third']); + }, + ); + + for (final completed in [false, true]) { + test('callbacks use their registration Zone and isolate errors ' + '(already completed: $completed)', () async { + late void Function(Exit) complete; + final fiber = completed + ? runtime.start(Task.succeed(42)) + : runtime.start( + Task.fromCallback((callback) { + complete = callback; + return () {}; + }), + ); + final key = Object(); + final zones = []; + final errors = <(Object, StackTrace)>[]; + final seen = >[]; + final error = StateError('listener failed'); + final stack = StackTrace.fromString('listener stack'); + late void Function() remove; + + runZoned( + () { + remove = fiber.onExit((exit) { + zones.add(Zone.current[key]); + seen.add(exit); + Error.throwWithStackTrace(error, stack); + }); + }, + zoneValues: {key: 'first'}, + zoneSpecification: ZoneSpecification( + handleUncaughtError: (self, parent, zone, error, stack) { + errors.add((error, stack)); + }, + ), + ); + runZoned( + () => fiber.onExit((exit) { + zones.add(Zone.current[key]); + seen.add(exit); + }), + zoneValues: {key: 'second'}, + ); + + if (!completed) { + expect(seen, isEmpty); + complete(const Exit.success(42)); + } else { + expect(zones, ['first', 'second']); + } + final exit = await runtime.runOrThrow(fiber.awaitExit()); + remove(); + remove(); + + expect(zones, ['first', 'second']); + expect(seen, [same(exit), same(exit)]); + expect(errors, hasLength(1)); + expect(errors.single.$1, same(error)); + expect(errors.single.$2.toString(), stack.toString()); + expect((exit as ExitSuccess).value, 42); + }); + } +} diff --git a/test/core/fiber_test.dart b/test/core/fiber_test.dart index fb97c55..bd271e6 100644 --- a/test/core/fiber_test.dart +++ b/test/core/fiber_test.dart @@ -88,7 +88,7 @@ void main() { expect((cause.causes.first as CauseFailure).error, 'business'); expect(cause.causes.last, same(defect)); await _reportsTurn(); - expect(reports, isEmpty); + expect((reports.single as CauseGroup).causes, hasLength(2)); }, ); @@ -264,33 +264,36 @@ void main() { expect(cause.causes, [same(defect), same(defect)]); }); - test('a cancelled waiter neither cancels nor observes its target', () async { - late void Function(Exit) complete; - var targetCancellations = 0; - final fiber = runtime.start( - Task.fromCallback((callback) { - complete = callback; - return () { - targetCancellations++; - }; - }), - ); - final controller = CancellationController(); - final waiting = runtime.run(fiber.awaitExit(), signal: controller.signal); - controller.requestCancel(reason: 'wait only'); - - expect((_cause(await waiting) as CauseCancelled).reason, 'wait only'); - expect(fiber.poll(), isA>>()); - expect(targetCancellations, 0); - complete(const Exit.failure(Cause.failure('unobserved'))); - await _reportsTurn(); - expect(reports, hasLength(1)); - expect((reports.single as CauseFailure).error, 'unobserved'); - expect(targetCancellations, 0); - }); + test( + 'a cancelled waiter leaves the target and its report route running', + () async { + late void Function(Exit) complete; + var targetCancellations = 0; + final fiber = runtime.start( + Task.fromCallback((callback) { + complete = callback; + return () { + targetCancellations++; + }; + }), + ); + final controller = CancellationController(); + final waiting = runtime.run(fiber.awaitExit(), signal: controller.signal); + controller.requestCancel(reason: 'wait only'); + + expect((_cause(await waiting) as CauseCancelled).reason, 'wait only'); + expect(fiber.poll(), isA>>()); + expect(targetCancellations, 0); + complete(const Exit.failure(Cause.failure('unobserved'))); + await _reportsTurn(); + expect(reports, hasLength(1)); + expect((reports.single as CauseFailure).error, 'unobserved'); + expect(targetCancellations, 0); + }, + ); test( - 'cancellation during exit handoff leaves its defect unobserved', + 'cancellation during exit handoff preserves independent reporting', () async { late void Function(Exit) complete; final defect = Cause.defect(Object(), StackTrace.current); @@ -331,9 +334,9 @@ void main() { }, ); - for (final completed in [false, true]) { - test('cancellation at a yield before exit consumption preserves reporting ' - '(already completed: $completed)', () async { + test( + 'another waiter can receive an exit without changing reporting', + () async { late void Function(Exit) complete; final defect = Cause.defect(Object(), StackTrace.current); final target = runtime.start( @@ -342,86 +345,38 @@ void main() { return () {}; }), ); - if (completed) { - complete(Exit.failure(defect)); - await _turn(); - expect(reports, isEmpty); - } - var task = target.awaitExit(); - final context = Context.from(const []); - // Put the completed wait immediately before the executor's cooperative - // yield, with only environment restoration before the consuming callback. - for (var i = 0; i < 2045; i++) { - task = task.provideContext(context); - } final controller = CancellationController(); - var intercepted = false; + var armed = false; var received = false; - final waiting = runZoned( + final cancelled = runZoned( () => runtime.run( - task.map((_) => received = true), + target.awaitExit().map((_) => received = true), signal: controller.signal, ), zoneSpecification: ZoneSpecification( - createTimer: (self, parent, zone, duration, callback) { - if (!intercepted && duration == Duration.zero) { - intercepted = true; - controller.requestCancel(reason: 'yield'); + scheduleMicrotask: (self, parent, zone, callback) { + if (armed) { + armed = false; + controller.requestCancel(); } - return parent.createTimer(zone, duration, callback); + parent.scheduleMicrotask(zone, callback); }, ), ); - if (!completed) complete(Exit.failure(defect)); + final observing = runtime.run(target.awaitExit()); + armed = true; + complete(Exit.failure(defect)); - expect((_cause(await waiting) as CauseCancelled).reason, 'yield'); - expect(intercepted, isTrue); + expect(_cause(await cancelled), isA()); expect(received, isFalse); + expect(_cause(_value(await observing)), same(defect)); await _reportsTurn(); expect(reports, [same(defect)]); - }); - } - - test('another waiter can observe an exit abandoned during handoff', () async { - late void Function(Exit) complete; - final defect = Cause.defect(Object(), StackTrace.current); - final target = runtime.start( - Task.fromCallback((callback) { - complete = callback; - return () {}; - }), - ); - final controller = CancellationController(); - var armed = false; - var received = false; - final cancelled = runZoned( - () => runtime.run( - target.awaitExit().map((_) => received = true), - signal: controller.signal, - ), - zoneSpecification: ZoneSpecification( - scheduleMicrotask: (self, parent, zone, callback) { - if (armed) { - armed = false; - controller.requestCancel(); - } - parent.scheduleMicrotask(zone, callback); - }, - ), - ); - final observing = runtime.run(target.awaitExit()); - armed = true; - complete(Exit.failure(defect)); - - expect(_cause(await cancelled), isA()); - expect(received, isFalse); - expect(_cause(_value(await observing)), same(defect)); - await _reportsTurn(); - expect(reports, isEmpty); - }); + }, + ); test( - 'cancellation after exit consumption keeps the result observed', + 'cancellation after exit delivery does not suppress reporting', () async { final defect = Cause.defect(Object(), StackTrace.current); final target = runtime.start(Task.failCause(defect)); @@ -438,7 +393,7 @@ void main() { expect(_cause(seen.single), same(defect)); expect((_cause(exit) as CauseCancelled).reason, 'after consumption'); await _reportsTurn(); - expect(reports, isEmpty); + expect(reports, [same(defect)]); }, ); @@ -474,7 +429,7 @@ void main() { expect(cause.causes.whereType(), [same(defect)]); expect(cause.causes.whereType(), hasLength(1)); await _reportsTurn(); - expect(reports, isEmpty); + expect(reports, [same(defect)]); }, ); @@ -499,7 +454,7 @@ void main() { await cleaning.future; if (cancel) controller.requestCancel(reason: 'cleanup'); await _reportsTurn(); - expect(reports, isEmpty); + expect(reports, [same(defect)]); cleaned.complete(); final exit = await waiting; @@ -509,47 +464,10 @@ void main() { expect(_cause(_value(exit)), same(defect)); } await _reportsTurn(); - expect(reports, cancel ? [same(defect)] : isEmpty); + expect(reports, [same(defect)]); }); } - for (final wrapper in ['scoped', 'exit', 'context', 'local', 'mask']) { - test( - '$wrapper does not consume an exit before cleanup completes', - () async { - final defect = Cause.defect(Object(), StackTrace.current); - final target = runtime.start(Task.failCause(defect)); - final controller = CancellationController(); - final cleaning = Completer(); - final cleaned = Completer(); - addTearDown(() { - if (!cleaned.isCompleted) cleaned.complete(); - }); - final source = Task.addFinalizer((_) { - cleaning.complete(); - return _future(cleaned.future); - }).flatMap((_) => target.awaitExit()); - final Task task = switch (wrapper) { - 'scoped' => source.scoped(), - 'exit' => source.exit(), - 'context' => source.provideContext(Context.from(const [])), - 'local' => TaskLocal(0).locally(1, source), - _ => Task.uninterruptibleMask((restore) => restore(source)), - }; - final waiting = runtime.run(task, signal: controller.signal); - await cleaning.future; - controller.requestCancel(reason: 'cleanup'); - await _reportsTurn(); - expect(reports, isEmpty); - cleaned.complete(); - - expect((_cause(await waiting) as CauseCancelled).reason, 'cleanup'); - await _reportsTurn(); - expect(reports, [same(defect)]); - }, - ); - } - for (final scoped in [false, true]) { test('directly returning a child exit excludes its owned cleanup defect ' '(scoped: $scoped)', () async { @@ -591,7 +509,7 @@ void main() { } test( - 'recovering cleanup failure does not observe a discarded exit', + 'recovering waiter cleanup does not handle the target failure', () async { final defect = Cause.defect(Object(), StackTrace.current); final cleanup = Cause.defect(Object(), StackTrace.current); @@ -940,11 +858,11 @@ void main() { expect((_cause(exit) as CauseDefect).error, isA()); expect(started, isFalse); await _reportsTurn(); - expect(reports, isEmpty); + expect((reports.single as CauseDefect).error, isA()); }); test( - 'unobserved business failures report once without waiting for shutdown', + 'independent business failures report once without waiting for shutdown', () async { final fiber = runtime.start(Task.fail('unobserved')); await _reportsTurn(); @@ -962,7 +880,7 @@ void main() { }, ); - test('constructing a wait does not count as observing a failure', () async { + test('constructing a wait does not change failure reporting', () async { final fiber = runtime.start(Task.fail('not executed')); fiber.awaitExit(); fiber.join(); @@ -971,13 +889,16 @@ void main() { expect(reports, hasLength(1)); }); - test('a completed poll suppresses an unhandled failure report', () async { - final fiber = runtime.start(Task.fail('observed')); - expect(fiber.poll(), isA>>()); - await _reportsTurn(); + test( + 'a completed poll leaves independent failure reporting unchanged', + () async { + final fiber = runtime.start(Task.fail('observed')); + expect(fiber.poll(), isA>>()); + await _reportsTurn(); - expect(reports, isEmpty); - }); + expect((reports.single as CauseFailure).error, 'observed'); + }, + ); test( 'cancellation-only exits are not reported as unhandled errors', @@ -992,7 +913,7 @@ void main() { ); test( - 'owner shutdown handles defects while retaining unobserved business errors', + 'owner shutdown receives defects while business failures are reported', () async { final gate = Completer(); addTearDown(() { diff --git a/test/core/layer_start_test.dart b/test/core/layer_start_test.dart index 0380572..6db6291 100644 --- a/test/core/layer_start_test.dart +++ b/test/core/layer_start_test.dart @@ -17,6 +17,7 @@ void main() { deferStart: true, signal: controller.signal, report: (_) => fail('Unexpected report'), + reportFailure: false, ); expect(started, isFalse); controller.requestCancel(reason: 'before start'); @@ -41,6 +42,7 @@ void main() { context: Context.from([]), deferStart: true, report: (_) => fail('Unexpected report'), + reportFailure: false, ); final closed = scopes.closeScope(owner, const Exit.success(null)); expect(await closed, isNull); diff --git a/test/core/native_async_test.dart b/test/core/native_async_test.dart index 2de3e8f..55323ab 100644 --- a/test/core/native_async_test.dart +++ b/test/core/native_async_test.dart @@ -170,7 +170,7 @@ void main() { ); test( - 'a host Future timeout neither cancels nor unobserves Runtime.run', + 'a host Future timeout leaves Runtime.run as the result receiver', () async { final native = _NativeCall(); addTearDown(native.finish); @@ -255,7 +255,17 @@ void main() { expect(client.releases, 1); expect(cancellations, 1); await Future.delayed(Duration.zero); - expect(reports, isEmpty); + if (stopFails) { + expect( + (reports.single as CauseGroup).causes + .whereType() + .single + .error, + same(error), + ); + } else { + expect(reports, isEmpty); + } }, ); } diff --git a/test/core/task_lifetime_test.dart b/test/core/task_lifetime_test.dart index b16c268..1baf23b 100644 --- a/test/core/task_lifetime_test.dart +++ b/test/core/task_lifetime_test.dart @@ -347,6 +347,9 @@ void main() { ); test('borrowed child and lexical cleanup failures remain distinct', () async { + final reports = >[]; + final runtime = Runtime(onUnhandledError: reports.add); + addTearDown(runtime.close); final ready = Completer(); final started = Completer(); final defect = Cause.defect(Object(), StackTrace.current); @@ -376,6 +379,11 @@ void main() { final causes = (result.cause as CauseGroup).causes; expect(causes.whereType(), hasLength(1)); expect(causes.whereType(), [same(defect), same(defect)]); + await Future.delayed(Duration.zero); + expect((reports.single as CauseGroup).causes.whereType(), [ + same(defect), + same(defect), + ]); }); test(