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 <noreply@anthropic.com>
This commit is contained in:
Meta Vens 2026-09-30 15:03:22 +02:00
commit cce4d391b8
2 changed files with 104 additions and 7 deletions

View file

@ -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.
/// </summary>
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; }
}
/// <summary>
@ -2719,6 +2725,10 @@ namespace GameCult.Networking
private readonly CultNetTransportStats _stats = new CultNetTransportStats();
private readonly Dictionary<string, CultNetRudpSocketServerPeer> _peers = new Dictionary<string, CultNetRudpSocketServerPeer>(StringComparer.Ordinal);
private readonly Queue<CultNetRudpSocketServerFrame> _deliveredFrames = new Queue<CultNetRudpSocketServerFrame>();
// 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<CultNetRudpSocketServerPeer> _unsendablePeers = new ConcurrentQueue<CultNetRudpSocketServerPeer>();
private bool _disposed;
/// <summary>
@ -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
/// </summary>
public bool TryReceiveOnce(out CultNetRudpSocketServerFrame? delivered)
{
RetireUnsendablePeers();
if (_deliveredFrames.Count > 0)
{
delivered = _deliveredFrames.Dequeue();
@ -3046,6 +3058,7 @@ namespace GameCult.Networking
/// </summary>
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);
}
}
/// <inheritdoc />

View file

@ -204,12 +204,73 @@ namespace GameCult.Networking.Tests
var error = Assert.Throws<SocketException>(() => 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<int>();
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<SocketException>(() => 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()
{