diff --git a/src/GameCult.Mesh/docs/reliability-migration-plan.md b/src/GameCult.Mesh/docs/reliability-migration-plan.md index b2153caa..89296dbf 100644 --- a/src/GameCult.Mesh/docs/reliability-migration-plan.md +++ b/src/GameCult.Mesh/docs/reliability-migration-plan.md @@ -669,6 +669,63 @@ Content-session delivery and product lifecycle are proven without claiming a mapped/zero-copy transfer; the managed session still copies and fragments the body in process. +### Phase 4 transport parity and body-plane cut + +**Owner:** CultMesh negotiation selects a body transport from provider-owned +capabilities and consumer demand. The selected transport owns byte movement; +`CultMeshContentTransferService` continues to own content identity, resumable +verification, and atomic cache promotion. CultNet RUDP does not own bulk-body +performance. + +**Inputs:** content hash and size, provider-advertised transport candidates, +consumer-supported transports, same-machine evidence, and platform support. + +**Outputs:** an authorized mapped body for same-machine deployments, or a +dedicated remote byte stream feeding the existing verification/promotion owner. +Typed control state, reactive variables, commands, and receipts remain CultNet +messages and are not smuggled into the bulk stream. + +**Derived state:** selected plane, physical endpoint, mapped-file descriptor, +stream progress, and transport telemetry. None can change content identity, +provider authority, or the final verified cache record. + +**Forbidden writers:** applications and renderers cannot choose an unadvertised +path or turn a local filesystem path into authority. Snapshot and schema-message +helpers cannot regain ownership of immutable body bytes. A remote stream cannot +publish a completed body without the transfer owner's hash verification and +atomic promotion. + +**Shared paths:** every remote plane terminates in the same partial-file, +checkpoint, final-hash, and promotion primitives. Same-machine mapping uses the +same advertised content hash and provider authorization but does not copy the +body merely to prove that two processes inhabit one machine. + +**Cut line:** request-window and scheduler-yield tuning is not the bulk-content +roadmap. RUDP remains a compatibility fallback while dedicated stream and local +mapping planes are integrated. The old fallback stays unable to become the +preferred same-machine or remote bulk plane through timing tweaks. + +**Parity evidence:** `tools/GameCult.TransportParity` measures the public +CultMesh RUDP content path against file mapping, TCP, and .NET's MsQuic-backed +QUIC stream with the Aetheria 56,204,750-byte body size. On the 2026-07-19 +Windows development host, a representative released-source run opened the +existing mapped body in 10.9 ms, moved and verified it over TCP in 213.8 ms +(250.7 MiB/s), moved and verified it over QUIC in 753.4 ms (71.1 MiB/s), and +moved it through CultMesh RUDP in 5,322.9 ms (10.1 MiB/s) while emitting +129,241,066 server bytes. Repeated QUIC runs reached 87.0-107.4 MiB/s; repeated +RUDP runs reached 10.1-13.0 MiB/s. This is a plane-selection result, not a case +for a more elaborate home-grown congestion controller. + +**Dedicated references:** .NET's stable `System.Net.Quic` API delegates to +MsQuic on supported platforms: +https://learn.microsoft.com/dotnet/fundamentals/networking/quic/quic-overview. +MsQuic publishes its performance methodology and dashboard at +https://microsoft.github.io/msquic/. Valve GameNetworkingSockets remains a +candidate for the cross-platform realtime message plane because it provides +reliable/unreliable messages, acknowledgement vectors, fragmentation, +congestion behavior, encryption, and priority lanes: +https://github.com/ValveSoftware/GameNetworkingSockets. + ### Phase 5 verified CDN mapped-body slice **Owner:** `CultMeshContentTransferService` remains the sole writer and promoter diff --git a/tools/GameCult.TransportParity/GameCult.TransportParity.csproj b/tools/GameCult.TransportParity/GameCult.TransportParity.csproj new file mode 100644 index 00000000..4a073fe7 --- /dev/null +++ b/tools/GameCult.TransportParity/GameCult.TransportParity.csproj @@ -0,0 +1,11 @@ + + + Exe + net10.0 + enable + enable + + + + + diff --git a/tools/GameCult.TransportParity/Program.cs b/tools/GameCult.TransportParity/Program.cs new file mode 100644 index 00000000..d729326a --- /dev/null +++ b/tools/GameCult.TransportParity/Program.cs @@ -0,0 +1,276 @@ +using System.Diagnostics; +using System.IO.MemoryMappedFiles; +using System.Net; +using System.Net.Quic; +using System.Net.Security; +using System.Net.Sockets; +using System.Security.Authentication; +using System.Security.Cryptography; +using System.Security.Cryptography.X509Certificates; +using GameCult.Caching; +using GameCult.Mesh; +using GameCult.Networking; + +var payloadBytes = ReadPayloadBytes(args); +var payload = new byte[payloadBytes]; +new Random(0xAE7E).NextBytes(payload); +var expectedHash = Convert.ToHexString(SHA256.HashData(payload)); + +Console.WriteLine($"payloadBytes={payloadBytes} quicSupported={QuicListener.IsSupported}"); +Print(MeasureMappedFile(payload)); +var tcp = await MeasureTcpAsync(payload, expectedHash); +Print(tcp); + +if (QuicListener.IsSupported) + Print(await MeasureQuicAsync(payload, expectedHash)); +else + Console.WriteLine("plane=quic status=unsupported"); + +Print(await MeasureCultMeshRudpAsync(payload)); + +static int ReadPayloadBytes(string[] args) +{ + const int defaultBytes = 56_204_750; + var index = Array.IndexOf(args, "--bytes"); + if (index < 0) return defaultBytes; + if (index + 1 >= args.Length || !int.TryParse(args[index + 1], out var bytes) || bytes <= 0) + throw new ArgumentException("--bytes requires a positive 32-bit integer."); + return bytes; +} + +static void Print(Result result) => + Console.WriteLine( + $"plane={result.Plane} elapsedMs={result.Elapsed.TotalMilliseconds:F1} " + + (result.GoodputMiBps.HasValue ? $"goodputMiBps={result.GoodputMiBps.Value:F1}" : "") + + (result.WireBytes.HasValue ? $" wireBytes={result.WireBytes.Value}" : string.Empty)); + +static Result MeasureMappedFile(byte[] payload) +{ + var source = TempPath("mapped-source"); + File.WriteAllBytes(source, payload); + var elapsed = Stopwatch.StartNew(); + try + { + using var mapping = MemoryMappedFile.CreateFromFile( + source, FileMode.Open, null, 0, MemoryMappedFileAccess.Read); + using var view = mapping.CreateViewAccessor(0, 0, MemoryMappedFileAccess.Read); + if (view.ReadByte(0) != payload[0] || view.ReadByte(payload.LongLength - 1) != payload[^1]) + throw new InvalidDataException("Mapped body did not expose the provider file."); + elapsed.Stop(); + return Result.CreateOpen("mapped-file-open", elapsed.Elapsed); + } + finally + { + File.Delete(source); + } +} + +static async Task MeasureTcpAsync(byte[] payload, string expectedHash) +{ + using var listener = new TcpListener(IPAddress.Loopback, 0); + listener.Start(); + var endpoint = (IPEndPoint)listener.LocalEndpoint; + var server = Task.Run(async () => + { + using var peer = await listener.AcceptTcpClientAsync(); + await peer.GetStream().WriteAsync(payload); + peer.Client.Shutdown(SocketShutdown.Send); + }); + + var output = TempPath("tcp"); + var elapsed = Stopwatch.StartNew(); + using (var client = new TcpClient()) + { + await client.ConnectAsync(endpoint.Address, endpoint.Port); + await using var file = new FileStream(output, FileMode.CreateNew, FileAccess.Write, FileShare.None, + 1024 * 1024, FileOptions.Asynchronous | FileOptions.SequentialScan); + await client.GetStream().CopyToAsync(file); + await file.FlushAsync(); + } + await server; + VerifyAndDelete(output, expectedHash); + elapsed.Stop(); + return Result.Create("tcp", payload.LongLength, elapsed.Elapsed); +} + +static async Task MeasureQuicAsync(byte[] payload, string expectedHash) +{ + var protocol = new SslApplicationProtocol("cultmesh-parity"); + using var certificate = CreateCertificate(); + await using var listener = await QuicListener.ListenAsync(new QuicListenerOptions + { + ListenEndPoint = new IPEndPoint(IPAddress.Loopback, 0), + ApplicationProtocols = [protocol], + ConnectionOptionsCallback = (_, _, _) => ValueTask.FromResult(new QuicServerConnectionOptions + { + DefaultCloseErrorCode = 0, + DefaultStreamErrorCode = 0, + ServerAuthenticationOptions = new SslServerAuthenticationOptions + { + ApplicationProtocols = [protocol], + EnabledSslProtocols = SslProtocols.Tls13, + ServerCertificate = certificate + } + }) + }); + + var server = Task.Run(async () => + { + await using var connection = await listener.AcceptConnectionAsync(); + await using var stream = await connection.OpenOutboundStreamAsync(QuicStreamType.Unidirectional); + await stream.WriteAsync(payload); + stream.CompleteWrites(); + await stream.WritesClosed; + }); + + var output = TempPath("quic"); + var elapsed = Stopwatch.StartNew(); + await using (var connection = await QuicConnection.ConnectAsync(new QuicClientConnectionOptions + { + RemoteEndPoint = listener.LocalEndPoint, + DefaultCloseErrorCode = 0, + DefaultStreamErrorCode = 0, + MaxInboundUnidirectionalStreams = 1, + ClientAuthenticationOptions = new SslClientAuthenticationOptions + { + ApplicationProtocols = [protocol], + EnabledSslProtocols = SslProtocols.Tls13, + RemoteCertificateValidationCallback = (_, _, _, _) => true + } + })) + await using (var stream = await connection.AcceptInboundStreamAsync()) + await using (var file = new FileStream(output, FileMode.CreateNew, FileAccess.Write, FileShare.None, + 1024 * 1024, FileOptions.Asynchronous | FileOptions.SequentialScan)) + { + await stream.CopyToAsync(file); + await file.FlushAsync(); + } + await server; + VerifyAndDelete(output, expectedHash); + elapsed.Stop(); + return Result.Create("quic-msquic", payload.LongLength, elapsed.Elapsed); +} + +static async Task MeasureCultMeshRudpAsync(byte[] payload) +{ + var artifact = CultMesh.PackCdnArtifact("parity/body", payload); + using var providerCache = new CultCache(CultMesh.CreateCultCacheDocumentRegistry( + typeof(CultMeshCdnArtifactManifest), typeof(CultMeshCdnArtifactChunk))); + await CultMeshCdn.PublishAsync(providerCache, artifact); + + using var socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); + socket.Bind(new IPEndPoint(IPAddress.Loopback, 0)); + using var wireServer = new RudpCultNetSchemaServer(new RudpCultNetSchemaServerOptions + { + RuntimeId = "cultmesh-transport-parity", + Socket = socket, + MaxFragmentBytes = 1024, + MaxPendingReliablePackets = 8192 + }); + using var contentServer = new CultMeshContentServer(wireServer, providerCache); + using var pumpCancellation = new CancellationTokenSource(); + var pump = Task.Run(async () => + { + while (!pumpCancellation.IsCancellationRequested) + { + var progress = await wireServer.PollAvailableAsync(256); + wireServer.PollResends(); + if (progress.TransportItemsConsumed == 0) + await Task.Delay(1, pumpCancellation.Token); + } + }); + + var endpoint = $"rudp://127.0.0.1:{wireServer.LocalEndPoint.Port}"; + using var discovery = new CultMeshDiscoveryService([new RouteSource(endpoint)]); + using var sessions = new CultMeshSessionManager( + discovery, [new CultMeshSchemaTransportConnector()]); + var provider = new CultMeshSessionContentProvider( + "parity.provider", sessions, CultMeshEndpointId.Parse("service:parity.provider"), + new CultMeshSessionContentProviderOptions { ResponseTimeout = TimeSpan.FromMinutes(2) }); + var directory = Path.Combine(Path.GetTempPath(), "cultmesh-transport-parity", Guid.NewGuid().ToString("N")); + using var transferState = new CultCache(CultMesh.CreateCultCacheDocumentRegistry( + typeof(CultMeshContentTransferStateDocument))); + var transfer = new CultMeshContentTransferService( + transferState, [provider], new CultMeshContentTransferOptions(directory)); + + var elapsed = Stopwatch.StartNew(); + try + { + var path = await transfer.FetchAsync(artifact.Manifest); + elapsed.Stop(); + if (!File.ReadAllBytes(path).AsSpan().SequenceEqual(payload)) + throw new InvalidDataException("CultMesh RUDP payload did not match source."); + return Result.Create("cultmesh-rudp", payload.LongLength, elapsed.Elapsed, wireServer.Stats.BytesSent); + } + finally + { + pumpCancellation.Cancel(); + try { await pump; } catch (OperationCanceledException) { } + if (Directory.Exists(directory)) Directory.Delete(directory, true); + } +} + +static X509Certificate2 CreateCertificate() +{ + using var key = RSA.Create(2048); + var request = new CertificateRequest("CN=localhost", key, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1); + request.CertificateExtensions.Add(new X509BasicConstraintsExtension(false, false, 0, false)); + request.CertificateExtensions.Add(new X509KeyUsageExtension(X509KeyUsageFlags.DigitalSignature, false)); + request.CertificateExtensions.Add(new X509EnhancedKeyUsageExtension( + new OidCollection { new("1.3.6.1.5.5.7.3.1") }, false)); + var names = new SubjectAlternativeNameBuilder(); + names.AddDnsName("localhost"); + names.AddIpAddress(IPAddress.Loopback); + request.CertificateExtensions.Add(names.Build()); + request.CertificateExtensions.Add(new X509SubjectKeyIdentifierExtension(request.PublicKey, false)); + using var certificate = request.CreateSelfSigned( + DateTimeOffset.UtcNow.AddMinutes(-1), DateTimeOffset.UtcNow.AddHours(1)); + return X509CertificateLoader.LoadPkcs12(certificate.Export(X509ContentType.Pfx), null); +} + +static string TempPath(string plane) => + Path.Combine(Path.GetTempPath(), $"cultmesh-parity-{plane}-{Guid.NewGuid():N}.body"); + +static void VerifyAndDelete(string path, string expectedHash) +{ + try + { + using var input = File.OpenRead(path); + var actualHash = Convert.ToHexString(SHA256.HashData(input)); + if (!actualHash.Equals(expectedHash, StringComparison.Ordinal)) + throw new InvalidDataException($"Body hash mismatch: expected {expectedHash}, got {actualHash}."); + } + finally + { + File.Delete(path); + } +} + +internal sealed class RouteSource(string endpoint) : ICultMeshLookupSource +{ + public string SourceId => "parity-route"; + + public Task> LookupAsync( + CultMeshDiscoveryQuery query, CancellationToken cancellationToken = default) + { + var now = DateTimeOffset.UtcNow; + IReadOnlyList observations = + [ + new( + new CultMeshVerseDescriptor( + "parity", "Transport parity", CultMeshVerseAuthorityModel.OperatorCluster, + new CultMeshVerseCompatibility("cultmesh.v1", "parity"), [endpoint]), + SourceId, now, now.AddMinutes(1), CultMeshDiscoveryTrust.Signed) + ]; + return Task.FromResult(observations); + } +} + +internal sealed record Result(string Plane, TimeSpan Elapsed, double? GoodputMiBps, long? WireBytes) +{ + public static Result Create(string plane, long bytes, TimeSpan elapsed, long? wireBytes = null) => + new(plane, elapsed, bytes / 1024d / 1024d / elapsed.TotalSeconds, wireBytes); + + public static Result CreateOpen(string plane, TimeSpan elapsed) => + new(plane, elapsed, null, null); +} diff --git a/tools/GameCult.TransportParity/README.md b/tools/GameCult.TransportParity/README.md new file mode 100644 index 00000000..2b7daeeb --- /dev/null +++ b/tools/GameCult.TransportParity/README.md @@ -0,0 +1,25 @@ +# CultMesh transport parity harness + +This harness compares the current public CultMesh content-session path with +dedicated byte streams under the same loopback conditions and payload size. +It is evidence for transport-plane selection, not a production transport. + +The measured paths are: + +- Authorized same-machine file mapping open and first/last-byte access. The + provider body is created before the timer because it already exists in the + real deployment. +- CultMesh content transfer over CultNet RUDP, including chunk verification, + partial-file writes, final SHA-256 verification, and atomic promotion. +- TCP stream to a file, followed by SHA-256 verification. +- QUIC stream to a file, followed by SHA-256 verification. .NET delegates QUIC + to MsQuic on supported platforms. + +Run the Aetheria-sized comparison with: + +```powershell +dotnet run --project tools/GameCult.TransportParity -c Release -- --bytes 56204750 +``` + +The default payload is 56,204,750 bytes. Results report elapsed time, +application goodput, and RUDP wire bytes where available.