Drain RUDP content traffic without per-packet sleeps

This commit is contained in:
Meta Vens 2026-07-16 02:36:07 +01:00
commit 25231429c1
5 changed files with 136 additions and 28 deletions

View file

@ -49,7 +49,10 @@ them in manifest-offset order. If one request fails, the owner observes the
rest of that window before returning; fetched-but-uncommitted bytes never become
trusted resume state. Concurrent artifacts have independent windows.
RUDP schema hosts should drain immediately available transport work with
`PollAvailableAsync`. Its result distinguishes transport items consumed from
application messages dispatched, so ACK and connection traffic counts as
progress without impersonating a message or triggering an idle delay.
RUDP schema hosts drain immediately available transport work with
`PollAvailableAsync`, and the managed schema client pump applies the same
bounded-drain rule. Transport packets, including fragments, ACKs, and connection
traffic, count as progress without impersonating an application message or
paying one operating-system scheduler delay per packet. Reliable sends are
paced in one 32-packet acknowledgement window rather than one fragment at a
time.

View file

@ -651,8 +651,12 @@ descriptors; the managed content protocol carries bounded payload responses.
**Verification layer:** Mesh tests transfer a multi-chunk body through one
managed session, assert zero snapshot requests, assert warm committed reuse
without another network request, and round-trip both wire messages through the
schema dispatcher. RUDP schema-host tests distinguish control-packet progress
from dispatched messages and drain bounded available work without idle sleeps.
schema dispatcher. RUDP schema hosts and managed clients distinguish transport
progress from dispatched messages and drain bounded available work without
idle sleeps. Wire sends pace one 32-packet acknowledgement window at a time
instead of paying a Windows scheduler quantum for every fragment; a real UDP
content-session test transfers a four-chunk, one-megabyte request window through
the public transfer owner within its ten-second regression bound.
The released EveUnity/Aetheria cold run now promotes the 13,006,384-byte bundle
to its exact SHA-256 `.body` under the unchanged 300-second deadline with no
partial left behind. The combined cold gameplay witness remains open because

View file

@ -247,15 +247,16 @@ namespace GameCult.Networking
return;
}
var message = transport.ReceiveSchemaMessageOnce();
transport.PollResends();
if (message != null)
var consumed = 0;
while (consumed < 256 && transport.TryReceiveOnce(out var frame))
{
Dispatch(message);
consumed++;
if (frame != null && string.Equals(frame.ChannelId, "schema", StringComparison.Ordinal))
Dispatch(CultNetSchemaMessageSerialization.Deserialize(frame.Payload));
}
Thread.Sleep(1);
transport.PollResends();
if (consumed == 0)
Thread.Sleep(1);
}
}
catch (ObjectDisposedException) when (_disposed)

View file

@ -1509,7 +1509,10 @@ namespace GameCult.Networking
public sealed class CultNetRudpSocketTransportConnection : IDisposable
{
private const int MinimumReceiveBufferBytes = 4 * 1024 * 1024;
private const int WireBurstPackets = 1;
// One acknowledgement carries the preceding 32-packet receive mask.
// Pace at that transport window instead of sleeping after every fragment;
// a one-millisecond sleep can consume a full scheduler quantum on Windows.
private const int WireBurstPackets = 32;
private readonly Socket _socket;
private readonly CultNetRudpSession _session;
private readonly CultNetRudpSocketMode _mode;
@ -1837,12 +1840,25 @@ namespace GameCult.Networking
/// Polls the UDP socket once and returns the next delivered transport frame if one is available.
/// </summary>
public CultNetTransportFrame? ReceiveOnce()
{
TryReceiveOnce(out var delivered);
return delivered;
}
/// <summary>
/// Consumes one available transport work item and reports progress independently
/// of whether that packet completed an application frame.
/// </summary>
public bool TryReceiveOnce(out CultNetTransportFrame? delivered)
{
if (_deliveredFrames.Count > 0)
{
return _deliveredFrames.Dequeue();
delivered = _deliveredFrames.Dequeue();
return true;
}
delivered = null;
var buffer = new byte[65535];
EndPoint remote = new IPEndPoint(IPAddress.Any, 0);
int received;
@ -1850,7 +1866,7 @@ namespace GameCult.Networking
{
if (!_socket.Poll(0, SelectMode.SelectRead))
{
return null;
return false;
}
received = _socket.ReceiveFrom(buffer, ref remote);
@ -1859,7 +1875,7 @@ namespace GameCult.Networking
error.SocketErrorCode == SocketError.WouldBlock ||
error.SocketErrorCode == SocketError.TimedOut)
{
return null;
return false;
}
catch (SocketException error) when (
error.SocketErrorCode == SocketError.ConnectionReset ||
@ -1867,7 +1883,7 @@ namespace GameCult.Networking
error.SocketErrorCode == SocketError.Shutdown)
{
DisconnectReason = Array.Empty<byte>();
return null;
return false;
}
_stats.BytesReceived += received;
@ -1877,7 +1893,7 @@ namespace GameCult.Networking
}
else if (!_remoteEndPoint.Equals(remote))
{
return null;
return true;
}
var wire = new byte[received];
@ -1887,7 +1903,7 @@ namespace GameCult.Networking
if (_mode == CultNetRudpSocketMode.Server && packet.PacketType == CultNetRudpPacketType.Connect)
{
SendPacket(_session.AcceptConnect(packet, NowMs()));
return null;
return true;
}
var result = _session.Receive(packet, NowMs());
@ -1902,7 +1918,7 @@ namespace GameCult.Networking
if (result.Disconnected)
{
DisconnectReason = result.DisconnectReason;
return null;
return true;
}
foreach (var frame in result.Delivered)
@ -1915,7 +1931,7 @@ namespace GameCult.Networking
_stats.FramesReceived++;
}
var delivered = _deliveredFrames.Count > 0 ? _deliveredFrames.Dequeue() : null;
delivered = _deliveredFrames.Count > 0 ? _deliveredFrames.Dequeue() : null;
if (packet.PacketType == CultNetRudpPacketType.Accept ||
packet.PacketType == CultNetRudpPacketType.Data ||
delivered != null)
@ -1923,7 +1939,7 @@ namespace GameCult.Networking
SendPacket(_session.CreateAck());
}
return delivered;
return true;
}
/// <summary>
@ -1941,7 +1957,7 @@ namespace GameCult.Networking
for (var index = 0; index < packets.Count; index++)
{
SendPacket(packets[index]);
if ((index + 1) % WireBurstPackets == 0)
if ((index + 1) % WireBurstPackets == 0 && index + 1 < packets.Count)
Thread.Sleep(1);
}
}
@ -2096,7 +2112,9 @@ namespace GameCult.Networking
public sealed class CultNetRudpSocketTransportServer : IDisposable
{
private const int MinimumReceiveBufferBytes = 4 * 1024 * 1024;
private const int WireBurstPackets = 1;
// Keep server response pacing aligned with the 32-packet ACK mask. Large
// content responses otherwise pay one Windows scheduler quantum per 1 KiB.
private const int WireBurstPackets = 32;
private readonly Socket _socket;
private readonly uint _connectionId;
private readonly uint _initialSequence;
@ -2335,7 +2353,7 @@ namespace GameCult.Networking
for (var index = 0; index < packets.Count; index++)
{
SendPacket(peer.RemoteEndPoint, packets[index]);
if ((index + 1) % WireBurstPackets == 0)
if ((index + 1) % WireBurstPackets == 0 && index + 1 < packets.Count)
Thread.Sleep(1);
}
}

View file

@ -1,7 +1,10 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Threading.Tasks;
using FluentAssertions;
@ -66,6 +69,81 @@ public sealed class CultMeshContentSessionTests
"all chunk requests borrow one identity-first content session");
}
[Test]
public async Task RudpContentSessionCarriesConcurrentChunkWindowWithoutPerFragmentSchedulerDelay()
{
var payload = Enumerable.Range(0, 1024 * 1024).Select(value => (byte)(value % 251)).ToArray();
var artifact = CultMesh.PackCdnArtifact("aetheria/world/rudp", 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-content-rudp-test",
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[] { new RouteSource(endpoint) });
using var sessions = new CultMeshSessionManager(
discovery,
new ICultMeshTransportConnector[] { new CultMeshSchemaTransportConnector() });
var provider = new CultMeshSessionContentProvider(
"aetheria.daemon",
sessions,
CultMeshEndpointId.Parse("service:aetheria.daemon"),
new CultMeshSessionContentProviderOptions { ResponseTimeout = TimeSpan.FromSeconds(20) });
using var transferState = new CultCache(CultMesh.CreateCultCacheDocumentRegistry(
typeof(CultMeshContentTransferStateDocument)));
var transfer = new CultMeshContentTransferService(
transferState,
new[] { provider },
new CultMeshContentTransferOptions(_directory));
var elapsed = Stopwatch.StartNew();
string path;
try
{
path = await transfer.FetchAsync(artifact.Manifest);
}
catch (Exception error)
{
var stats = wireServer.Stats;
Assert.Fail(
$"RUDP content transfer failed after {elapsed.Elapsed}; " +
$"server sent {stats.BytesSent} bytes and received {stats.BytesReceived} bytes; " +
$"pump status is {pump.Status}: {error}");
return;
}
finally
{
pumpCancellation.Cancel();
try { await pump; }
catch (OperationCanceledException) { }
}
elapsed.Stop();
File.ReadAllBytes(path).Should().Equal(payload);
elapsed.Elapsed.Should().BeLessThan(TimeSpan.FromSeconds(10),
"a bounded content request window must not pay one scheduler quantum per RUDP fragment");
}
[Test]
public void ContentWireMessagesRoundTripThroughTheSchemaDispatcher()
{
@ -93,7 +171,11 @@ public sealed class CultMeshContentSessionTests
private sealed class RouteSource : ICultMeshLookupSource
{
public string SourceId => "odin";
private readonly string _endpoint;
public RouteSource(string endpoint = "rudp://content.test:3076") => _endpoint = endpoint;
public string SourceId => "test-rendezvous";
public Task<IReadOnlyList<CultMeshDiscoveryObservation>> LookupAsync(
CultMeshDiscoveryQuery query,
@ -108,7 +190,7 @@ public sealed class CultMeshContentSessionTests
"Aetheria",
CultMeshVerseAuthorityModel.OperatorCluster,
new CultMeshVerseCompatibility("cultmesh.v1", "rules"),
new[] { "rudp://content.test:3076" }),
new[] { _endpoint }),
SourceId,
now,
now.AddMinutes(1),