From 4da8bbe291f88e5c34ed1f8d0e707ce7f68cb101 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 30 Sep 2026 09:53:06 +0200 Subject: [PATCH] Ack Cut 1d batch 2 (C#): an Ack does not retire a Connect awaiting its Accept; the fresh attempt jumps by the receive window less one While a Connect awaits its Accept, only an Accept the client honours retires it. An Ack that names the Connect (a server's reply to a repeat or a stale copy) no longer wedges the client with nothing to resend. The Connect payload lives on the session, so a fresh attempt can always be built. The fresh attempt uses the abandoned sequence plus the receive window less one (serial), so a late copy of the abandoned Connect stays inside the new one's stale window; only a session's first Connect draws at random. Co-Authored-By: Claude Sonnet 5.5 --- src/GameCult.Networking/CultNetTransport.cs | 51 +++---- .../CultNetRudpConnectGenerationTests.cs | 130 ++++++++++++++++++ 2 files changed, 156 insertions(+), 25 deletions(-) diff --git a/src/GameCult.Networking/CultNetTransport.cs b/src/GameCult.Networking/CultNetTransport.cs index 187f2a6b..9799cb38 100644 --- a/src/GameCult.Networking/CultNetTransport.cs +++ b/src/GameCult.Networking/CultNetTransport.cs @@ -926,6 +926,9 @@ namespace GameCult.Networking // When the unanswered Connect first went out; DueResends abandons it for a fresh attempt once // ConnectAttemptMs has passed. private long _connectStartedAtMs; + // The payload of the Connect this side sent, kept so a fresh attempt can always be built + // whatever became of the pending packet. + private byte[] _connectPayload = Array.Empty(); private long? _lastReceivedAtMs; private uint? _highestReceivedSequence; private readonly HashSet _receivedSequences = new HashSet(); @@ -952,27 +955,23 @@ namespace GameCult.Networking ValidateLimits(options.InitialSequence, options.MaxPendingReliablePackets); ConnectionId = options.ConnectionId; - _nextSequence = options.InitialSequence ?? DrawSequence(1); + _nextSequence = options.InitialSequence ?? DrawSequence(); ResendDelayMs = options.ResendDelayMs; _maxPendingReliablePackets = options.MaxPendingReliablePackets; } /// - /// A sequence drawn from a secure source in [, 2^31). The Connect's - /// sequence is what tells a peer whether a Connect repeats one it already accepted or starts a - /// new session, so two sessions must not share one by default. A floor above the range draws - /// nothing new: the caller keeps its own sequence. + /// A sequence drawn from a secure source in [1, 2^31). The Connect's sequence is what tells a + /// peer whether a Connect repeats one it already accepted or starts a new session, so two + /// sessions must not share one by default. /// - private static uint DrawSequence(uint floor) + private static uint DrawSequence() { - floor = Math.Max(1u, floor); const uint ceiling = 1u << 31; - if (floor >= ceiling) - return floor; var bytes = new byte[4]; using (var random = System.Security.Cryptography.RandomNumberGenerator.Create()) random.GetBytes(bytes); - return floor + BitConverter.ToUInt32(bytes, 0) % (ceiling - floor); + return 1u + BitConverter.ToUInt32(bytes, 0) % (ceiling - 1u); } // Whether `sequence` is at or before `mark` in serial order, within the receive window. The @@ -1061,6 +1060,7 @@ namespace GameCult.Networking _connectSequence = packet.Sequence; _awaitingAccept = true; _connectStartedAtMs = nowMs; + _connectPayload = packet.Payload ?? Array.Empty(); TrackReliable(packet, nowMs); return packet; } @@ -1249,7 +1249,11 @@ namespace GameCult.Networking { return new CultNetRudpReceiveResult(); } - ApplyAcknowledgements(packet); + // While this side's Connect awaits its Accept, only the Accept it honours retires it: an Ack + // that names the Connect (a server's reply to a repeat or a stale copy) says the server did + // not start a session. + if (honoursAccept || !_awaitingAccept) + ApplyAcknowledgements(packet); var readyToSend = PromoteQueuedReliable(nowMs); _lastReceivedAtMs = nowMs; @@ -1661,23 +1665,20 @@ namespace GameCult.Networking } // A Connect unanswered for ConnectAttemptMs is replaced, not retransmitted further, by a Connect - // with a newly drawn sequence and the same payload. Nothing was ever sent in an unanswered - // generation, so no sequence issued so far is owed; the draw stays above them, so a frame the - // peer still remembers from an earlier generation of this session stays at or before the new - // Connect. + // with the same payload and the abandoned sequence plus the receive window less one. Nothing + // was ever sent in an unanswered generation, so no sequence issued so far is owed. The jump + // keeps a late copy of the abandoned Connect inside the new one's stale window, so a server + // that took the new Connect answers the copy with an Ack instead of restarting; and it leaves + // the stale window of whatever generation the server holds, unless that generation sits + // exactly at the jump, and then the next attempt leaves it. The first Connect of a session is + // the only one drawn at random. private CultNetRudpPacket? AbandonUnansweredConnect(long nowMs) { - if (!_awaitingAccept || nowMs - _connectStartedAtMs < ConnectAttemptMs) + if (!_awaitingAccept || nowMs - _connectStartedAtMs < ConnectAttemptMs || !_connectSequence.HasValue) return null; - byte[] payload; - lock (_pendingReliableGate) - { - if (!_connectSequence.HasValue || !_pendingReliable.TryGetValue(_connectSequence.Value, out var pending)) - return null; - payload = pending.Packet.Payload ?? Array.Empty(); - } - _nextSequence = DrawSequence(_nextSequence); - return CreateConnect(nowMs, payload); + var jumped = (ulong)_connectSequence.Value + ReceivedSequenceWindow - 1; + _nextSequence = (uint)Math.Min(jumped, uint.MaxValue - 1); + return CreateConnect(nowMs, _connectPayload); } // The handshake's one act on the watermark: the peer's Connect or Accept is the first sequence diff --git a/tests/GameCult.Networking.Tests/CultNetRudpConnectGenerationTests.cs b/tests/GameCult.Networking.Tests/CultNetRudpConnectGenerationTests.cs index 1d24d722..87249dd4 100644 --- a/tests/GameCult.Networking.Tests/CultNetRudpConnectGenerationTests.cs +++ b/tests/GameCult.Networking.Tests/CultNetRudpConnectGenerationTests.cs @@ -583,6 +583,136 @@ namespace GameCult.Networking.Tests Assert.That(Encoding.UTF8.GetString(server.ReceiveOnce()!.Payload), Is.EqualTo("after")); } + // Ack Cut 1d, batch 2: the connect-attempt timeout. + + /// + /// A server that keeps a session answers a client's repeated or stale Connect with an Ack that + /// may name the client's pending Connect. That Ack says no session started: only an Accept the + /// client honours retires its Connect, so the attempt still times out and is replaced. + /// + [Test] + public void AnAckNamingThePendingConnectDoesNotRetireIt() + { + var server = Session(500); + var old = Session(1); + var oldAccept = server.AcceptConnect(old.CreateConnect(0), 0); + old.Receive(oldAccept, 0); + server.Receive(old.CreateAckForReceived(oldAccept.Sequence), 0); + + var restarted = Session(1); + var first = restarted.CreateConnect(0, Encoding.UTF8.GetBytes("join")); + var reply = server.AcceptConnect(first, 1); + Assert.That(reply.PacketType, Is.EqualTo(CultNetRudpPacketType.Ack)); + Assert.That(NamesSequence(reply, first.Sequence), Is.True, "the Ack must name the pending Connect for this test to bite"); + restarted.Receive(reply, 1); + Assert.That(restarted.Connected, Is.False); + Assert.That(restarted.PendingReliableSequences, Is.EqualTo(new[] { first.Sequence }), "an Ack retired the Connect"); + + var fresh = restarted.DueResends(3_000); + Assert.That(fresh, Has.Count.EqualTo(1), "the client waits for ever with nothing to resend"); + Assert.That(Encoding.UTF8.GetString(fresh[0].Payload), Is.EqualTo("join")); + var accept = server.AcceptConnect(fresh[0], 3_000); + Assert.That(accept.PacketType, Is.EqualTo(CultNetRudpPacketType.Accept)); + restarted.Receive(accept, 3_000); + Assert.That(restarted.Connected, Is.True); + } + + [Test] + public void ALateCopyOfAnAbandonedConnectIsStaleOnceItsReplacementIsAccepted() + { + var server = Session(500); + var client = Session(10); + var abandoned = client.CreateConnect(0); + var fresh = client.DueResends(3_000); + Assert.That(fresh, Has.Count.EqualTo(1)); + Assert.That(fresh[0].Sequence, Is.EqualTo(abandoned.Sequence + 4_095)); + var accept = server.AcceptConnect(fresh[0], 3_001); + client.Receive(accept, 3_002); + server.Receive(client.CreateAckForReceived(accept.Sequence), 3_002); + Assert.That(client.Connected, Is.True); + var a = Send(client, "a"); + Assert.That(Names(server.Receive(a, 3_003)), Is.EqualTo(new[] { "a" })); + client.Receive(server.CreateAckForReceived(a.Sequence), 3_003); + + Assert.That(server.ConnectRepeats(abandoned), Is.True, "the late copy would restart the server"); + var reply = server.AcceptConnect(abandoned, 3_004); + Assert.That(reply.PacketType, Is.EqualTo(CultNetRudpPacketType.Ack)); + client.Receive(reply, 3_005); + Assert.That(client.Connected, Is.True); + Assert.That(Names(server.Receive(Send(client, "b"), 3_006)), Is.EqualTo(new[] { "b" })); + } + + [Test] + public void AServerSittingAtTheJumpIsLeftByTheNextAttempt() + { + var server = Session(500); + var old = Session(5_095); + var oldAccept = server.AcceptConnect(old.CreateConnect(0), 0); + old.Receive(oldAccept, 0); + server.Receive(old.CreateAckForReceived(oldAccept.Sequence), 0); + + var restarted = Session(1_000); + var first = restarted.CreateConnect(0, Encoding.UTF8.GetBytes("join")); + restarted.Receive(server.AcceptConnect(first, 1), 1); + Assert.That(restarted.Connected, Is.False); + + var second = restarted.DueResends(3_000)[0]; + Assert.That(second.Sequence, Is.EqualTo(5_095u), "the jump lands on the server's generation"); + var reply = server.AcceptConnect(second, 3_001); + Assert.That(reply.PacketType, Is.EqualTo(CultNetRudpPacketType.Ack)); + restarted.Receive(reply, 3_001); + Assert.That(restarted.Connected, Is.False); + + var third = restarted.DueResends(6_000)[0]; + Assert.That(third.Sequence, Is.EqualTo(5_095u + 4_095u)); + var accept = server.AcceptConnect(third, 6_001); + Assert.That(accept.PacketType, Is.EqualTo(CultNetRudpPacketType.Accept)); + restarted.Receive(accept, 6_001); + Assert.That(restarted.Connected, Is.True); + } + + /// + /// A pinned client that restarts on the same address is a repeat by sequence, so the listener + /// answers with an Ack; the client's attempt times out, and the fresh Connect (another + /// sequence) starts a new generation the listener admits. + /// + [Test] + public void TheListenerAdmitsAPinnedClientThatRestartsOnTheSameAddress() + { + using var serverSocket = Bind(); + using var peerSocket = Bind(); + using var server = new CultNetRudpSocketTransportServer(new CultNetRudpSocketTransportServerOptions + { + RuntimeId = "csharp-rudp-listener", + Socket = serverSocket, + ConnectionId = ConnectionId + }); + var serverEndPoint = serverSocket.LocalEndPoint!; + void ToServer(CultNetRudpPacket packet) => peerSocket.SendTo(CultNetRudpPacketCodec.Encode(packet), serverEndPoint); + + var first = Session(1); + ToServer(first.CreateConnect(0, Encoding.UTF8.GetBytes("join"))); + server.ReceiveOnce(); + var accept = Drain(peerSocket).First(p => p.PacketType == CultNetRudpPacketType.Accept); + first.Receive(accept, 0); + ToServer(first.CreateAckForReceived(accept.Sequence)); + server.ReceiveOnce(); + Drain(peerSocket); + + var restarted = Session(1); + ToServer(restarted.CreateConnect(0, Encoding.UTF8.GetBytes("join"))); + server.ReceiveOnce(); + foreach (var packet in Drain(peerSocket)) + restarted.Receive(packet, 1); + Assert.That(restarted.Connected, Is.False); + + ToServer(restarted.DueResends(3_000)[0]); + server.ReceiveOnce(); + foreach (var packet in Drain(peerSocket)) + restarted.Receive(packet, 3_001); + Assert.That(restarted.Connected, Is.True, "the restarted pinned client was never admitted"); + } + // Transports. [Test]