Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -284,6 +284,19 @@ 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,
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
`ObjectDisposedException`. Ordinary nodes retain the disposal-drains behavior above.

## Drive simulated execution

```csharp
Expand Down
24 changes: 22 additions & 2 deletions docs/compatibility.md
Original file line number Diff line number Diff line change
Expand Up @@ -91,8 +91,28 @@ 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 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
`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,
Expand Down
7 changes: 4 additions & 3 deletions src/Orleans.Testing.Simulation/Cluster/SimulationCluster.cs
Original file line number Diff line number Diff line change
Expand Up @@ -219,10 +219,11 @@ internal SimulationCluster(
public IReadOnlyList<SimulationNode> Nodes => [.. _nodes.Values];

/// <summary>
/// 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.
/// </summary>
public IReadOnlyList<SimulationNode> ActiveNodes => [.. _nodes.Values.Where(n => !n.IsSuspended)];
public IReadOnlyList<SimulationNode> ActiveNodes =>
[.. _nodes.Values.Where(static node => node.Context.State == SimulationNodeState.Running)];

/// <summary>
/// Gets the simulated network for this cluster. The network is available immediately, including
Expand Down
121 changes: 113 additions & 8 deletions src/Orleans.Testing.Simulation/Nodes/SimulationNodeContext.cs
Original file line number Diff line number Diff line change
@@ -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;
Expand All @@ -22,6 +23,11 @@ public enum SimulationNodeState
/// Timers will accumulate and fire when the node is resumed if their due time has passed.
/// </summary>
Suspended,

/// <summary>
/// The node has explicitly discarded all pending work and cannot accept new work.
/// </summary>
Discarded,
}

internal enum SimulationNodeAttachmentState
Expand Down Expand Up @@ -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
Expand All @@ -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.
/// </summary>
public DateTimeOffset? NextWaitingDueTime => SchedulerLane.NextWaitingDueTime;
public DateTimeOffset? NextWaitingDueTime =>
State == SimulationNodeState.Discarded ? null : SchedulerLane.NextWaitingDueTime;

/// <summary>
/// Executes one ready task from this node's lane.
Expand All @@ -171,6 +178,7 @@ public bool HasReadyTasks
public bool Step(CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
ThrowIfPendingWorkDiscarded();
if (State == SimulationNodeState.Suspended)
return false;

Expand All @@ -187,6 +195,7 @@ public bool Step(CancellationToken cancellationToken)
public int RunUntilIdle(CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
ThrowIfPendingWorkDiscarded();
if (State == SimulationNodeState.Suspended)
return 0;

Expand All @@ -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)
{
Expand All @@ -217,7 +226,7 @@ public void Suspend()
public void Resume()
{
using var _ = _guard.Enter();
ThrowIfDetached();
ThrowIfUnavailable();
State = SimulationNodeState.Running;
if (_attachmentState != SimulationNodeAttachmentState.Disposing)
{
Expand All @@ -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(
Expand Down Expand Up @@ -280,6 +289,80 @@ public void SuspendFor(TimeSpan duration)
}
}

/// <summary>
/// Permanently discards every pending unit of work owned by this node.
/// </summary>
/// <remarks>
/// <para>
/// 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.
/// </para>
/// <para>
/// The transition is permanent and idempotent while the context remains attached. The context
/// enters <see cref="SimulationNodeState.Discarded"/>, and later attempts to enqueue node-owned
/// work throw <see cref="ObjectDisposedException"/>. Calling this from work currently executing
/// for this node throws <see cref="InvalidOperationException"/> without discarding anything.
/// After the containing cluster has detached the context, this method throws
/// <see cref="ObjectDisposedException"/>.
/// </para>
/// </remarks>
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
Expand All @@ -294,6 +377,11 @@ internal bool HasPendingAttachmentWork
get
{
using var _ = _guard.Enter();
if (State == SimulationNodeState.Discarded)
{
return false;
}

return SchedulerLane.HasPendingWork || _sharedLaneItems.Count > 0;
}
}
Expand Down Expand Up @@ -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()
Expand All @@ -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);
Expand Down Expand Up @@ -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})";

Expand Down
Loading
Loading