From 551c566225226444916904525fe69fe0d2b41973 Mon Sep 17 00:00:00 2001 From: Reuben Bond Date: Wed, 18 Nov 2026 08:55:30 -0800 Subject: [PATCH 1/4] feat: discard stopped member work --- README.md | 12 ++ docs/compatibility.md | 23 +++- .../Nodes/SimulationNodeContext.cs | 121 ++++++++++++++++-- .../Runtime/Scheduling/SimulationScheduler.cs | 61 +++++++++ .../Scheduling/SimulationSchedulerLane.cs | 59 ++++++++- 5 files changed, 262 insertions(+), 14 deletions(-) diff --git a/README.md b/README.md index cb46fc7..b2989af 100644 --- a/README.md +++ b/README.md @@ -284,6 +284,18 @@ cleanup applies when an attachment fails. Disposing the cluster from inside an `AddCustomNode` factory is unsupported and throws without changing the cluster's state. Clockwork does not provide `IHost` integration. +After a consumer has stopped or crashed a member and completed any member-specific shutdown it +requires, call `node.Context.DiscardPendingWork()` to remove that member's remaining work instead of +allowing cluster disposal to drain it. The call permanently transitions the context to +`SimulationNodeState.Discarded`; it cancels ready and delayed lane callbacks, timers and virtual +deadlines, controlled operations and resource waits, and context-owned shared callbacks such as a +`SuspendFor` resume. Their callbacks do not run, their deadlines do not advance virtual time, and +pending-work diagnostics no longer include them. Other members and cluster-level work are unchanged. +The call is idempotent while the context is attached. New node-owned work is rejected with +`ObjectDisposedException`, calling it from a callback currently running for that node throws +`InvalidOperationException` without changing the node, and calling it after cluster disposal throws +`ObjectDisposedException`. Ordinary nodes retain the disposal-drains behavior above. + ## Drive simulated execution ```csharp diff --git a/docs/compatibility.md b/docs/compatibility.md index 14301d5..748486d 100644 --- a/docs/compatibility.md +++ b/docs/compatibility.md @@ -91,8 +91,27 @@ stops idle workers, and joins every worker before returning. `TeardownCancellationToken`, drives pending lane callbacks and node-disposal work to quiescence, and advances virtual time to scheduled deadlines when required, subject to the configured execution bounds. Pending work is completed rather than discarded; callback and disposal failures are collected -after cleanup. Call a drive method with an explicit execution bound before disposal when teardown must -not advance beyond that bound. +after cleanup. + +`SimulationNodeContext.DiscardPendingWork()` is the explicit escape hatch for a member which the +consumer has already stopped or crashed. The scheduler's node identity is the ownership boundary: the +call cancels that node's ready and delayed lane callbacks, callback timers and virtual deadlines, +controlled operations (including readiness continuations), resource waits and their timeout/cancellation +registrations, plus context-owned shared callbacks such as the cluster-lane resume registered by +`SuspendFor`. Cancellation unwinds parked controlled-operation stacks cooperatively and releases their +workers; it does not invoke the discarded callbacks. Work owned by other nodes or by the cluster is +unchanged, discarded work disappears from pending-work diagnostics, and its deadlines cannot advance +virtual time during later cluster disposal. + +Discard is a permanent lifecycle transition to `SimulationNodeState.Discarded`. It is idempotent while +the context remains attached, and every later node-owned enqueue is rejected with +`ObjectDisposedException`, including task-scheduler, synchronization-context, timer, continuation, and +direct scheduler paths. A node cannot discard itself from one of its currently running callbacks: +that call throws `InvalidOperationException` before changing state. Suspended nodes may be discarded. +After cluster disposal detaches the context, discard throws `ObjectDisposedException`. The consumer +must complete any shutdown or disposal logic which needs to schedule node work before discarding it; +the cluster still invokes the node object's disposer, but node-scoped scheduling from that disposer is +rejected. Nodes which are not explicitly discarded retain the draining teardown behavior. The reusable resource model provides stable resource identities, ownership and capacity metadata, deterministic waiter queues, atomic pause/wakeup, virtual-time deadlines, synchronous cancellation, diff --git a/src/Orleans.Testing.Simulation/Nodes/SimulationNodeContext.cs b/src/Orleans.Testing.Simulation/Nodes/SimulationNodeContext.cs index 073b7b4..280972a 100644 --- a/src/Orleans.Testing.Simulation/Nodes/SimulationNodeContext.cs +++ b/src/Orleans.Testing.Simulation/Nodes/SimulationNodeContext.cs @@ -1,4 +1,5 @@ using System.Diagnostics; +using System.Runtime.ExceptionServices; using Orleans.Testing.Simulation.Runtime.Execution; using Orleans.Testing.Simulation.Runtime.Scheduling; using Microsoft.Extensions.Logging; @@ -22,6 +23,11 @@ public enum SimulationNodeState /// Timers will accumulate and fire when the node is resumed if their due time has passed. /// Suspended, + + /// + /// The node has explicitly discarded all pending work and cannot accept new work. + /// + Discarded, } internal enum SimulationNodeAttachmentState @@ -143,7 +149,7 @@ public bool HasReadyTasks { get { - if (State == SimulationNodeState.Suspended) + if (State != SimulationNodeState.Running) return false; // Check if the lane has any items due at or before the current time @@ -159,7 +165,8 @@ public bool HasReadyTasks /// Gets the due time of the next waiting (not yet ready) task on this node's lane, /// or null if no tasks are waiting. /// - public DateTimeOffset? NextWaitingDueTime => SchedulerLane.NextWaitingDueTime; + public DateTimeOffset? NextWaitingDueTime => + State == SimulationNodeState.Discarded ? null : SchedulerLane.NextWaitingDueTime; /// /// Executes one ready task from this node's lane. @@ -171,6 +178,7 @@ public bool HasReadyTasks public bool Step(CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); + ThrowIfPendingWorkDiscarded(); if (State == SimulationNodeState.Suspended) return false; @@ -187,6 +195,7 @@ public bool Step(CancellationToken cancellationToken) public int RunUntilIdle(CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); + ThrowIfPendingWorkDiscarded(); if (State == SimulationNodeState.Suspended) return 0; @@ -200,7 +209,7 @@ public int RunUntilIdle(CancellationToken cancellationToken) public void Suspend() { using var _ = _guard.Enter(); - ThrowIfDetached(); + ThrowIfUnavailable(); State = SimulationNodeState.Suspended; if (_attachmentState != SimulationNodeAttachmentState.Disposing) { @@ -217,7 +226,7 @@ public void Suspend() public void Resume() { using var _ = _guard.Enter(); - ThrowIfDetached(); + ThrowIfUnavailable(); State = SimulationNodeState.Running; if (_attachmentState != SimulationNodeAttachmentState.Disposing) { @@ -243,7 +252,7 @@ public void SuspendFor(TimeSpan duration) ArgumentOutOfRangeException.ThrowIfLessThanOrEqual(duration, TimeSpan.Zero); using var _ = _guard.Enter(); - ThrowIfDetached(); + ThrowIfUnavailable(); if (_externalSchedulerLane is null) { throw new InvalidOperationException( @@ -280,6 +289,80 @@ public void SuspendFor(TimeSpan duration) } } + /// + /// Permanently discards every pending unit of work owned by this node. + /// + /// + /// + /// Call this only after the simulated member has stopped. Ready and delayed scheduler-lane + /// callbacks, timers and virtual deadlines, controlled operations and resource waits, and + /// cluster-lane callbacks owned by this context (such as a timed-suspension resume) are canceled + /// without invoking their callbacks. Work owned by other nodes or by the cluster is unchanged. + /// + /// + /// The transition is permanent and idempotent while the context remains attached. The context + /// enters , and later attempts to enqueue node-owned + /// work throw . Calling this from work currently executing + /// for this node throws without discarding anything. + /// After the containing cluster has detached the context, this method throws + /// . + /// + /// + public void DiscardPendingWork() + { + using IDisposable? control = Scheduler.CurrentOperation is null + ? Scheduler.EnterControlScope() + : null; + ScheduledItem[] laneItems; + ScheduledItem[] sharedLaneItems; + Exception? schedulerFailure = null; + using (var _ = _guard.Enter()) + { + ThrowIfDetached(); + SimulationNodeIdentity node = SchedulerLane.Node + ?? throw new InvalidOperationException("The scheduler lane is not node-scoped."); + if (State == SimulationNodeState.Discarded) + { + laneItems = SchedulerLane.CaptureItems(); + sharedLaneItems = []; + } + else + { + Scheduler.EnsureNodeCanDiscardPendingWork(node); + State = SimulationNodeState.Discarded; + laneItems = SchedulerLane.MarkPendingWorkDiscarded(); + sharedLaneItems = [.. _sharedLaneItems]; + _sharedLaneItems.Clear(); + } + + try + { + Scheduler.DiscardPendingWork(node); + } + catch (Exception exception) + { + schedulerFailure = exception; + } + } + + try + { + CancelScheduledItems(laneItems, sharedLaneItems); + } + catch (Exception cancellationFailure) when (schedulerFailure is not null) + { + throw new AggregateException( + "Simulation node pending-work discard failed during scheduler and lane cleanup.", + schedulerFailure, + cancellationFailure).Flatten(); + } + + if (schedulerFailure is not null) + { + ExceptionDispatchInfo.Capture(schedulerFailure).Throw(); + } + } + internal bool IsAttachmentInProgress { get @@ -294,6 +377,11 @@ internal bool HasPendingAttachmentWork get { using var _ = _guard.Enter(); + if (State == SimulationNodeState.Discarded) + { + return false; + } + return SchedulerLane.HasPendingWork || _sharedLaneItems.Count > 0; } } @@ -328,8 +416,11 @@ internal void BeginAttachmentCleanup() } _attachmentState = SimulationNodeAttachmentState.Disposing; - State = SimulationNodeState.Running; - SchedulerLane.SetEnabled(enabled: true); + if (State != SimulationNodeState.Discarded) + { + State = SimulationNodeState.Running; + SchedulerLane.SetEnabled(enabled: true); + } } internal void CompleteAttachmentCleanup() @@ -347,7 +438,10 @@ internal void CompleteAttachmentCleanup() laneItems = SchedulerLane.Detach(); sharedLaneItems = [.. _sharedLaneItems]; _sharedLaneItems.Clear(); - State = SimulationNodeState.Running; + if (State != SimulationNodeState.Discarded) + { + State = SimulationNodeState.Running; + } } CancelScheduledItems(laneItems, sharedLaneItems); @@ -405,6 +499,17 @@ private void ThrowIfDetached() => _attachmentState == SimulationNodeAttachmentState.Detached, this); + private void ThrowIfPendingWorkDiscarded() => + ObjectDisposedException.ThrowIf( + State == SimulationNodeState.Discarded, + this); + + private void ThrowIfUnavailable() + { + ThrowIfDetached(); + ThrowIfPendingWorkDiscarded(); + } + private string DebuggerDisplay => $"SimulationNodeContext({State}, Tasks={SchedulerLane.CaptureScheduledItems().Count})"; diff --git a/src/Orleans.Testing.Simulation/Runtime/Scheduling/SimulationScheduler.cs b/src/Orleans.Testing.Simulation/Runtime/Scheduling/SimulationScheduler.cs index 7536214..bb1ce34 100644 --- a/src/Orleans.Testing.Simulation/Runtime/Scheduling/SimulationScheduler.cs +++ b/src/Orleans.Testing.Simulation/Runtime/Scheduling/SimulationScheduler.cs @@ -77,6 +77,7 @@ public sealed class SimulationScheduler : IDisposable private readonly List _activeOperations = []; private readonly SortedDictionary _resources = new(); private readonly HashSet _suspendedNodes = new(StringComparer.Ordinal); + private readonly HashSet _discardedNodes = new(StringComparer.Ordinal); private readonly SemaphoreSlim _handback = new(0, 1); private readonly SimulationLogicalExecutionIdSource _logicalIds = new(); private readonly SimulationTimerQueue _clock = new(); @@ -596,6 +597,7 @@ private SimulationOperation RegisterCore( lock (_gate) { ThrowIfDisposed(); + ThrowIfNodeDiscardedUnderLock(node); SimulationOperation? parent = t_currentOperation is { } currentParent && ReferenceEquals(currentParent.Scheduler, this) ? currentParent @@ -746,6 +748,7 @@ internal ISimulationTimer RegisterTimer( lock (_gate) { ThrowIfDisposed(); + ThrowIfNodeDiscardedUnderLock(snapshot.Node); Action? scheduleCallback = onElapsed is null ? null : () => Schedule( @@ -781,6 +784,7 @@ internal IDisposable ScheduleAfter( lock (_gate) { ThrowIfDisposed(); + ThrowIfNodeDiscardedUnderLock(snapshot.Node); timer = _clock.Schedule( delay, () => registration.Schedule( @@ -1486,6 +1490,48 @@ internal bool HasPendingWork(SimulationNodeIdentity node) } } + internal void EnsureNodeCanDiscardPendingWork(SimulationNodeIdentity node) + { + ArgumentNullException.ThrowIfNull(node); + lock (_gate) + { + ThrowIfDisposed(); + if (_discardedNodes.Contains(node.Address)) + { + return; + } + + if (HasRunningOperationUnderLock(node)) + { + throw new InvalidOperationException( + string.Create( + CultureInfo.InvariantCulture, + $"Cannot discard pending work for simulation node '{node.Address}' while one of its callbacks is running.")); + } + } + } + + internal void DiscardPendingWork(SimulationNodeIdentity node) + { + ArgumentNullException.ThrowIfNull(node); + lock (_gate) + { + ThrowIfDisposed(); + if (HasRunningOperationUnderLock(node)) + { + throw new InvalidOperationException( + string.Create( + CultureInfo.InvariantCulture, + $"Cannot discard pending work for simulation node '{node.Address}' while one of its callbacks is running.")); + } + + _discardedNodes.Add(node.Address); + _suspendedNodes.Remove(node.Address); + } + + RemovePendingWork(node); + } + internal void RemovePendingWork(SimulationNodeIdentity node) { ArgumentNullException.ThrowIfNull(node); @@ -3302,6 +3348,21 @@ private void Notify(SimulationOperation operation, SimulationOperationState stat private void ThrowIfDisposed() => ObjectDisposedException.ThrowIf(_disposed, this); + private void ThrowIfNodeDiscardedUnderLock(SimulationNodeIdentity? node) + { + if (node is { } identity && _discardedNodes.Contains(identity.Address)) + { + throw new ObjectDisposedException( + identity.Address, + "The simulation node discarded its pending work and cannot accept new work."); + } + } + + private bool HasRunningOperationUnderLock(SimulationNodeIdentity node) => + _activeOperations.Any( + operation => operation.Node == node + && operation.State == SimulationOperationState.Running); + private sealed class ReadinessWait : ISimulationWorkRegistration { private readonly SimulationScheduler _scheduler; diff --git a/src/Orleans.Testing.Simulation/Scheduling/SimulationSchedulerLane.cs b/src/Orleans.Testing.Simulation/Scheduling/SimulationSchedulerLane.cs index 720c2ea..a97ba92 100644 --- a/src/Orleans.Testing.Simulation/Scheduling/SimulationSchedulerLane.cs +++ b/src/Orleans.Testing.Simulation/Scheduling/SimulationSchedulerLane.cs @@ -21,6 +21,7 @@ public sealed class SimulationSchedulerLane private readonly SimulationSynchronizationContext _synchronizationContext; private long _sequenceNumber; private bool _enabled = true; + private bool _pendingWorkDiscarded; private volatile bool _detached; /// Initializes a lane owned by . @@ -64,7 +65,9 @@ public SimulationSynchronizationContext SynchronizationContext internal bool IsDetached => _detached; internal bool HasPendingWork => - _node is { } node ? _scheduler.HasPendingWork(node) : HasItems; + _pendingWorkDiscarded + ? false + : _node is { } node ? _scheduler.HasPendingWork(node) : HasItems; /// Gets whether this lane has pending items. public bool HasItems @@ -73,6 +76,11 @@ public bool HasItems { using var _ = _guard.Enter(); ThrowIfDetachedUnderGuard(); + if (_pendingWorkDiscarded) + { + return false; + } + return _items.Count > 0; } } @@ -84,6 +92,11 @@ public DateTimeOffset? NextWaitingDueTime { using var _ = _guard.Enter(); ThrowIfDetachedUnderGuard(); + if (_pendingWorkDiscarded) + { + return null; + } + var now = _scheduler.UtcNow; foreach (var item in _items) { @@ -127,6 +140,7 @@ private void Schedule(ScheduledItem item, TimeSpan delay) using var _ = _guard.Enter(); ThrowIfDetachedUnderGuard(); + ThrowIfPendingWorkDiscardedUnderGuard(); var dueTime = _scheduler.UtcNow + delay; item.OnScheduled(this, dueTime, _sequenceNumber++); _items.Add(item); @@ -158,6 +172,11 @@ public IReadOnlyList CaptureScheduledItems() { using var _ = _guard.Enter(); ThrowIfDetachedUnderGuard(); + if (_pendingWorkDiscarded) + { + return []; + } + var now = _scheduler.UtcNow; var queueIdentity = _node?.Address ?? "cluster"; var result = new SimulationScheduledItemDiagnostic[_items.Count]; @@ -219,7 +238,7 @@ private void Execute(ScheduledItem item) /// A token checked before dispatching the operation. public bool RunOnce(CancellationToken cancellationToken) { - ThrowIfDetached(); + ThrowIfUnavailable(); using var control = _scheduler.EnterControlScope(); return _scheduler.RunStep(cancellationToken); } @@ -228,7 +247,7 @@ public bool RunOnce(CancellationToken cancellationToken) /// A token that can cancel the run between scheduler dispatches. public int RunUntilIdle(CancellationToken cancellationToken) { - ThrowIfDetached(); + ThrowIfUnavailable(); using var control = _scheduler.EnterControlScope(); return _scheduler.RunUntilIdle(cancellationToken); } @@ -237,6 +256,7 @@ internal void SetEnabled(bool enabled) { using var _ = _guard.Enter(); ThrowIfDetachedUnderGuard(); + ThrowIfPendingWorkDiscardedUnderGuard(); _enabled = enabled; if (_node is { } node) { @@ -253,7 +273,7 @@ internal ScheduledItem[] Detach() } _detached = true; - if (_node is { } node) + if (!_pendingWorkDiscarded && _node is { } node) { _scheduler.RemovePendingWork(node); } @@ -261,18 +281,49 @@ internal ScheduledItem[] Detach() return [.. _items]; } + internal ScheduledItem[] MarkPendingWorkDiscarded() + { + using var _ = _guard.Enter(); + ThrowIfDetachedUnderGuard(); + if (_pendingWorkDiscarded) + { + return []; + } + + _pendingWorkDiscarded = true; + _enabled = false; + return [.. _items]; + } + private void ThrowIfDetached() { using var _ = _guard.Enter(); ThrowIfDetachedUnderGuard(); } + private void ThrowIfUnavailable() + { + using var _ = _guard.Enter(); + ThrowIfDetachedUnderGuard(); + ThrowIfPendingWorkDiscardedUnderGuard(); + } + private void ThrowIfDetachedWithoutGuard() => ObjectDisposedException.ThrowIf(_detached, this); private void ThrowIfDetachedUnderGuard() => ObjectDisposedException.ThrowIf(_detached, this); + private void ThrowIfPendingWorkDiscardedUnderGuard() + { + if (_pendingWorkDiscarded) + { + throw new ObjectDisposedException( + nameof(SimulationSchedulerLane), + "The owning simulation node discarded its pending work and cannot accept new work."); + } + } + private string DebuggerDisplay { get From b654bddfb79858423c687e99e922a514de337b63 Mon Sep 17 00:00:00 2001 From: Reuben Bond Date: Wed, 18 Nov 2026 08:57:02 -0800 Subject: [PATCH 2/4] fix: seal discarded node scheduling --- README.md | 3 ++- docs/compatibility.md | 5 +++-- .../Cluster/SimulationCluster.cs | 7 ++++--- .../Runtime/Scheduling/SimulationScheduler.cs | 10 ++++++++++ 4 files changed, 19 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index b2989af..159e060 100644 --- a/README.md +++ b/README.md @@ -290,7 +290,8 @@ allowing cluster disposal to drain it. The call permanently transitions the cont `SimulationNodeState.Discarded`; it cancels ready and delayed lane callbacks, timers and virtual deadlines, controlled operations and resource waits, and context-owned shared callbacks such as a `SuspendFor` resume. Their callbacks do not run, their deadlines do not advance virtual time, and -pending-work diagnostics no longer include them. Other members and cluster-level work are unchanged. +pending-work diagnostics no longer include them. Other members and cluster-level work are unchanged, +and discarded nodes are excluded from `SimulationCluster.ActiveNodes`. The call is idempotent while the context is attached. New node-owned work is rejected with `ObjectDisposedException`, calling it from a callback currently running for that node throws `InvalidOperationException` without changing the node, and calling it after cluster disposal throws diff --git a/docs/compatibility.md b/docs/compatibility.md index 748486d..6df8649 100644 --- a/docs/compatibility.md +++ b/docs/compatibility.md @@ -100,8 +100,9 @@ controlled operations (including readiness continuations), resource waits and th registrations, plus context-owned shared callbacks such as the cluster-lane resume registered by `SuspendFor`. Cancellation unwinds parked controlled-operation stacks cooperatively and releases their workers; it does not invoke the discarded callbacks. Work owned by other nodes or by the cluster is -unchanged, discarded work disappears from pending-work diagnostics, and its deadlines cannot advance -virtual time during later cluster disposal. +unchanged, discarded nodes are excluded from `SimulationCluster.ActiveNodes`, discarded work disappears +from pending-work diagnostics, and its deadlines cannot advance virtual time during later cluster +disposal. Discard is a permanent lifecycle transition to `SimulationNodeState.Discarded`. It is idempotent while the context remains attached, and every later node-owned enqueue is rejected with diff --git a/src/Orleans.Testing.Simulation/Cluster/SimulationCluster.cs b/src/Orleans.Testing.Simulation/Cluster/SimulationCluster.cs index 5aaa43b..59891aa 100644 --- a/src/Orleans.Testing.Simulation/Cluster/SimulationCluster.cs +++ b/src/Orleans.Testing.Simulation/Cluster/SimulationCluster.cs @@ -219,10 +219,11 @@ internal SimulationCluster( public IReadOnlyList Nodes => [.. _nodes.Values]; /// - /// Gets all active (non-suspended) nodes in the simulation (snapshot). - /// Suspended nodes cannot process messages and are excluded from convergence checks. + /// Gets all running nodes in the simulation (snapshot). + /// Suspended and discarded nodes cannot process messages and are excluded from convergence checks. /// - public IReadOnlyList ActiveNodes => [.. _nodes.Values.Where(n => !n.IsSuspended)]; + public IReadOnlyList ActiveNodes => + [.. _nodes.Values.Where(static node => node.Context.State == SimulationNodeState.Running)]; /// /// Gets the simulated network for this cluster. The network is available immediately, including diff --git a/src/Orleans.Testing.Simulation/Runtime/Scheduling/SimulationScheduler.cs b/src/Orleans.Testing.Simulation/Runtime/Scheduling/SimulationScheduler.cs index bb1ce34..d97f81f 100644 --- a/src/Orleans.Testing.Simulation/Runtime/Scheduling/SimulationScheduler.cs +++ b/src/Orleans.Testing.Simulation/Runtime/Scheduling/SimulationScheduler.cs @@ -725,6 +725,15 @@ internal ISimulationWorkRegistration ScheduleWhenReady( lock (_gate) { ThrowIfDisposed(); + ThrowIfNodeDiscardedUnderLock(snapshot.Node); + if (operation.IsTerminal) + { + throw new SimulationSchedulerException( + string.Create( + CultureInfo.InvariantCulture, + $"Cannot schedule readiness work for terminal operation {operation.Id}.")); + } + _readinessWaits.Add(wait); } @@ -971,6 +980,7 @@ public void Admit(SimulationOperation operation) lock (_gate) { ThrowIfDisposed(); + ThrowIfNodeDiscardedUnderLock(operation.Node); operation.ApplyTransition(SimulationOperationState.Runnable); } From a9dffc063c11cbef05df4255cf4ae00836a1717f Mon Sep 17 00:00:00 2001 From: Reuben Bond Date: Wed, 18 Nov 2026 09:01:30 -0800 Subject: [PATCH 3/4] test: cover discarded member work --- .../SimulationSchedulerNodeDiscardTests.cs | 426 ++++++++++++++++++ .../SimulationNodeDiscardTests.cs | 221 +++++++++ 2 files changed, 647 insertions(+) create mode 100644 tests/Clockwork.Runtime.Tests/Scheduling/SimulationSchedulerNodeDiscardTests.cs create mode 100644 tests/Clockwork.Tests/SimulationNodeDiscardTests.cs diff --git a/tests/Clockwork.Runtime.Tests/Scheduling/SimulationSchedulerNodeDiscardTests.cs b/tests/Clockwork.Runtime.Tests/Scheduling/SimulationSchedulerNodeDiscardTests.cs new file mode 100644 index 0000000..2d0ef4b --- /dev/null +++ b/tests/Clockwork.Runtime.Tests/Scheduling/SimulationSchedulerNodeDiscardTests.cs @@ -0,0 +1,426 @@ +using Orleans.Testing.Simulation.Runtime.Decisions; +using Orleans.Testing.Simulation.Runtime.Execution; +using Orleans.Testing.Simulation.Runtime.Scheduling; +using Orleans.Testing.Simulation.Runtime.Scheduling.Resources; +using Orleans.Testing.Simulation.Runtime.Tasks; +using Orleans.Testing.Simulation.Runtime.Tests.Tasks; +using Orleans.Testing.Simulation.Shims.System.Threading.Tasks; + +namespace Orleans.Testing.Simulation.Runtime.Tests.Scheduling; + +public sealed class SimulationSchedulerNodeDiscardTests +{ + [Fact] + public void DiscardPendingWorkCancelsControlledDelayAndWaitAsyncDeadlines() + { + using var host = new SimulationSchedulerTestHost(); + var node = new SimulationNodeIdentity(TaskTestHarness.DefaultNodeAddress); + SimulationNodeContext context = CreateContext(host.Scheduler, node); + var source = new TaskCompletionSource(); + + TaskTestHarness.RunInSimulation(host, () => + { + Task delay = ControlledTask.Delay( + TimeSpan.FromMinutes(9), + TestContext.Current.CancellationToken); + Task wait = ControlledTask.WaitAsync( + source.Task, + TimeSpan.FromMinutes(11), + TestContext.Current.CancellationToken); + Assert.Equal(2, host.Scheduler.PendingTimerRegistrationCount); + Assert.Equal(1, host.Scheduler.WaitingOperationCount); + + context.DiscardPendingWork(); + source.SetResult(); + int steps = host.Scheduler.RunUntilIdle(TestContext.Current.CancellationToken); + + Assert.Equal(SimulationNodeState.Discarded, context.State); + Assert.False(delay.IsCompleted); + Assert.False(wait.IsCompleted); + Assert.Equal(0, steps); + Assert.Null(host.Scheduler.NextTimerDue); + Assert.Equal(0, host.Scheduler.PendingTimerRegistrationCount); + Assert.Equal(0, host.Scheduler.WaitingOperationCount); + Assert.Equal(0, host.Scheduler.PendingOperationCount); + Assert.Equal(TimeSpan.Zero, host.Scheduler.VirtualTime); + }); + } + + [Fact] + public void DiscardPendingWorkCancelsNodeReadinessAndResourcePausedOperations() + { + using var scheduler = SchedulerTestHarness.NewScheduler(); + var node = new SimulationNodeIdentity("node-1"); + SimulationNodeContext context = CreateContext(scheduler, node); + var readinessReached = false; + var readinessCallbackRan = false; + var afterWaitRan = false; + using var cancellation = new CancellationTokenSource(); + SimulationResource resource = scheduler.CreateResource( + SimulationResourceKind.Semaphore, + "node-resource"); + _ = scheduler.ScheduleWhenReady( + node, + () => readinessReached, + () => readinessCallbackRan = true); + SimulationOperation resourceOperation = scheduler.Schedule( + "node-resource-wait", + () => + { + _ = scheduler.WaitOnResource( + resource, + TimeSpan.FromMinutes(5), + SimulationPauseReason.ResourceWait("node-resource"), + cancellation.Token); + afterWaitRan = true; + }, + node); + + Assert.True(scheduler.RunStep(TestContext.Current.CancellationToken)); + Assert.Equal(SimulationOperationState.Paused, resourceOperation.State); + Assert.Equal(1, resource.WaiterCount); + Assert.Single(scheduler.CapturePendingTimeouts()); + Thread resourceWorker = resourceOperation.Thread!; + + context.DiscardPendingWork(); + readinessReached = true; + cancellation.Cancel(); + + Assert.Equal(SimulationNodeState.Discarded, context.State); + Assert.Equal(SimulationOperationState.Canceled, resourceOperation.State); + Assert.Null(resourceOperation.Thread); + Assert.False(readinessCallbackRan); + Assert.False(afterWaitRan); + Assert.Equal(0, resource.WaiterCount); + Assert.Empty(scheduler.CapturePendingTimeouts()); + Assert.Null(scheduler.SignalOne(resource)); + Assert.Equal(0, scheduler.PendingOperationCount); + Assert.All( + scheduler.CaptureStatus().Where(status => status.NodeAddress == node.Address), + status => Assert.Equal(SimulationOperationState.Canceled, status.State)); + Assert.Equal(1, scheduler.IdleWorkerThreadCount); + + scheduler.Dispose(); + Assert.False(resourceWorker.IsAlive); + } + + [Fact] + public void DiscardedNodeRejectsSchedulerContinuationReadinessAndTimerPaths() + { + using var host = new SimulationSchedulerTestHost(); + var node = new SimulationNodeIdentity(TaskTestHarness.DefaultNodeAddress); + SimulationNodeContext context = CreateContext(host.Scheduler, node); + context.DiscardPendingWork(); + + Assert.Throws( + () => host.Scheduler.Schedule("direct", static () => { }, node)); + Assert.Throws( + () => host.Scheduler.ScheduleWhenReady(node, static () => true, static () => { })); + Assert.Throws( + () => host.Scheduler.RegisterTimer(node, TimeSpan.FromSeconds(1), static () => { })); + Assert.Throws( + () => host.Scheduler.ScheduleAfter( + "delayed", + static () => { }, + TimeSpan.FromSeconds(1), + node)); + + TaskTestHarness.RunInSimulation(host, () => + { + Assert.Throws( + () => SimulationTaskRuntime.QueueWork( + static () => { }, + "test.queue", + flowExecutionContext: false)); + Assert.Throws( + () => SimulationTaskRuntime.ScheduleContinuation( + Task.CompletedTask, + static () => { }, + "test.await", + flowExecutionContext: false)); + Assert.Throws( + () => + { + _ = ControlledTask.Delay( + TimeSpan.FromSeconds(1), + TestContext.Current.CancellationToken); + }); + Assert.Throws( + () => + { + _ = ControlledTask.WaitAsync( + new TaskCompletionSource().Task, + TimeSpan.FromSeconds(1), + TestContext.Current.CancellationToken); + }); + }); + + Assert.Equal(0, host.Scheduler.PendingOperationCount); + Assert.Equal(0, host.Scheduler.PendingTimerRegistrationCount); + Assert.Equal(0, host.Scheduler.WaitingOperationCount); + } + + [Fact] + public void DiscardDuringCreatedNotificationRejectsAdmissionWithoutRunnableLeak() + { + var listener = new CallbackListener(); + using var scheduler = SchedulerTestHarness.NewScheduler(listener); + var node = new SimulationNodeIdentity("node-1"); + SimulationNodeContext context = CreateContext(scheduler, node); + listener.Callback = (operation, state) => + { + if (state == SimulationOperationState.Created && operation.Node == node) + { + context.DiscardPendingWork(); + } + }; + + Assert.Throws( + () => scheduler.Schedule("reentrant-admission", static () => { }, node)); + + SimulationOperationStatus status = Assert.Single(scheduler.CaptureStatus()); + Assert.Equal(SimulationOperationState.Canceled, status.State); + Assert.Equal(SimulationNodeState.Discarded, context.State); + Assert.Equal(0, scheduler.PendingOperationCount); + Assert.Equal(0, scheduler.RunnableOperationCount); + Assert.Equal(0, scheduler.WaitingOperationCount); + } + + [Fact] + public void DiscardDuringReadinessCreatedNotificationRejectsInsertionWithoutWaitLeak() + { + var listener = new CallbackListener(); + using var scheduler = SchedulerTestHarness.NewScheduler(listener); + var node = new SimulationNodeIdentity("node-1"); + SimulationNodeContext context = CreateContext(scheduler, node); + var readinessCallbackRan = false; + listener.Callback = (operation, state) => + { + if (state == SimulationOperationState.Created && operation.Node == node) + { + context.DiscardPendingWork(); + } + }; + + Assert.Throws( + () => scheduler.ScheduleWhenReady( + node, + static () => true, + () => readinessCallbackRan = true)); + + Assert.False(readinessCallbackRan); + SimulationOperationStatus status = Assert.Single(scheduler.CaptureStatus()); + Assert.Equal(SimulationOperationState.Canceled, status.State); + Assert.Equal(SimulationNodeState.Discarded, context.State); + Assert.Equal(0, scheduler.PendingOperationCount); + Assert.Equal(0, scheduler.RunnableOperationCount); + Assert.Equal(0, scheduler.WaitingOperationCount); + Assert.False(scheduler.RunStep(TestContext.Current.CancellationToken)); + } + + [Fact] + public void DiscardPendingWorkRecordAndReplayConsumeTheSameDecisionStream() + { + var log = new SimulationDecisionLog(); + ScenarioResult recorded = RunScenario(log, replay: null); + Assert.NotEmpty(log.Records); + + ScenarioResult replayed = RunScenario(record: null, log.Records); + + Assert.Equal(recorded.Trace, replayed.Trace); + Assert.Equal(recorded.TargetStates, replayed.TargetStates); + Assert.Equal(recorded.VirtualTime, replayed.VirtualTime); + Assert.Equal(recorded.CreatedWorkerCount, replayed.CreatedWorkerCount); + Assert.Equal(["survivor-a:0", "survivor-b:0", "survivor-a:1", "survivor-b:1"], recorded.Trace); + Assert.All(recorded.TargetStates, state => Assert.Equal(SimulationOperationState.Canceled, state)); + } + + [Fact] + public void DiscardPendingWorkCleansRegistrationsWorkersAndPreservesExactlyOneRunning() + { + using var scheduler = SchedulerTestHarness.NewScheduler(); + var discardedNode = new SimulationNodeIdentity("discarded"); + var survivorNode = new SimulationNodeIdentity("survivor"); + SimulationNodeContext context = CreateContext(scheduler, discardedNode); + SimulationResource resource = scheduler.CreateResource( + SimulationResourceKind.Semaphore, + "discarded-resource"); + SimulationOperation parked = scheduler.Schedule( + "parked", + () => scheduler.WaitOnResource( + resource, + TimeSpan.FromMinutes(5), + SimulationPauseReason.ResourceWait("discarded-resource")), + discardedNode); + Assert.True(scheduler.RunStep(TestContext.Current.CancellationToken)); + Thread parkedWorker = parked.Thread!; + + _ = scheduler.ScheduleWhenReady( + discardedNode, + static () => false, + static () => { }); + _ = scheduler.RegisterTimer( + discardedNode, + TimeSpan.FromMinutes(7), + static () => { }); + SimulationOperation queuedA = + scheduler.Schedule("discarded-a", static () => { }, discardedNode); + SimulationOperation queuedB = + scheduler.Schedule("discarded-b", static () => { }, discardedNode); + + var concurrent = 0; + var maximumConcurrent = 0; + var survivorExecutions = 0; + var survivorWorkers = new HashSet(); + var survivorOperations = new List(); + for (var operationIndex = 0; operationIndex < 4; operationIndex++) + { + survivorOperations.Add(scheduler.Schedule( + $"survivor-{operationIndex}", + () => + { + survivorWorkers.Add(Thread.CurrentThread); + for (var iteration = 0; iteration < 5; iteration++) + { + int current = Interlocked.Increment(ref concurrent); + UpdateMaximum(ref maximumConcurrent, current); + survivorExecutions++; + Interlocked.Decrement(ref concurrent); + scheduler.Yield(); + } + }, + survivorNode)); + } + + context.DiscardPendingWork(); + scheduler.Drain(TestContext.Current.CancellationToken); + + Assert.Equal(1, maximumConcurrent); + Assert.Equal(20, survivorExecutions); + Assert.Equal(SimulationOperationState.Canceled, parked.State); + Assert.Equal(SimulationOperationState.Canceled, queuedA.State); + Assert.Equal(SimulationOperationState.Canceled, queuedB.State); + Assert.Null(parked.Thread); + Assert.Equal(0, resource.WaiterCount); + Assert.Empty(scheduler.CapturePendingTimeouts()); + Assert.Equal(0, scheduler.PendingTimerRegistrationCount); + Assert.Equal(0, scheduler.PendingOperationCount); + Assert.Equal(4, survivorWorkers.Count); + Assert.Equal(4, scheduler.CreatedWorkerThreadCount); + Assert.Equal(1, scheduler.IdleWorkerThreadCount); + Assert.All(survivorOperations, static operation => Assert.Null(operation.Thread)); + Assert.All( + scheduler.CaptureStatus().Where(status => status.NodeAddress == discardedNode.Address), + status => Assert.Equal(SimulationOperationState.Canceled, status.State)); + Assert.All( + scheduler.CaptureStatus().Where(status => status.NodeAddress == survivorNode.Address), + status => Assert.Equal(SimulationOperationState.Completed, status.State)); + + scheduler.Dispose(); + Assert.All(survivorWorkers, static worker => Assert.False(worker.IsAlive)); + Assert.False(parkedWorker.IsAlive); + } + + private static SimulationNodeContext CreateContext( + SimulationScheduler scheduler, + SimulationNodeIdentity node) + { + var guard = new SingleThreadedGuard( + () => scheduler.IsSimulationThread + ? SimulationScheduler.SimulationLogicalThreadOwnerId + : Environment.CurrentManagedThreadId); + return new SimulationNodeContext( + scheduler, + guard, + new SimulationRandom(seed: 1), + externalSchedulerLane: null, + logger: null, + node); + } + + private static ScenarioResult RunScenario( + SimulationDecisionLog? record, + IReadOnlyList? replay) + { + using var scheduler = SchedulerTestHarness.NewScheduler(); + if (record is not null) + { + scheduler.DecisionLog = record; + } + + if (replay is not null) + { + scheduler.ReplayValidator = new SimulationDecisionReplayValidator( + new SimulationInMemoryDecisionReplayReader(replay)); + } + + var discardedNode = new SimulationNodeIdentity("discarded"); + var survivorNode = new SimulationNodeIdentity("survivor"); + SimulationNodeContext context = CreateContext(scheduler, discardedNode); + SimulationOperation targetA = + scheduler.Schedule("target-a", static () => { }, discardedNode); + SimulationOperation targetB = + scheduler.Schedule("target-b", static () => { }, discardedNode); + var trace = new List(); + ScheduleSurvivor("survivor-a"); + ScheduleSurvivor("survivor-b"); + + context.DiscardPendingWork(); + scheduler.Drain(TestContext.Current.CancellationToken); + if (replay is not null) + { + scheduler.ValidateReplayComplete(); + } + + return new ScenarioResult( + [.. trace], + [targetA.State, targetB.State], + scheduler.VirtualTime, + scheduler.CreatedWorkerThreadCount); + + void ScheduleSurvivor(string name) + { + scheduler.Schedule( + name, + () => + { + for (var iteration = 0; iteration < 2; iteration++) + { + trace.Add($"{name}:{iteration}"); + scheduler.Yield(); + } + }, + survivorNode); + } + } + + private static void UpdateMaximum(ref int target, int candidate) + { + int observed; + do + { + observed = Volatile.Read(ref target); + if (candidate <= observed) + { + return; + } + } + while (Interlocked.CompareExchange(ref target, candidate, observed) != observed); + } + + private sealed record ScenarioResult( + string[] Trace, + SimulationOperationState[] TargetStates, + TimeSpan VirtualTime, + int CreatedWorkerCount); + + private sealed class CallbackListener : ISimulationOperationListener + { + public Action? Callback { get; set; } + + public void OnStateChanged( + SimulationOperation operation, + SimulationOperationState newState) => + Callback?.Invoke(operation, newState); + } +} diff --git a/tests/Clockwork.Tests/SimulationNodeDiscardTests.cs b/tests/Clockwork.Tests/SimulationNodeDiscardTests.cs new file mode 100644 index 0000000..4b909b0 --- /dev/null +++ b/tests/Clockwork.Tests/SimulationNodeDiscardTests.cs @@ -0,0 +1,221 @@ +namespace Orleans.Testing.Simulation.Tests; + +public sealed class SimulationNodeDiscardTests +{ + [Theory] + [InlineData(9)] + [InlineData(11)] + public async Task DiscardPendingWorkCancelsDelayedCallbackWithoutAdvancingTimeAndAllowsDisposal( + int delayMinutes) + { + var cluster = new SimulationCluster(seed: 1, DateTimeOffset.UnixEpoch); + SimulationNode node = cluster.AddNode("node-1"); + var callbackRan = false; + node.Context.SchedulerLane.EnqueueAfter( + () => callbackRan = true, + TimeSpan.FromMinutes(delayMinutes)); + DateTimeOffset utcNow = node.Context.TimeProvider.GetUtcNow(); + + node.Context.DiscardPendingWork(); + Assert.Equal(utcNow, node.Context.TimeProvider.GetUtcNow()); + await cluster.DisposeAsync(); + + Assert.False(callbackRan); + Assert.Equal(utcNow, cluster.Scheduler.UtcNow); + Assert.Equal(SimulationNodeState.Discarded, node.Context.State); + } + + [Fact] + public async Task DiscardPendingWorkCancelsReadyDelayedAndTimeProviderCallbacks() + { + await using var cluster = new SimulationCluster(seed: 1, DateTimeOffset.UnixEpoch); + SimulationNode node = cluster.AddNode("node-1"); + var readyRan = false; + var delayedRan = false; + var timerRan = false; + node.Context.SchedulerLane.Enqueue(() => readyRan = true); + node.Context.SchedulerLane.EnqueueAfter( + () => delayedRan = true, + TimeSpan.FromMinutes(1)); + using ITimer timer = node.Context.TimeProvider.CreateTimer( + _ => timerRan = true, + null, + TimeSpan.FromMinutes(2), + Timeout.InfiniteTimeSpan); + + node.Context.DiscardPendingWork(); + cluster.Scheduler.AdvanceVirtualTimeTo(TimeSpan.FromMinutes(3)); + SimulationExecutionResult result = + cluster.RunUntilIdle(TestContext.Current.CancellationToken); + + Assert.Equal(SimulationNodeState.Discarded, node.Context.State); + Assert.False(readyRan); + Assert.False(delayedRan); + Assert.False(timerRan); + Assert.False(node.Context.HasReadyTasks); + Assert.Null(node.Context.NextWaitingDueTime); + Assert.False(node.Context.HasPendingAttachmentWork); + Assert.Empty(node.Context.SchedulerLane.CaptureScheduledItems()); + Assert.Equal(0, cluster.Scheduler.PendingTimerRegistrationCount); + Assert.Equal(SimulationExecutionReason.Idle, result.Reason); + Assert.Equal(0, result.PendingWork.PendingCount); + } + + [Fact] + public async Task DiscardPendingWorkCancelsSuspendForSharedResumeAndStaysDiscarded() + { + await using var cluster = new SimulationCluster(seed: 1, DateTimeOffset.UnixEpoch); + SimulationNode node = cluster.AddNode("node-1"); + node.SuspendFor(TimeSpan.FromMinutes(1)); + + node.Context.DiscardPendingWork(); + cluster.Scheduler.AdvanceVirtualTimeTo(TimeSpan.FromMinutes(2)); + SimulationExecutionResult result = + cluster.RunUntilIdle(TestContext.Current.CancellationToken); + + Assert.Equal(SimulationNodeState.Discarded, node.Context.State); + Assert.False(node.Context.IsSuspended); + Assert.Empty(cluster.SchedulerLane.CaptureScheduledItems()); + Assert.Equal(SimulationExecutionReason.Idle, result.Reason); + Assert.Equal(0, result.PendingWork.PendingCount); + } + + [Fact] + public async Task DiscardPendingWorkWhileSuspendedRemovesBlockedWorkAndPendingDiagnostics() + { + await using var cluster = new SimulationCluster(seed: 1, DateTimeOffset.UnixEpoch); + SimulationNode node = cluster.AddNode("node-1"); + var callbackRan = false; + node.Suspend(); + node.Context.SchedulerLane.Enqueue(() => callbackRan = true); + + SimulationExecutionResult before = + cluster.RunUntilIdle(TestContext.Current.CancellationToken); + Assert.Equal(SimulationExecutionReason.IdleWithPendingWork, before.Reason); + Assert.Equal(1, before.PendingWork.BlockedCount); + + node.Context.DiscardPendingWork(); + SimulationExecutionResult after = + cluster.RunUntilIdle(TestContext.Current.CancellationToken); + + Assert.Equal(SimulationNodeState.Discarded, node.Context.State); + Assert.False(node.Context.IsSuspended); + Assert.False(callbackRan); + Assert.Equal(SimulationExecutionReason.Idle, after.Reason); + Assert.Equal(0, after.PendingWork.PendingCount); + Assert.DoesNotContain( + after.PendingWork.Items, + static item => item.QueueIdentity == "node-1"); + } + + [Fact] + public async Task DiscardPendingWorkIsIdempotentAndRejectsEveryNodeEnqueueSurface() + { + await using var cluster = new SimulationCluster(seed: 1, DateTimeOffset.UnixEpoch); + SimulationNode node = cluster.AddNode("node-1"); + SimulationNodeContext context = node.Context; + + context.DiscardPendingWork(); + context.DiscardPendingWork(); + + Assert.Equal(SimulationNodeState.Discarded, context.State); + Assert.Throws(() => context.SchedulerLane.Enqueue(static () => { })); + Assert.Throws( + () => context.SchedulerLane.EnqueueAfter(static () => { }, TimeSpan.FromSeconds(1))); + Assert.Throws( + () => context.SynchronizationContext.Post(static _ => { }, null)); + Assert.Throws( + () => context.SynchronizationContext.Send(static _ => { }, null)); + Assert.Throws( + () => context.TimeProvider.CreateTimer( + static _ => { }, + null, + TimeSpan.Zero, + Timeout.InfiniteTimeSpan)); + + var task = new Task(static () => { }); + TaskSchedulerException taskException = + Assert.Throws(() => task.Start(context.TaskScheduler)); + Assert.IsType(taskException.InnerException); + + Assert.Throws(context.Suspend); + Assert.Throws(context.Resume); + Assert.Throws( + () => context.SuspendFor(TimeSpan.FromSeconds(1))); + Assert.Throws( + () => context.Step(TestContext.Current.CancellationToken)); + Assert.Throws( + () => context.RunUntilIdle(TestContext.Current.CancellationToken)); + Assert.Empty(context.SchedulerLane.CaptureScheduledItems()); + Assert.Equal(0, context.Scheduler.PendingOperationCount); + Assert.Equal(0, context.Scheduler.PendingTimerRegistrationCount); + } + + [Fact] + public async Task DiscardPendingWorkDoesNotAffectOtherNodesOrClusterGlobalWork() + { + await using var cluster = new SimulationCluster(seed: 1, DateTimeOffset.UnixEpoch); + SimulationNode discarded = cluster.AddNode("discarded"); + SimulationNode survivor = cluster.AddNode("survivor"); + var discardedCount = 0; + var survivorCount = 0; + var clusterCount = 0; + for (var index = 0; index < 3; index++) + { + discarded.Context.SchedulerLane.Enqueue(() => discardedCount++); + survivor.Context.SchedulerLane.Enqueue(() => survivorCount++); + cluster.SchedulerLane.Enqueue(() => clusterCount++); + } + + discarded.Context.DiscardPendingWork(); + SimulationExecutionResult result = + cluster.RunUntilIdle(TestContext.Current.CancellationToken); + + Assert.Equal(0, discardedCount); + Assert.Equal(3, survivorCount); + Assert.Equal(3, clusterCount); + Assert.Equal(SimulationNodeState.Discarded, discarded.Context.State); + Assert.Equal(SimulationNodeState.Running, survivor.Context.State); + Assert.DoesNotContain(discarded, cluster.ActiveNodes); + Assert.Contains(survivor, cluster.ActiveNodes); + Assert.Equal(SimulationExecutionReason.Idle, result.Reason); + Assert.Equal(0, result.PendingWork.PendingCount); + } + + [Fact] + public async Task DiscardPendingWorkAfterClusterDisposalThrowsObjectDisposedException() + { + var cluster = new SimulationCluster(seed: 1, DateTimeOffset.UnixEpoch); + SimulationNodeContext context = cluster.AddNode("node-1").Context; + await cluster.DisposeAsync(); + + Assert.Throws(context.DiscardPendingWork); + } + + [Fact] + public async Task DiscardPendingWorkFromActiveCallbackIsRejectedWithoutPartialDiscard() + { + await using var cluster = new SimulationCluster(seed: 1, DateTimeOffset.UnixEpoch); + SimulationNode node = cluster.AddNode("node-1"); + Exception? rejection = null; + SimulationNodeState? stateDuringCallback = null; + var secondCallbackRan = false; + node.Context.SchedulerLane.Enqueue(() => + { + rejection = Record.Exception(node.Context.DiscardPendingWork); + stateDuringCallback = node.Context.State; + }); + node.Context.SchedulerLane.Enqueue(() => secondCallbackRan = true); + + SimulationExecutionResult result = + cluster.RunUntilIdle(TestContext.Current.CancellationToken); + + InvalidOperationException exception = Assert.IsType(rejection); + Assert.Contains("while one of its callbacks is running", exception.Message, StringComparison.Ordinal); + Assert.Equal(SimulationNodeState.Running, stateDuringCallback); + Assert.Equal(SimulationNodeState.Running, node.Context.State); + Assert.True(secondCallbackRan); + Assert.Equal(SimulationExecutionReason.Idle, result.Reason); + Assert.Equal(0, result.PendingWork.PendingCount); + } +} From 725dc475adcf7412c2968d8266934452d21eac0a Mon Sep 17 00:00:00 2001 From: Reuben Bond Date: Wed, 18 Nov 2026 09:09:04 -0800 Subject: [PATCH 4/4] fix: skip dequeued discarded timers --- .../Runtime/Scheduling/SimulationScheduler.cs | 8 +++ .../SimulationSchedulerNodeDiscardTests.cs | 54 +++++++++++++++++++ 2 files changed, 62 insertions(+) diff --git a/src/Orleans.Testing.Simulation/Runtime/Scheduling/SimulationScheduler.cs b/src/Orleans.Testing.Simulation/Runtime/Scheduling/SimulationScheduler.cs index d97f81f..8339370 100644 --- a/src/Orleans.Testing.Simulation/Runtime/Scheduling/SimulationScheduler.cs +++ b/src/Orleans.Testing.Simulation/Runtime/Scheduling/SimulationScheduler.cs @@ -1596,6 +1596,14 @@ private int ElapseTimers(IReadOnlyList due) { if (timeoutRegistration is SimulationTimerRegistration timer) { + lock (_gate) + { + if (timer.Node is { } node && _discardedNodes.Contains(node.Address)) + { + timer.Cancel(); + } + } + if (timer.TryClaimElapsed(out Action? callback)) { callback?.Invoke(); diff --git a/tests/Clockwork.Runtime.Tests/Scheduling/SimulationSchedulerNodeDiscardTests.cs b/tests/Clockwork.Runtime.Tests/Scheduling/SimulationSchedulerNodeDiscardTests.cs index 2d0ef4b..d5f24a3 100644 --- a/tests/Clockwork.Runtime.Tests/Scheduling/SimulationSchedulerNodeDiscardTests.cs +++ b/tests/Clockwork.Runtime.Tests/Scheduling/SimulationSchedulerNodeDiscardTests.cs @@ -218,6 +218,60 @@ public void DiscardDuringReadinessCreatedNotificationRejectsInsertionWithoutWait Assert.False(scheduler.RunStep(TestContext.Current.CancellationToken)); } + [Fact] + public void SameDeadlineTimerSchedulingCallbackDiscardSkipsLaterNodeTimerAndPreservesFutureTimer() + { + var listener = new CallbackListener(); + using var scheduler = SchedulerTestHarness.NewScheduler(listener); + var discardedNode = new SimulationNodeIdentity("discarded"); + var survivorNode = new SimulationNodeIdentity("survivor"); + SimulationNodeContext context = CreateContext(scheduler, discardedNode); + var trace = new List(); + var discardedDuringElapsedBatch = false; + listener.Callback = (operation, state) => + { + // An elapsed scheduler timer registers its callback operation synchronously. Discard + // reentrantly while ElapseTimers is still walking the already-dequeued same-time batch. + if (!discardedDuringElapsedBatch + && state == SimulationOperationState.Created + && operation.Node is null) + { + discardedDuringElapsedBatch = true; + context.DiscardPendingWork(); + } + }; + _ = scheduler.RegisterTimer( + node: null, + TimeSpan.FromMinutes(5), + () => trace.Add("first")); + _ = scheduler.RegisterTimer( + discardedNode, + TimeSpan.FromMinutes(5), + () => trace.Add("discarded")); + _ = scheduler.RegisterTimer( + survivorNode, + TimeSpan.FromMinutes(7), + () => trace.Add("later")); + + Assert.True(scheduler.TryAdvanceVirtualTime()); + Assert.Equal(TimeSpan.FromMinutes(5), scheduler.VirtualTime); + Assert.Equal(SimulationNodeState.Discarded, context.State); + Assert.True(discardedDuringElapsedBatch); + Assert.Equal(1, scheduler.PendingTimerRegistrationCount); + + scheduler.RunUntilIdle(TestContext.Current.CancellationToken); + + Assert.Equal(["first"], trace); + Assert.Equal(TimeSpan.FromMinutes(5), scheduler.VirtualTime); + Assert.True(scheduler.TryAdvanceVirtualTime()); + Assert.Equal(TimeSpan.FromMinutes(7), scheduler.VirtualTime); + scheduler.RunUntilIdle(TestContext.Current.CancellationToken); + + Assert.Equal(["first", "later"], trace); + Assert.Equal(0, scheduler.PendingTimerRegistrationCount); + Assert.False(scheduler.TryAdvanceVirtualTime()); + } + [Fact] public void DiscardPendingWorkRecordAndReplayConsumeTheSameDecisionStream() {