diff --git a/src/GameCult.Mesh/CultMeshBodies.cs b/src/GameCult.Mesh/CultMeshBodies.cs index f673a3ca..080f4869 100644 --- a/src/GameCult.Mesh/CultMeshBodies.cs +++ b/src/GameCult.Mesh/CultMeshBodies.cs @@ -54,6 +54,8 @@ namespace GameCult.Mesh public string SchemaId { get; set; } = string.Empty; public int LayoutVersion { get; set; } public long ProducerEpoch { get; set; } + public long? Sequence { get; set; } + public int? Capacity { get; set; } public CultMeshBodyAccessMode AccessMode { get; set; } = CultMeshBodyAccessMode.ReadOnly; public DateTimeOffset NowUtc { get; set; } = DateTimeOffset.UtcNow; } @@ -74,6 +76,10 @@ namespace GameCult.Mesh throw new InvalidOperationException("CultMesh body layout version mismatch."); if (descriptor.ProducerEpoch != request.ProducerEpoch) throw new InvalidOperationException("CultMesh body producer epoch mismatch."); + if (request.Sequence.HasValue && descriptor.Sequence != request.Sequence.Value) + throw new InvalidOperationException("CultMesh body sequence mismatch."); + if (request.Capacity.HasValue && descriptor.Capacity != request.Capacity.Value) + throw new InvalidOperationException("CultMesh body capacity mismatch."); if (descriptor.ByteSize < 0 || descriptor.Capacity < 0) throw new InvalidOperationException("CultMesh body size and logical capacity must be non-negative."); if (descriptor.Sequence < 0) @@ -83,9 +89,6 @@ namespace GameCult.Mesh if (request.AccessMode != CultMeshBodyAccessMode.ReadOnly || descriptor.AccessMode != CultMeshBodyAccessMode.ReadOnly) throw new UnauthorizedAccessException("CultMesh body consumers are read-only by default."); - if (descriptor.TransportKind != CultMeshBodyTransportKind.Network && - string.IsNullOrWhiteSpace(descriptor.CapabilityToken)) - throw new InvalidOperationException("Local CultMesh body descriptor has no capability token."); } } @@ -268,6 +271,8 @@ namespace GameCult.Mesh CultMeshBodyDescriptorValidator.Validate(descriptor, request); if (descriptor.TransportKind != CultMeshBodyTransportKind.SharedFileMapping) throw new NotSupportedException($"CultMesh body transport '{descriptor.TransportKind}' is not a file mapping."); + if (string.IsNullOrWhiteSpace(descriptor.CapabilityToken)) + throw new InvalidOperationException("Mapped CultMesh body descriptor has no transport capability token."); var path = _verifiedBodies != null ? _verifiedBodies.Resolve(descriptor.CapabilityToken, request.NowUtc) : ResolvePublisherPath(descriptor.CapabilityToken); @@ -369,6 +374,8 @@ namespace GameCult.Mesh CultMeshBodyValidationRequest request) { CultMeshBodyDescriptorValidator.Validate(descriptor, request); + if (string.IsNullOrWhiteSpace(descriptor.CapabilityToken)) + throw new InvalidOperationException("Shared-memory CultMesh body descriptor has no transport capability token."); MemoryMappedFile mapping; try { diff --git a/src/GameCult.Mesh/CultMeshFrameBodies.cs b/src/GameCult.Mesh/CultMeshFrameBodies.cs new file mode 100644 index 00000000..6234cba4 --- /dev/null +++ b/src/GameCult.Mesh/CultMeshFrameBodies.cs @@ -0,0 +1,335 @@ +using System; +using System.Collections.Generic; +using System.Threading; + +#nullable enable + +namespace GameCult.Mesh +{ + public sealed class CultMeshFrameGeneration + { + internal CultMeshFrameGeneration( + int slotIndex, + CultMeshBodyDescriptor descriptor, + long timestampNs, + long durationNs, + int unavoidableCopyCount, + IReadOnlyDictionary? metadata) + { + SlotIndex = slotIndex; + Descriptor = descriptor; + TimestampNs = timestampNs; + DurationNs = durationNs; + UnavoidableCopyCount = unavoidableCopyCount; + Metadata = metadata == null + ? new Dictionary() + : new Dictionary(metadata); + } + + public int SlotIndex { get; } + public CultMeshBodyDescriptor Descriptor { get; } + public long TimestampNs { get; } + public long DurationNs { get; } + public int UnavoidableCopyCount { get; } + public IReadOnlyDictionary Metadata { get; } + } + + public readonly struct CultMeshFrameRegionWriteLease + { + private readonly CultMeshFrameRegion? _owner; + private readonly object? _reservation; + + internal CultMeshFrameRegionWriteLease( + CultMeshFrameRegion owner, + object reservation, + int slotIndex, + long sequence, + Memory memory) + { + _owner = owner; + _reservation = reservation; + SlotIndex = slotIndex; + Sequence = sequence; + Memory = memory; + } + + public int SlotIndex { get; } + public long Sequence { get; } + public Memory Memory { get; } + public Span Span => Memory.Span; + + internal CultMeshFrameGeneration Commit( + int byteLength, + long timestampNs, + long durationNs, + int unavoidableCopyCount, + IReadOnlyDictionary? metadata) => + _owner?.Commit(this, _reservation!, byteLength, timestampNs, durationNs, unavoidableCopyCount, metadata) + ?? throw new InvalidOperationException("The frame-region write lease is not valid."); + } + + public sealed class CultMeshFrameRegionReadLease : IDisposable + { + private CultMeshFrameRegion? _owner; + + internal CultMeshFrameRegionReadLease( + CultMeshFrameRegion owner, + CultMeshFrameGeneration generation, + ReadOnlyMemory memory) + { + _owner = owner; + Generation = generation; + Memory = memory; + } + + public CultMeshFrameGeneration Generation { get; } + public ReadOnlyMemory Memory { get; } + public ReadOnlySpan Span => Memory.Span; + + public void Dispose() => Interlocked.Exchange(ref _owner, null)?.ReleaseRead(Generation.SlotIndex); + } + + public sealed class CultMeshFrameRegionStats + { + internal CultMeshFrameRegionStats( + ulong publishedFrames, + ulong droppedFrames, + ulong blockedWrites, + long latestSequence, + ulong unavoidableCopyCount) + { + PublishedFrames = publishedFrames; + DroppedFrames = droppedFrames; + BlockedWrites = blockedWrites; + LatestSequence = latestSequence; + UnavoidableCopyCount = unavoidableCopyCount; + } + + public ulong PublishedFrames { get; } + public ulong DroppedFrames { get; } + public ulong BlockedWrites { get; } + public long LatestSequence { get; } + public ulong UnavoidableCopyCount { get; } + } + + public sealed class CultMeshFrameRegion : IDisposable + { + public const int SlotCount = 3; + + private readonly object _gate = new(); + private readonly byte[] _storage; + private readonly int[] _readerCounts = new int[SlotCount]; + private readonly object?[] _writeReservations = new object?[SlotCount]; + private readonly CultMeshFrameGeneration?[] _generations = new CultMeshFrameGeneration?[SlotCount]; + private object? _activeWriteReservation; + private int _writeCursor; + private int _latestSlot = -1; + private bool _disposed; + private long _nextSequence; + private ulong _publishedFrames; + private ulong _droppedFrames; + private ulong _blockedWrites; + private ulong _unavoidableCopyCount; + + public CultMeshFrameRegion( + string bodyId, + string schemaId, + int layoutVersion, + int capacity, + long producerEpoch, + int slotByteLength) + { + BodyId = Require(bodyId, nameof(bodyId)); + SchemaId = Require(schemaId, nameof(schemaId)); + if (layoutVersion < 0) throw new ArgumentOutOfRangeException(nameof(layoutVersion)); + if (capacity < 0) throw new ArgumentOutOfRangeException(nameof(capacity)); + if (producerEpoch < 0) throw new ArgumentOutOfRangeException(nameof(producerEpoch)); + if (slotByteLength <= 0) throw new ArgumentOutOfRangeException(nameof(slotByteLength)); + LayoutVersion = layoutVersion; + Capacity = capacity; + ProducerEpoch = producerEpoch; + SlotByteLength = slotByteLength; + _storage = new byte[checked(SlotCount * slotByteLength)]; + } + + public string BodyId { get; } + public string SchemaId { get; } + public int LayoutVersion { get; } + public int Capacity { get; } + public long ProducerEpoch { get; } + public int SlotByteLength { get; } + + public bool TryAcquireWrite(out CultMeshFrameRegionWriteLease lease) + { + lock (_gate) + { + ThrowIfDisposed(); + if (_activeWriteReservation != null) + { + _blockedWrites++; + lease = default; + return false; + } + + for (var attempt = 0; attempt < SlotCount; attempt++) + { + var slotIndex = (_writeCursor + attempt) % SlotCount; + if (_readerCounts[slotIndex] != 0 || _writeReservations[slotIndex] != null) + continue; + + if (_generations[slotIndex] != null) + _droppedFrames++; + + var reservation = new object(); + _writeReservations[slotIndex] = reservation; + _activeWriteReservation = reservation; + _writeCursor = (slotIndex + 1) % SlotCount; + lease = new CultMeshFrameRegionWriteLease( + this, + reservation, + slotIndex, + _nextSequence, + new Memory(_storage, slotIndex * SlotByteLength, SlotByteLength)); + return true; + } + + _blockedWrites++; + lease = default; + return false; + } + } + + public CultMeshFrameGeneration Commit( + CultMeshFrameRegionWriteLease lease, + int byteLength, + long timestampNs, + long durationNs = 0, + int unavoidableCopyCount = 0, + IReadOnlyDictionary? metadata = null) => + lease.Commit(byteLength, timestampNs, durationNs, unavoidableCopyCount, metadata); + + internal CultMeshFrameGeneration Commit( + CultMeshFrameRegionWriteLease lease, + object reservation, + int byteLength, + long timestampNs, + long durationNs, + int unavoidableCopyCount, + IReadOnlyDictionary? metadata) + { + lock (_gate) + { + ThrowIfDisposed(); + RequireSlot(lease.SlotIndex); + if (!ReferenceEquals(_activeWriteReservation, reservation) || + !ReferenceEquals(_writeReservations[lease.SlotIndex], reservation) || + lease.Sequence != _nextSequence) + throw new InvalidOperationException("The frame-region write lease is stale or was already committed."); + if (byteLength < 0 || byteLength > SlotByteLength) + throw new ArgumentOutOfRangeException(nameof(byteLength)); + + var descriptor = new CultMeshBodyDescriptor + { + BodyId = BodyId, + SchemaId = SchemaId, + LayoutVersion = LayoutVersion, + ByteSize = byteLength, + Capacity = Capacity, + ProducerEpoch = ProducerEpoch, + Sequence = _nextSequence, + AccessMode = CultMeshBodyAccessMode.ReadOnly, + Synchronization = CultMeshBodySynchronization.TripleBuffer, + LeaseExpiresAtUnixMs = long.MaxValue, + TransportKind = CultMeshBodyTransportKind.SharedMemory + }; + var generation = new CultMeshFrameGeneration( + lease.SlotIndex, descriptor, timestampNs, durationNs, unavoidableCopyCount, metadata); + + _generations[lease.SlotIndex] = generation; + _writeReservations[lease.SlotIndex] = null; + _activeWriteReservation = null; + _latestSlot = lease.SlotIndex; + _nextSequence++; + _publishedFrames++; + _unavoidableCopyCount += (ulong)Math.Max(0, unavoidableCopyCount); + return generation; + } + } + + public bool TryAcquireLatestRead( + CultMeshBodyValidationRequest request, + out CultMeshFrameRegionReadLease lease) + { + if (request == null) throw new ArgumentNullException(nameof(request)); + lock (_gate) + { + ThrowIfDisposed(); + if (_latestSlot < 0 || _generations[_latestSlot] == null) + { + lease = null!; + return false; + } + + var generation = _generations[_latestSlot]!; + CultMeshBodyDescriptorValidator.Validate(generation.Descriptor, request); + _readerCounts[_latestSlot]++; + lease = new CultMeshFrameRegionReadLease( + this, + generation, + new ReadOnlyMemory( + _storage, + _latestSlot * SlotByteLength, + checked((int)generation.Descriptor.ByteSize))); + return true; + } + } + + public CultMeshFrameRegionStats Stats() + { + lock (_gate) + { + ThrowIfDisposed(); + return new CultMeshFrameRegionStats( + _publishedFrames, + _droppedFrames, + _blockedWrites, + _latestSlot < 0 ? 0 : _generations[_latestSlot]!.Descriptor.Sequence, + _unavoidableCopyCount); + } + } + + internal void ReleaseRead(int slotIndex) + { + lock (_gate) + { + if (_disposed) return; + RequireSlot(slotIndex); + if (_readerCounts[slotIndex] <= 0) + throw new InvalidOperationException("The frame-region reader lease was released more than once."); + _readerCounts[slotIndex]--; + } + } + + public void Dispose() + { + lock (_gate) + { + if (_disposed) return; + _disposed = true; + } + } + + private void ThrowIfDisposed() + { + if (_disposed) throw new ObjectDisposedException(nameof(CultMeshFrameRegion)); + } + + private static string Require(string value, string parameterName) => + string.IsNullOrWhiteSpace(value) ? throw new ArgumentException("Value is required.", parameterName) : value; + + private static void RequireSlot(int slotIndex) + { + if (slotIndex < 0 || slotIndex >= SlotCount) throw new ArgumentOutOfRangeException(nameof(slotIndex)); + } + } +} diff --git a/src/GameCult.Mesh/CultMeshStreaming.cs b/src/GameCult.Mesh/CultMeshStreaming.cs index ba3dcfd6..51876200 100644 --- a/src/GameCult.Mesh/CultMeshStreaming.cs +++ b/src/GameCult.Mesh/CultMeshStreaming.cs @@ -1,5 +1,4 @@ using System; -using System.Buffers; using System.Collections.Generic; using System.Linq; using System.Threading; @@ -264,43 +263,43 @@ namespace GameCult.Mesh public readonly struct CultMeshFrameWriteLease { - internal CultMeshFrameWriteLease(int slotIndex, ulong sequence, Memory memory) + private readonly CultMeshFrameRegionWriteLease _lease; + + internal CultMeshFrameWriteLease(CultMeshFrameRegionWriteLease lease) { - SlotIndex = slotIndex; - Sequence = sequence; - Memory = memory; + _lease = lease; } - public int SlotIndex { get; } - public ulong Sequence { get; } - public Memory Memory { get; } + public int SlotIndex => _lease.SlotIndex; + public ulong Sequence => checked((ulong)_lease.Sequence); + public Memory Memory => _lease.Memory; public Span Span => Memory.Span; + + internal CultMeshFrameRegionWriteLease RegionLease => _lease; } public readonly struct CultMeshFrameReadLease : IDisposable { - private readonly CultMeshSharedMemoryFrameRing? _owner; + private readonly CultMeshFrameRegionReadLease? _lease; internal CultMeshFrameReadLease( - CultMeshSharedMemoryFrameRing owner, - int slotIndex, + CultMeshFrameRegionReadLease lease, CultMeshStreamFrameHandle handle, - ReadOnlyMemory memory) + int slotIndex) { - _owner = owner; + _lease = lease; SlotIndex = slotIndex; Handle = handle; - Memory = memory; } public int SlotIndex { get; } public CultMeshStreamFrameHandle Handle { get; } - public ReadOnlyMemory Memory { get; } + public ReadOnlyMemory Memory => _lease?.Memory ?? ReadOnlyMemory.Empty; public ReadOnlySpan Span => Memory.Span; public void Dispose() { - _owner?.ReleaseRead(SlotIndex); + _lease?.Dispose(); } } @@ -338,59 +337,33 @@ namespace GameCult.Mesh public sealed class CultMeshSharedMemoryFrameRing : IDisposable { - private readonly byte[] _storage; - private readonly int[] _readerCounts; - private readonly CultMeshStreamFrameHandle?[] _handles; - private int _writeCursor; - private int _latestSlot = -1; - private int _disposed; - private ulong _nextSequence; - private ulong _publishedFrames; - private ulong _droppedFrames; - private ulong _blockedWrites; - private ulong _unavoidableCopyCount; + private readonly CultMeshFrameRegion _region; public CultMeshSharedMemoryFrameRing(string streamId, int slotCount, int slotByteLength) { StreamId = RequireNonEmpty(streamId, nameof(streamId)); - if (slotCount <= 0) throw new ArgumentOutOfRangeException(nameof(slotCount)); - if (slotByteLength <= 0) throw new ArgumentOutOfRangeException(nameof(slotByteLength)); - SlotByteLength = slotByteLength; - _storage = ArrayPool.Shared.Rent(checked(slotCount * slotByteLength)); - _readerCounts = new int[slotCount]; - _handles = new CultMeshStreamFrameHandle?[slotCount]; + if (slotCount != CultMeshFrameRegion.SlotCount) + throw new ArgumentOutOfRangeException(nameof(slotCount), "CultMesh frame regions use exactly three slots."); + _region = new CultMeshFrameRegion( + streamId, + $"{streamId}.frame", + layoutVersion: 1, + capacity: slotByteLength, + producerEpoch: 0, + slotByteLength); } public string StreamId { get; } - public int SlotCount => _handles.Length; - public int SlotByteLength { get; } + public int SlotCount => CultMeshFrameRegion.SlotCount; + public int SlotByteLength => _region.SlotByteLength; public bool TryAcquireWriteSlot(out CultMeshFrameWriteLease lease) { - ThrowIfDisposed(); - - for (var attempt = 0; attempt < SlotCount; attempt++) + if (_region.TryAcquireWrite(out var regionLease)) { - var slotIndex = (_writeCursor + attempt) % SlotCount; - if (Volatile.Read(ref _readerCounts[slotIndex]) != 0) - { - continue; - } - - if (_handles[slotIndex] != null) - { - _droppedFrames++; - } - - _writeCursor = (slotIndex + 1) % SlotCount; - lease = new CultMeshFrameWriteLease( - slotIndex, - _nextSequence, - new Memory(_storage, slotIndex * SlotByteLength, SlotByteLength)); + lease = new CultMeshFrameWriteLease(regionLease); return true; } - - _blockedWrites++; lease = default; return false; } @@ -403,29 +376,9 @@ namespace GameCult.Mesh int unavoidableCopyCount = 0, IReadOnlyDictionary? metadata = null) { - ThrowIfDisposed(); - RequireSlot(lease.SlotIndex); - if (byteLength < 0 || byteLength > SlotByteLength) - { - throw new ArgumentOutOfRangeException(nameof(byteLength)); - } - - _unavoidableCopyCount += (ulong)Math.Max(0, unavoidableCopyCount); - var handle = new CultMeshStreamFrameHandle( - StreamId, - lease.Sequence, - timestampNs, - CultMeshStreamBodyTransport.SharedMemory, - durationNs, - byteLength, - resourceKey: $"{StreamId}:slot:{lease.SlotIndex}", - unavoidableCopyCount: unavoidableCopyCount, - metadata: metadata); - _handles[lease.SlotIndex] = handle; - _latestSlot = lease.SlotIndex; - _nextSequence = lease.Sequence + 1; - _publishedFrames++; - return handle; + var generation = _region.Commit( + lease.RegionLease, byteLength, timestampNs, durationNs, unavoidableCopyCount, metadata); + return ToHandle(generation); } public bool TryPublishCopy( @@ -434,7 +387,6 @@ namespace GameCult.Mesh long durationNs, out CultMeshStreamFrameHandle handle) { - ThrowIfDisposed(); if (bytes.Length > SlotByteLength) { throw new ArgumentOutOfRangeException(nameof(bytes)); @@ -453,79 +405,51 @@ namespace GameCult.Mesh public bool TryAcquireLatestRead(out CultMeshFrameReadLease lease) { - ThrowIfDisposed(); - var slotIndex = Volatile.Read(ref _latestSlot); - if (slotIndex < 0) + var request = new CultMeshBodyValidationRequest + { + BodyId = _region.BodyId, + SchemaId = _region.SchemaId, + LayoutVersion = _region.LayoutVersion, + ProducerEpoch = _region.ProducerEpoch, + Capacity = _region.Capacity, + AccessMode = CultMeshBodyAccessMode.ReadOnly + }; + if (!_region.TryAcquireLatestRead(request, out var regionLease)) { lease = default; return false; } - - var handle = _handles[slotIndex]; - if (handle == null) - { - lease = default; - return false; - } - - Interlocked.Increment(ref _readerCounts[slotIndex]); - lease = new CultMeshFrameReadLease( - this, - slotIndex, - handle, - new ReadOnlyMemory(_storage, slotIndex * SlotByteLength, handle.ByteLength)); + var generation = regionLease.Generation; + lease = new CultMeshFrameReadLease(regionLease, ToHandle(generation), generation.SlotIndex); return true; } public CultMeshSharedMemoryFrameRingStats Stats() { - ThrowIfDisposed(); - var latest = _latestSlot < 0 ? 0 : _handles[_latestSlot]?.Sequence ?? 0; + var stats = _region.Stats(); return new CultMeshSharedMemoryFrameRingStats( StreamId, SlotCount, SlotByteLength, - _publishedFrames, - _droppedFrames, - _blockedWrites, - latest, - _unavoidableCopyCount); + stats.PublishedFrames, + stats.DroppedFrames, + stats.BlockedWrites, + checked((ulong)stats.LatestSequence), + stats.UnavoidableCopyCount); } - internal void ReleaseRead(int slotIndex) - { - if (Volatile.Read(ref _disposed) != 0) - { - return; - } + public void Dispose() => _region.Dispose(); - RequireSlot(slotIndex); - Interlocked.Decrement(ref _readerCounts[slotIndex]); - } - - public void Dispose() - { - if (Interlocked.Exchange(ref _disposed, 1) == 0) - { - ArrayPool.Shared.Return(_storage); - } - } - - private void ThrowIfDisposed() - { - if (Volatile.Read(ref _disposed) != 0) - { - throw new ObjectDisposedException(nameof(CultMeshSharedMemoryFrameRing)); - } - } - - private void RequireSlot(int slotIndex) - { - if (slotIndex < 0 || slotIndex >= SlotCount) - { - throw new ArgumentOutOfRangeException(nameof(slotIndex)); - } - } + private CultMeshStreamFrameHandle ToHandle(CultMeshFrameGeneration generation) => new( + StreamId, + checked((ulong)generation.Descriptor.Sequence), + generation.TimestampNs, + CultMeshStreamBodyTransport.SharedMemory, + generation.DurationNs, + checked((int)generation.Descriptor.ByteSize), + resourceKey: $"{StreamId}:slot:{generation.SlotIndex}", + unavoidableCopyCount: generation.UnavoidableCopyCount, + metadata: generation.Metadata); } public sealed class CultMeshStreamCatalog diff --git a/src/GameCult.Mesh/docs/reliability-migration-plan.md b/src/GameCult.Mesh/docs/reliability-migration-plan.md index 531e4b17..89de78d8 100644 --- a/src/GameCult.Mesh/docs/reliability-migration-plan.md +++ b/src/GameCult.Mesh/docs/reliability-migration-plan.md @@ -676,6 +676,40 @@ local shared-memory body and its remote network representation. 7. Decide from measurements whether ordinary local control traffic merits a separate shared-memory lane. Do not build that lane as part of this phase. +### Frame-region authority + +**Owner:** `CultMeshFrameRegion` is the sole owner of one fixed-capacity, +schema/layout-versioned, producer-epoch-bound triple buffer. It owns slot +storage, write reservations, reader protection, publication metadata, latest +generation selection, sequence advancement, and contention statistics. + +**Inputs:** logical body identity, schema identity, layout version, logical +capacity, producer epoch, slot byte length, frame bytes, and commit metadata. +The bounded producer contract permits at most one outstanding write reservation +for the region, so sequence assignment and slot reservation cannot diverge. + +**Outputs:** bounded write leases, immutable generation descriptors, read-only +consumer leases, and owner-derived statistics. Publication installs bytes and +metadata as one locked commit and advances sequence exactly once. + +**Derived state:** `CultMeshSharedMemoryFrameRing` handles and statistics are +compatibility projections of region generations. Capability tokens remain +transport material and do not participate in frame identity or generation +validation. + +**Forbidden writers:** the compatibility ring has no slot buffers, cursors, +reader counts, latest-slot state, frame-handle catalog, sequence counter, or +independent commit path. + +**Shared paths:** direct SoA writes, compatibility zero-copy writes, and +compatibility copy publication all reserve and commit through +`CultMeshFrameRegion`. Direct and compatibility reads acquire the same owner +lease and release the same reader count. + +**Cut line:** the former ring-owned arrays and counters are removed. A frame +region always has exactly three slots; construction with another slot count is +rejected rather than creating a second buffering model. + ### Required invariants - Only an explicitly authorized producer may publish or advance a body. diff --git a/tests/GameCult.Mesh.Tests/CultMeshFrameBodyTests.cs b/tests/GameCult.Mesh.Tests/CultMeshFrameBodyTests.cs new file mode 100644 index 00000000..a492ed89 --- /dev/null +++ b/tests/GameCult.Mesh.Tests/CultMeshFrameBodyTests.cs @@ -0,0 +1,191 @@ +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using FluentAssertions; +using NUnit.Framework; + +namespace GameCult.Mesh.Tests; + +[TestFixture] +public sealed class CultMeshFrameBodyTests +{ + [Test] + public void PublishesOneAtomicSchemaVersionedGenerationPerCommit() + { + using var region = Region(); + region.TryAcquireWrite(out var write).Should().BeTrue(); + write.Sequence.Should().Be(0); + write.Span[..4].Fill(7); + + var generation = region.Commit( + write, + 4, + timestampNs: 12, + metadata: new Dictionary { ["plane"] = "positions" }); + + generation.Descriptor.Sequence.Should().Be(0); + generation.Descriptor.SchemaId.Should().Be("tests.frame.v2"); + generation.Descriptor.LayoutVersion.Should().Be(2); + generation.Descriptor.Capacity.Should().Be(64); + generation.Descriptor.ProducerEpoch.Should().Be(9); + generation.Descriptor.Synchronization.Should().Be(CultMeshBodySynchronization.TripleBuffer); + generation.Descriptor.AccessMode.Should().Be(CultMeshBodyAccessMode.ReadOnly); + region.Stats().PublishedFrames.Should().Be(1); + + Action duplicate = () => region.Commit(write, 4, timestampNs: 13); + duplicate.Should().Throw().WithMessage("*stale or was already committed*"); + region.Stats().PublishedFrames.Should().Be(1); + } + + [Test] + public void RefusesASecondOutstandingWriteAndRecoversAfterCommit() + { + using var region = Region(); + + region.TryAcquireWrite(out var first).Should().BeTrue(); + first.Sequence.Should().Be(0); + region.TryAcquireWrite(out _).Should().BeFalse(); + + first.Span[0] = 10; + region.Commit(first, 1, timestampNs: 1).Descriptor.Sequence.Should().Be(0); + + region.TryAcquireWrite(out var second).Should().BeTrue(); + second.Sequence.Should().Be(1); + second.Span[0] = 11; + region.Commit(second, 1, timestampNs: 2).Descriptor.Sequence.Should().Be(1); + + region.TryAcquireWrite(out var third).Should().BeTrue(); + third.Sequence.Should().Be(2); + region.Stats().BlockedWrites.Should().Be(1); + } + + [Test] + public void RefusesWritesWhenEverySlotHasAReaderLease() + { + using var region = Region(); + var reads = new CultMeshFrameRegionReadLease[3]; + for (var sequence = 0; sequence < 3; sequence++) + { + region.TryAcquireWrite(out var write).Should().BeTrue(); + write.Span[0] = (byte)sequence; + region.Commit(write, 1, sequence); + region.TryAcquireLatestRead(Request(sequence), out reads[sequence]).Should().BeTrue(); + } + + region.TryAcquireWrite(out _).Should().BeFalse(); + region.Stats().BlockedWrites.Should().Be(1); + + reads[1].Dispose(); + region.TryAcquireWrite(out var available).Should().BeTrue(); + available.SlotIndex.Should().Be(1); + reads[0].Dispose(); + reads[2].Dispose(); + } + + [TestCase("wrong", "tests.frame.v2", 2, 9, 64, 0)] + [TestCase("body", "tests.frame.v1", 2, 9, 64, 0)] + [TestCase("body", "tests.frame.v2", 1, 9, 64, 0)] + [TestCase("body", "tests.frame.v2", 2, 8, 64, 0)] + [TestCase("body", "tests.frame.v2", 2, 9, 63, 0)] + [TestCase("body", "tests.frame.v2", 2, 9, 64, 1)] + public void RejectsMismatchedGenerationBeforeExposingBytes( + string bodyId, + string schemaId, + int layoutVersion, + long epoch, + int capacity, + long sequence) + { + using var region = Region(); + region.TryAcquireWrite(out var write).Should().BeTrue(); + write.Span[0] = 42; + region.Commit(write, 1, 0); + var request = new CultMeshBodyValidationRequest + { + BodyId = bodyId, + SchemaId = schemaId, + LayoutVersion = layoutVersion, + ProducerEpoch = epoch, + Capacity = capacity, + Sequence = sequence, + AccessMode = CultMeshBodyAccessMode.ReadOnly + }; + + Action read = () => region.TryAcquireLatestRead(request, out _); + + read.Should().Throw(); + } + + [Test] + public void ReadLeaseIsReadOnlyAndProtectsItsBytesAcrossLaterCommits() + { + using var region = Region(); + region.TryAcquireWrite(out var first).Should().BeTrue(); + first.Span[..4].Fill(11); + region.Commit(first, 4, 0); + region.TryAcquireLatestRead(Request(0), out var protectedRead).Should().BeTrue(); + + for (var value = 12; value <= 13; value++) + { + region.TryAcquireWrite(out var write).Should().BeTrue(); + write.Span[..4].Fill((byte)value); + region.Commit(write, 4, value); + } + + protectedRead.Span.ToArray().Should().OnlyContain(value => value == 11); + protectedRead.Dispose(); + } + + [Test] + public async Task ConcurrentReadersNeverObserveTornBytesOrMetadata() + { + using var region = Region(); + var failures = new ConcurrentQueue(); + + for (var sequence = 0; sequence < 200; sequence++) + { + CultMeshFrameRegionWriteLease write; + while (!region.TryAcquireWrite(out write)) + await Task.Yield(); + var marker = (byte)(sequence % 251 + 1); + write.Span[..64].Fill(marker); + region.Commit( + write, + 64, + sequence, + metadata: new Dictionary { ["marker"] = marker.ToString() }); + + var readers = Enumerable.Range(0, 4).Select(_ => Task.Run(() => + { + if (!region.TryAcquireLatestRead(Request(), out var read)) return; + using (read) + { + var expected = byte.Parse(read.Generation.Metadata["marker"]); + if (read.Span.ToArray().Any(value => value != expected)) + failures.Enqueue($"Torn generation {read.Generation.Descriptor.Sequence}"); + } + })); + await Task.WhenAll(readers); + } + + failures.Should().BeEmpty(); + region.Stats().PublishedFrames.Should().Be(200); + region.Stats().LatestSequence.Should().Be(199); + } + + private static CultMeshFrameRegion Region() => + new("body", "tests.frame.v2", layoutVersion: 2, capacity: 64, producerEpoch: 9, slotByteLength: 64); + + private static CultMeshBodyValidationRequest Request(long? sequence = null) => new() + { + BodyId = "body", + SchemaId = "tests.frame.v2", + LayoutVersion = 2, + ProducerEpoch = 9, + Capacity = 64, + Sequence = sequence, + AccessMode = CultMeshBodyAccessMode.ReadOnly + }; +} diff --git a/tests/GameCult.Mesh.Tests/CultMeshStreamingTests.cs b/tests/GameCult.Mesh.Tests/CultMeshStreamingTests.cs index 46116d72..4364aba3 100644 --- a/tests/GameCult.Mesh.Tests/CultMeshStreamingTests.cs +++ b/tests/GameCult.Mesh.Tests/CultMeshStreamingTests.cs @@ -3440,7 +3440,7 @@ public sealed class CultMeshStreamingTests public void SharedMemoryRingPublishesWritableSlotsWithoutInternalCopies() { var catalog = CatalogWithByteStream(); - using var ring = catalog.CreateSharedMemoryRing("mimir:leap:depth", slotCount: 2, slotByteLength: 16); + using var ring = catalog.CreateSharedMemoryRing("mimir:leap:depth", slotCount: 3, slotByteLength: 16); ring.TryAcquireWriteSlot(out var write).Should().BeTrue(); ReadOnlySpan seed = stackalloc byte[] { 1, 2, 3, 4 }; @@ -3467,7 +3467,7 @@ public sealed class CultMeshStreamingTests public void SharedMemoryRingDoesNotOverwriteSlotsHeldByReaders() { var catalog = CatalogWithByteStream(); - using var ring = catalog.CreateSharedMemoryRing("mimir:leap:depth", slotCount: 1, slotByteLength: 8); + using var ring = catalog.CreateSharedMemoryRing("mimir:leap:depth", slotCount: 3, slotByteLength: 8); ring.TryAcquireWriteSlot(out var firstWrite).Should().BeTrue(); firstWrite.Span[0] = 11; @@ -3475,26 +3475,36 @@ public sealed class CultMeshStreamingTests ring.TryAcquireLatestRead(out var read).Should().BeTrue(); + ring.TryAcquireWriteSlot(out var secondWrite).Should().BeTrue(); + ring.CommitWriteSlot(secondWrite, timestampNs: 2, byteLength: 1); + ring.TryAcquireWriteSlot(out var thirdWrite).Should().BeTrue(); + ring.CommitWriteSlot(thirdWrite, timestampNs: 3, byteLength: 1); + ring.TryAcquireLatestRead(out var thirdRead).Should().BeTrue(); + ring.TryAcquireWriteSlot(out var overwriteSecond).Should().BeTrue(); + ring.CommitWriteSlot(overwriteSecond, timestampNs: 4, byteLength: 1); + ring.TryAcquireLatestRead(out var secondRead).Should().BeTrue(); ring.TryAcquireWriteSlot(out _).Should().BeFalse(); ring.Stats().BlockedWrites.Should().Be(1); read.Dispose(); + thirdRead.Dispose(); + secondRead.Dispose(); - ring.TryAcquireWriteSlot(out var secondWrite).Should().BeTrue(); - secondWrite.Span[0] = 12; - ring.CommitWriteSlot(secondWrite, timestampNs: 2, byteLength: 1); + ring.TryAcquireWriteSlot(out var fifthWrite).Should().BeTrue(); + fifthWrite.Span[0] = 12; + ring.CommitWriteSlot(fifthWrite, timestampNs: 5, byteLength: 1); var stats = ring.Stats(); - stats.PublishedFrames.Should().Be(2); - stats.DroppedFrames.Should().Be(1); - stats.LatestSequence.Should().Be(1); + stats.PublishedFrames.Should().Be(5); + stats.DroppedFrames.Should().Be(2); + stats.LatestSequence.Should().Be(4); } [Test] public void CopyPublishMarksFallbackCopiesExplicitly() { var catalog = CatalogWithByteStream(); - using var ring = catalog.CreateSharedMemoryRing("mimir:leap:depth", slotCount: 2, slotByteLength: 8); + using var ring = catalog.CreateSharedMemoryRing("mimir:leap:depth", slotCount: 3, slotByteLength: 8); ring.TryPublishCopy(stackalloc byte[] { 5, 6, 7 }, timestampNs: 10, durationNs: 2, out var handle) .Should()