|
| 1 | +using Microsoft.Extensions.DependencyInjection; |
| 2 | +using System.Collections.Concurrent; |
| 3 | +using ModularityKit.Mutator.Abstractions; |
| 4 | +using ModularityKit.Mutator.Abstractions.Changes; |
| 5 | +using ModularityKit.Mutator.Abstractions.Context; |
| 6 | +using ModularityKit.Mutator.Abstractions.Engine; |
| 7 | +using ModularityKit.Mutator.Abstractions.Intent; |
| 8 | +using ModularityKit.Mutator.Abstractions.Results; |
| 9 | +using ModularityKit.Mutator.Runtime; |
| 10 | +using Xunit; |
| 11 | + |
| 12 | +namespace ModularityKit.Mutator.Tests.Runtime; |
| 13 | + |
| 14 | +public sealed class MutationEngineConcurrencyTests |
| 15 | +{ |
| 16 | + [Fact] |
| 17 | + public async Task ExecuteAsync_serializes_mutations_that_target_the_same_state_id() |
| 18 | + { |
| 19 | + var services = new ServiceCollection(); |
| 20 | + services.AddMutators(configure: options => |
| 21 | + { |
| 22 | + options.MaxConcurrentMutations = 4; |
| 23 | + options.EnableDetailedMetrics = false; |
| 24 | + }); |
| 25 | + |
| 26 | + await using var provider = services.BuildServiceProvider(); |
| 27 | + var engine = provider.GetRequiredService<IMutationEngine>(); |
| 28 | + using var gate = new BlockingMutationGate(); |
| 29 | + var state = new OrderedState("initial"); |
| 30 | + |
| 31 | + var first = new BlockingMutation(gate, "shared-state", "first"); |
| 32 | + var second = new BlockingMutation(gate, "shared-state", "second"); |
| 33 | + |
| 34 | + var firstTask = Task.Run(() => engine.ExecuteAsync(first, state)); |
| 35 | + var secondTask = Task.Run(() => engine.ExecuteAsync(second, state)); |
| 36 | + |
| 37 | + Assert.True(await gate.WaitForEntriesAsync(1, TimeSpan.FromSeconds(5))); |
| 38 | + Assert.Equal(1, gate.PeakConcurrency); |
| 39 | + |
| 40 | + gate.Release(); |
| 41 | + |
| 42 | + var results = await Task.WhenAll(firstTask, secondTask); |
| 43 | + |
| 44 | + Assert.All(results, result => Assert.True(result.IsSuccess)); |
| 45 | + Assert.Equal(1, gate.PeakConcurrency); |
| 46 | + } |
| 47 | + |
| 48 | + [Fact] |
| 49 | + public async Task ExecuteAsync_honors_max_concurrent_mutations_for_different_states() |
| 50 | + { |
| 51 | + var services = new ServiceCollection(); |
| 52 | + services.AddMutators(configure: options => |
| 53 | + { |
| 54 | + options.MaxConcurrentMutations = 2; |
| 55 | + options.EnableDetailedMetrics = false; |
| 56 | + }); |
| 57 | + |
| 58 | + await using var provider = services.BuildServiceProvider(); |
| 59 | + var engine = provider.GetRequiredService<IMutationEngine>(); |
| 60 | + using var gate = new BlockingMutationGate(); |
| 61 | + var states = new[] |
| 62 | + { |
| 63 | + new OrderedState("one"), |
| 64 | + new OrderedState("two"), |
| 65 | + new OrderedState("three"), |
| 66 | + new OrderedState("four") |
| 67 | + }; |
| 68 | + |
| 69 | + var tasks = new[] |
| 70 | + { |
| 71 | + Task.Run(() => engine.ExecuteAsync(new BlockingMutation(gate, "state-1", "one"), states[0])), |
| 72 | + Task.Run(() => engine.ExecuteAsync(new BlockingMutation(gate, "state-2", "two"), states[1])), |
| 73 | + Task.Run(() => engine.ExecuteAsync(new BlockingMutation(gate, "state-3", "three"), states[2])), |
| 74 | + Task.Run(() => engine.ExecuteAsync(new BlockingMutation(gate, "state-4", "four"), states[3])) |
| 75 | + }; |
| 76 | + |
| 77 | + Assert.True(await gate.WaitForEntriesAsync(2, TimeSpan.FromSeconds(5))); |
| 78 | + Assert.Equal(2, gate.PeakConcurrency); |
| 79 | + |
| 80 | + gate.Release(); |
| 81 | + |
| 82 | + var results = await Task.WhenAll(tasks); |
| 83 | + |
| 84 | + Assert.All(results, result => Assert.True(result.IsSuccess)); |
| 85 | + Assert.Equal(2, gate.PeakConcurrency); |
| 86 | + } |
| 87 | + |
| 88 | + [Fact] |
| 89 | + public async Task ExecuteBatchAsync_remains_ordered_while_respecting_runtime_concurrency_gates() |
| 90 | + { |
| 91 | + var services = new ServiceCollection(); |
| 92 | + services.AddMutators(configure: options => |
| 93 | + { |
| 94 | + options.MaxConcurrentMutations = 2; |
| 95 | + options.EnableDetailedMetrics = false; |
| 96 | + }); |
| 97 | + |
| 98 | + await using var provider = services.BuildServiceProvider(); |
| 99 | + var engine = provider.GetRequiredService<IMutationEngine>(); |
| 100 | + var observed = new ConcurrentQueue<string>(); |
| 101 | + |
| 102 | + var batch = new[] |
| 103 | + { |
| 104 | + new OrderedMutation("state-1", "first", observed), |
| 105 | + new OrderedMutation("state-2", "second", observed), |
| 106 | + new OrderedMutation("state-1", "third", observed) |
| 107 | + }; |
| 108 | + |
| 109 | + var result = await engine.ExecuteBatchAsync(batch, new OrderedState("initial")); |
| 110 | + |
| 111 | + Assert.True(result.IsSuccess); |
| 112 | + Assert.Equal(3, result.Results.Count); |
| 113 | + Assert.Equal(new[] { "first", "second", "third" }, observed); |
| 114 | + } |
| 115 | + |
| 116 | + [Fact] |
| 117 | + public void AddMutators_rejects_non_positive_max_concurrent_mutations() |
| 118 | + { |
| 119 | + var services = new ServiceCollection(); |
| 120 | + services.AddMutators(configure: options => options.MaxConcurrentMutations = 0); |
| 121 | + |
| 122 | + Assert.Throws<ArgumentOutOfRangeException>(() => services.BuildServiceProvider().GetRequiredService<IMutationEngine>()); |
| 123 | + } |
| 124 | + |
| 125 | + private sealed record OrderedState(string Value); |
| 126 | + |
| 127 | + private sealed class OrderedMutation(string stateId, string value, ConcurrentQueue<string> observed) |
| 128 | + : IMutation<OrderedState> |
| 129 | + { |
| 130 | + public MutationIntent Intent { get; } = new() |
| 131 | + { |
| 132 | + OperationName = "Order", |
| 133 | + Category = "Test", |
| 134 | + Description = "Observe execution order" |
| 135 | + }; |
| 136 | + |
| 137 | + public MutationContext Context { get; } = MutationContext.User("tester", "Tester", "Order test") |
| 138 | + with { StateId = stateId }; |
| 139 | + |
| 140 | + public MutationResult<OrderedState> Apply(OrderedState state) |
| 141 | + { |
| 142 | + observed.Enqueue(value); |
| 143 | + return MutationResult<OrderedState>.Success(state with { Value = value }, ChangeSet.Empty); |
| 144 | + } |
| 145 | + |
| 146 | + public ValidationResult Validate(OrderedState state) => ValidationResult.Success(); |
| 147 | + |
| 148 | + public MutationResult<OrderedState> Simulate(OrderedState state) => Apply(state); |
| 149 | + } |
| 150 | + |
| 151 | + private sealed class BlockingMutationGate : IDisposable |
| 152 | + { |
| 153 | + private readonly ManualResetEventSlim _release = new(false); |
| 154 | + private int _entered; |
| 155 | + private int _active; |
| 156 | + private int _peak; |
| 157 | + |
| 158 | + public int PeakConcurrency => Volatile.Read(ref _peak); |
| 159 | + |
| 160 | + public async Task<bool> WaitForEntriesAsync(int expectedEntries, TimeSpan timeout) |
| 161 | + { |
| 162 | + var started = DateTimeOffset.UtcNow; |
| 163 | + |
| 164 | + while (Volatile.Read(ref _entered) < expectedEntries) |
| 165 | + { |
| 166 | + if (DateTimeOffset.UtcNow - started > timeout) |
| 167 | + return false; |
| 168 | + |
| 169 | + await Task.Delay(10); |
| 170 | + } |
| 171 | + |
| 172 | + return true; |
| 173 | + } |
| 174 | + |
| 175 | + public void Enter() |
| 176 | + { |
| 177 | + Interlocked.Increment(ref _entered); |
| 178 | + var active = Interlocked.Increment(ref _active); |
| 179 | + |
| 180 | + while (true) |
| 181 | + { |
| 182 | + var peak = Volatile.Read(ref _peak); |
| 183 | + if (active <= peak || Interlocked.CompareExchange(ref _peak, active, peak) == peak) |
| 184 | + break; |
| 185 | + } |
| 186 | + |
| 187 | + _release.Wait(); |
| 188 | + Interlocked.Decrement(ref _active); |
| 189 | + } |
| 190 | + |
| 191 | + public void Release() => _release.Set(); |
| 192 | + |
| 193 | + public void Dispose() => _release.Dispose(); |
| 194 | + } |
| 195 | + |
| 196 | + private sealed class BlockingMutation( |
| 197 | + BlockingMutationGate gate, |
| 198 | + string stateId, |
| 199 | + string value) : IMutation<OrderedState> |
| 200 | + { |
| 201 | + public MutationIntent Intent { get; } = new() |
| 202 | + { |
| 203 | + OperationName = "Block", |
| 204 | + Category = "Test", |
| 205 | + Description = "Block until released" |
| 206 | + }; |
| 207 | + |
| 208 | + public MutationContext Context { get; } = MutationContext.User($"{stateId}-actor", $"{stateId}-actor", "Concurrency test") |
| 209 | + with { StateId = stateId }; |
| 210 | + |
| 211 | + public MutationResult<OrderedState> Apply(OrderedState state) |
| 212 | + { |
| 213 | + gate.Enter(); |
| 214 | + return MutationResult<OrderedState>.Success(state with { Value = value }, ChangeSet.Empty); |
| 215 | + } |
| 216 | + |
| 217 | + public ValidationResult Validate(OrderedState state) => ValidationResult.Success(); |
| 218 | + |
| 219 | + public MutationResult<OrderedState> Simulate(OrderedState state) => Apply(state); |
| 220 | + } |
| 221 | +} |
0 commit comments