From cce4d391b8e9db9e264c029f2a3acc002b1209df Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 30 Sep 2026 15:03:22 +0200 Subject: [PATCH] Ack Cut D D2 (C#): only the polling thread changes the peer set A caller-directed Send that failed after a fragment left called EndUnsendablePeer on the caller's thread, removing from _peers and raising PeerDisconnected while the polling thread could be changing _peers too. Send now ends the session and sends the goodbye under the peer's SessionGate, and queues the peer; TryReceiveOnce and PollResends retire queued peers before anything else. A peer a new Connect already replaced is skipped, so a stale peer object cannot remove the peer that replaced it. Co-Authored-By: Claude Opus 5.5 --- src/GameCult.Networking/CultNetTransport.cs | 50 ++++++++++++--- .../CultNetRudpSendFailureTests.cs | 61 +++++++++++++++++++ 2 files changed, 104 insertions(+), 7 deletions(-) diff --git a/src/GameCult.Networking/CultNetTransport.cs b/src/GameCult.Networking/CultNetTransport.cs index 710227be..4ff0fbab 100644 --- a/src/GameCult.Networking/CultNetTransport.cs +++ b/src/GameCult.Networking/CultNetTransport.cs @@ -1,5 +1,6 @@ using System; using System.Buffers.Binary; +using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.IO; @@ -2682,6 +2683,11 @@ namespace GameCult.Networking /// Gets the last transport-level remote disconnect reason, if one was received. /// public byte[]? DisconnectReason { get; internal set; } + + // The goodbye's reason once the session ended over a packet it could never send. Written + // under SessionGate by whichever thread's send found the failure; the polling thread reads + // it when it retires the peer. + internal byte[]? UnsendableReason { get; set; } } /// @@ -2719,6 +2725,10 @@ namespace GameCult.Networking private readonly CultNetTransportStats _stats = new CultNetTransportStats(); private readonly Dictionary _peers = new Dictionary(StringComparer.Ordinal); private readonly Queue _deliveredFrames = new Queue(); + // Peers whose session ended over a packet it could never send, waiting for the polling thread + // to retire them. Only the polling thread changes _peers or raises PeerDisconnected; a send on + // a caller's thread ends the session and leaves the peer here. + private readonly ConcurrentQueue _unsendablePeers = new ConcurrentQueue(); private bool _disposed; /// @@ -2795,8 +2805,9 @@ namespace GameCult.Networking } if (unsendable != null) { + // The polling thread retires the peer; this thread only ends its session. if (failedIndex > 0) - EndUnsendablePeer(peer, unsendable); + EndUnsendableSession(peer, unsendable); throw unsendable; } _stats.FramesSent++; @@ -2843,6 +2854,7 @@ namespace GameCult.Networking /// public bool TryReceiveOnce(out CultNetRudpSocketServerFrame? delivered) { + RetireUnsendablePeers(); if (_deliveredFrames.Count > 0) { delivered = _deliveredFrames.Dequeue(); @@ -3046,6 +3058,7 @@ namespace GameCult.Networking /// public void PollResends() { + RetireUnsendablePeers(); if (_socket.Poll(0, SelectMode.SelectRead)) return; foreach (var peer in _peers.Values.ToArray()) @@ -3082,16 +3095,39 @@ namespace GameCult.Networking // names the error. private void EndUnsendablePeer(CultNetRudpSocketServerPeer peer, SocketException error) { - var key = RemoteKey(peer.RemoteEndPoint); - if (!_peers.TryGetValue(key, out var current) || !ReferenceEquals(current, peer)) - return; - _peers.Remove(key); + EndUnsendableSession(peer, error); + RetireUnsendablePeers(); + } + + // Ends the session and tells the peer, on whichever thread found the failure. The peer stays in + // _peers until the polling thread retires it. + private void EndUnsendableSession(CultNetRudpSocketServerPeer peer, SocketException error) + { CultNetRudpPacket goodbye; lock (peer.SessionGate) + { + if (peer.UnsendableReason != null) + return; goodbye = peer.Session.EndUnsendable(error); - peer.DisconnectReason = goodbye.Payload; + peer.UnsendableReason = goodbye.Payload; + } SendPacket(peer.RemoteEndPoint, goodbye); - PeerDisconnected?.Invoke(peer); + _unsendablePeers.Enqueue(peer); + } + + // Polling thread only. A peer a new Connect already replaced was reported then, and its key now + // names the peer that replaced it. + private void RetireUnsendablePeers() + { + while (_unsendablePeers.TryDequeue(out var peer)) + { + var key = RemoteKey(peer.RemoteEndPoint); + if (!_peers.TryGetValue(key, out var current) || !ReferenceEquals(current, peer)) + continue; + _peers.Remove(key); + peer.DisconnectReason = peer.UnsendableReason; + PeerDisconnected?.Invoke(peer); + } } /// diff --git a/tests/GameCult.Networking.Tests/CultNetRudpSendFailureTests.cs b/tests/GameCult.Networking.Tests/CultNetRudpSendFailureTests.cs index a3976375..25c07e7b 100644 --- a/tests/GameCult.Networking.Tests/CultNetRudpSendFailureTests.cs +++ b/tests/GameCult.Networking.Tests/CultNetRudpSendFailureTests.cs @@ -204,12 +204,73 @@ namespace GameCult.Networking.Tests var error = Assert.Throws(() => server.SendSchema(x.Server, new byte[3000]))!; Assert.That(CultNetRudpSession.IsPermanentSendError(error), Is.True); + // The send ends the session and tells the peer; it leaves the peer for the polling + // thread to retire, because only that thread changes the peer set. + Assert.That(x.Server.Connected, Is.False); + Assert.That(Drain(x.Socket).Last().PacketType, Is.EqualTo(CultNetRudpPacketType.Disconnect)); + Assert.That(ended, Is.Empty); + + server.ReceiveOnce(); Assert.That(server.Peers, Has.Count.EqualTo(1)); Assert.That(ended, Is.EqualTo(new[] { x.Server })); Assert.That(IsUnsendableReason(x.Server.DisconnectReason), Is.True); } } + [Test] + public void APeerEndedByASendOnAnotherThreadIsRetiredByThePollingThread() + { + var (server, _, x, _) = TwoPeers(maxFragmentBytes: 1000); + using (server) + { + var retiredOn = new List(); + server.PeerDisconnected += _ => retiredOn.Add(Environment.CurrentManagedThreadId); + server.UnsendableAfter[x.EndPoint] = 1; + + SocketException? thrown = null; + var sender = new Thread(() => + { + try { server.SendSchema(x.Server, new byte[3000]); } + catch (SocketException error) { thrown = error; } + }); + sender.Start(); + sender.Join(); + Assert.That(thrown, Is.Not.Null); + Assert.That(server.Peers, Has.Count.EqualTo(2), "the sending thread leaves the peer set alone"); + + server.PollResends(); + Assert.That(retiredOn, Is.EqualTo(new[] { Environment.CurrentManagedThreadId })); + Assert.That(server.Peers, Has.Count.EqualTo(1)); + } + } + + [Test] + public void ASendOnAPeerAlreadyReplacedLeavesThePeerThatReplacedIt() + { + var (server, listenerEndPoint, x, _) = TwoPeers(maxFragmentBytes: 1000); + using (server) + { + var stale = x.Server; + // X connects again as a new session: the listener replaces the peer it held. + var fresh = new CultNetRudpSession(new CultNetRudpSessionOptions { ConnectionId = ConnectionId }); + x.Socket.SendTo(CultNetRudpPacketCodec.Encode(fresh.CreateConnect(0)), listenerEndPoint); + server.ReceiveOnce(); + var replacing = server.Peers.Single(p => p.RemoteEndPoint.Equals(x.EndPoint)); + Assert.That(replacing, Is.Not.SameAs(stale)); + var ended = RecordDisconnects(server); + + // A caller still holding the old peer sends through it, and that send fails after a + // fragment left. + server.UnsendableAfter[x.EndPoint] = 1; + Assert.Throws(() => server.SendSchema(stale, new byte[3000])); + server.ReceiveOnce(); + + Assert.That(server.Peers, Has.Member(replacing)); + Assert.That(server.Peers, Has.Count.EqualTo(2)); + Assert.That(ended, Is.Empty); + } + } + [Test] public void APermanentFailureInResendsEndsOnlyThatPeersSession() {