AutoId review fixes: login pack sweep, refused sends kept, flight tag after send

- The login pack was never appraised: at login the PWD snapshot is cold, so ownership
  reads miss, the item classified Unknown and was skipped at 2 s. Unknown now waits
  (WaitSnapshot) until the snapshot has entries or 120 s pass, and a one-shot sweep runs
  at LoginCompleteAtMs + 30 s (and again after a hot reload's MarkAlreadyComplete, which
  restamps login): the player's owned items plus each owned side pack, uncached ones
  added as inventory work. The 5/s inventory cap still applies.
- The drain moved into AutoIdDrain.cs, a pure unit behind IAutoIdWorld, so it runs
  against a fake world in EngineRobustnessTests (cold snapshot for N seconds, then every
  pack item is sent, none before login + 30 s, at most 5 per second).
- A refused EnqueueRequestId keeps the entry, is not counted as sent, ends the tick's
  sending and does not take the inventory rate slot. The priority target is re-armed on
  refusal.
- The flight tag is registered only after _requestId returns true; the pending table is
  256 (MaxRequestIdQueue); IdentifyTagging covers 200 registrations and 200 matches.
- The 4096 pending cap applies only in Limited mode; _incoming is bounded at 16384 while
  DrainTick returns early, dropping the oldest and counting them.
- 0x0022 InventoryPutObjInContainer is read in SmartBoxHooks.ParseGameEvent so it works
  with ServerMessageStream off; ServerMessageStream is back to its base text.
- check_offthread_mutators.py: the stale DrainPending allow-list entry is replaced by
  LiveWorld's Enqueue.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Daniel Wallace 2026-10-12 16:29:54 -07:00
commit c9bbafbfb4
14 changed files with 670 additions and 218 deletions

View file

@ -0,0 +1,232 @@
using RynthCore.Engine.Compatibility;
using RynthCore.Engine.Net;
namespace EngineRobustnessTests;
/// <summary>
/// AutoIdDrain against a fake world and a fake clock: the pack
/// created before the object snapshot is warm still gets appraised, a refused enqueue
/// is kept, and the bounds.
/// </summary>
internal static partial class Program
{
private sealed class FakeWorld : IAutoIdWorld
{
public bool Warm;
public readonly Dictionary<uint, (uint Container, uint Wielder)> Snapshot = new();
public readonly HashSet<uint> Cached = new();
public readonly HashSet<uint> Released = new();
public bool Refuse;
public readonly List<(uint Id, IdRequester Who, long At)> Sent = new();
public long Now;
public bool TryGetOwnership(uint id, out uint container, out uint wielder)
{
container = wielder = 0;
if (!Warm || !Snapshot.TryGetValue(id, out var e)) return false;
container = e.Container; wielder = e.Wielder;
return true;
}
public bool SnapshotWarm => Warm;
public int CollectOwned(uint container, Span<uint> dest)
{
if (!Warm) return 0;
int n = 0;
foreach (var kv in Snapshot)
{
if (n >= dest.Length) break;
if (kv.Key != container && (kv.Value.Container == container || kv.Value.Wielder == container)) dest[n++] = kv.Key;
}
return n;
}
public bool IsLive(uint id) => !Released.Contains(id);
public bool HasAppraisal(uint id) => Cached.Contains(id);
public bool IsFresh(uint id) => Cached.Contains(id);
public bool Enqueue(uint id, IdRequester who)
{
if (Refuse) return false;
Sent.Add((id, who, Now));
Cached.Add(id); // the reply lands
return true;
}
}
private const uint Me = 0x50000001, SidePack = 0x80000900;
private static AutoIdDrain.Context Ctx(FakeWorld w, long loginAt, AutoIdMode mode = AutoIdMode.Limited, long settle = 0) => new()
{
Now = w.Now, Mode = mode, PlayerId = Me, OpenContainer = 0, OpenedAtMs = 0, SettleUntilMs = settle, LoginCompleteAtMs = loginAt,
};
/// <summary>Runs the 100 ms drain from w.Now to <paramref name="until"/>.</summary>
private static void RunUntil(AutoIdDrain d, FakeWorld w, long until, long loginAt, AutoIdMode mode = AutoIdMode.Limited, Action? each = null)
{
for (; w.Now <= until; w.Now += 100)
{
each?.Invoke();
d.Tick(Ctx(w, loginAt, mode), 0);
}
}
private static void RunAutoIdDrainTests()
{
DrainLoginPackWithColdSnapshot();
DrainLoginSweep();
DrainUnknownWaitsForSnapshotThenGivesUp();
DrainRefusedEnqueueIsKept();
DrainBounds();
}
// The pack is created at login, before the snapshot is warm; it must still go out.
private static void DrainLoginPackWithColdSnapshot()
{
_case = "drain login pack, cold snapshot";
var w = new FakeWorld { Now = 10_000 };
var d = new AutoIdDrain(w);
// The login create burst: 20 pack items and a side pack with 5 more, created at 10 s.
var pack = new List<uint>();
for (uint i = 1; i <= 20; i++) { pack.Add(0x80001000 + i); w.Snapshot[0x80001000 + i] = (Me, 0); }
w.Snapshot[SidePack] = (Me, 0);
pack.Add(SidePack);
for (uint i = 1; i <= 5; i++) { pack.Add(0x80002000 + i); w.Snapshot[0x80002000 + i] = (SidePack, 0); }
foreach (uint id in pack) d.Offer(id, w.Now);
const long LoginAt = 12_000;
const long WarmAt = 40_000; // the snapshot starts 28 s after login-complete (cold for N seconds)
// Before login completes, and while the snapshot is cold: nothing is sent, nothing dropped.
RunUntil(d, w, LoginAt - 100, loginAt: 0);
Check(w.Sent.Count == 0, $"nothing before login-complete, sent {w.Sent.Count}");
RunUntil(d, w, WarmAt - 100, LoginAt);
Check(w.Sent.Count == 0, $"nothing while the snapshot is cold, sent {w.Sent.Count}");
Check(d.PendingCount == pack.Count, $"all {pack.Count} kept while the snapshot is cold, pending {d.PendingCount}");
w.Warm = true;
RunUntil(d, w, 120_000, LoginAt);
var sentIds = w.Sent.Select(s => s.Id).ToHashSet();
Check(pack.All(sentIds.Contains), $"every pack item eventually sent ({sentIds.Count}/{pack.Count})");
Check(w.Sent.All(s => s.Who == IdRequester.AutoIdInventory), "all as autoid-inventory");
Check(w.Sent.Min(s => s.At) >= LoginAt + AutoIdPolicy.DeferMs, "none before login + DeferMs");
int worst = w.Sent.Max(s => w.Sent.Count(t => t.At >= s.At && t.At < s.At + 1_000));
Check(worst <= 5, $"at most 5 a second, got {worst}");
}
// The one-shot sweep at login + DeferMs, also after a hot reload (a new login stamp).
private static void DrainLoginSweep()
{
_case = "drain login sweep";
var w = new FakeWorld { Now = 100_000, Warm = true };
var d = new AutoIdDrain(w);
for (uint i = 1; i <= 8; i++) w.Snapshot[0x80003000 + i] = (Me, 0); // main pack, never offered
w.Snapshot[SidePack] = (Me, 0);
for (uint i = 1; i <= 4; i++) w.Snapshot[0x80004000 + i] = (SidePack, 0); // side pack contents
w.Snapshot[0x80005000] = (0, Me); // worn
w.Cached.Add(0x80003001); // already appraised
w.Snapshot[0x80006000] = (0, 0); // a ground item: not ours
long loginAt = 100_000;
RunUntil(d, w, loginAt + AutoIdPolicy.DeferMs - 100, loginAt);
Check(w.Sent.Count == 0, $"no sweep before login + DeferMs, sent {w.Sent.Count}");
RunUntil(d, w, loginAt + AutoIdPolicy.DeferMs + 10_000, loginAt);
var ids = w.Sent.Select(s => s.Id).ToHashSet();
Check(Enumerable.Range(2, 7).All(i => ids.Contains(0x80003000 + (uint)i)), "the uncached main-pack items are swept");
Check(!ids.Contains(0x80003001), "a cached one is not");
Check(Enumerable.Range(1, 4).All(i => ids.Contains(0x80004000 + (uint)i)), "the side pack's contents are swept");
Check(ids.Contains(SidePack) && ids.Contains(0x80005000), "the side pack itself and worn gear are swept");
Check(!ids.Contains(0x80006000), "a ground item is not");
Check(d.Swept == 13, $"13 swept (7 main pack, the side pack, its 4, 1 worn), got {d.Swept}");
int count = w.Sent.Count;
// The same login: no second sweep, even with new uncached items.
w.Snapshot[0x80007000] = (Me, 0);
RunUntil(d, w, w.Now + 5_000, loginAt);
Check(w.Sent.Count == count, "one sweep per login");
// A hot reload (MarkAlreadyComplete) stamps a new login: swept again after its defer.
long reloadAt = w.Now;
RunUntil(d, w, reloadAt + AutoIdPolicy.DeferMs + 2_000, reloadAt);
Check(w.Sent.Any(s => s.Id == 0x80007000), "a new login stamp sweeps again");
// All mode never sweeps (it appraises every create anyway).
var w2 = new FakeWorld { Now = 100_000, Warm = true };
w2.Snapshot[0x80008000] = (Me, 0);
var d2 = new AutoIdDrain(w2);
RunUntil(d2, w2, 100_000 + AutoIdPolicy.DeferMs + 5_000, 100_000, AutoIdMode.All);
Check(w2.Sent.Count == 0, "All mode: no sweep");
}
private static void DrainUnknownWaitsForSnapshotThenGivesUp()
{
_case = "drain unknown";
// Warm snapshot, object not in it: dropped at MinAgeMs (a creature gone, or never placed).
var w = new FakeWorld { Now = 1_000_000, Warm = true };
var d = new AutoIdDrain(w);
d.Offer(0x80009001, w.Now);
RunUntil(d, w, w.Now + AutoIdPolicy.MinAgeMs + 200, loginAt: 1);
Check(d.PendingCount == 0 && d.SkipMode == 1, $"warm snapshot: dropped after MinAgeMs (pending {d.PendingCount}, skipMode {d.SkipMode})");
// Cold snapshot that never warms: kept until UnknownMaxWaitMs, then dropped.
var c = new FakeWorld { Now = 1_000_000 };
var e = new AutoIdDrain(c);
e.Offer(0x80009002, c.Now);
long t0 = c.Now;
RunUntil(e, c, t0 + AutoIdPolicy.UnknownMaxWaitMs - 200, loginAt: 1);
Check(e.PendingCount == 1, "cold snapshot: still kept just before UnknownMaxWaitMs");
RunUntil(e, c, t0 + AutoIdPolicy.UnknownMaxWaitMs + 200, loginAt: 1);
Check(e.PendingCount == 0 && e.SkipMode == 1, "cold snapshot: dropped at UnknownMaxWaitMs");
}
// A refused enqueue (transition, full ring) is kept, not counted, and sent later.
private static void DrainRefusedEnqueueIsKept()
{
_case = "drain refused enqueue";
var w = new FakeWorld { Now = 1_000_000, Warm = true, Refuse = true };
var d = new AutoIdDrain(w);
for (uint i = 1; i <= 3; i++) { w.Snapshot[0x8000A000 + i] = (0, 0); d.Offer(0x8000A000 + i, w.Now); }
int sent = d.Tick(Ctx(w, 1, AutoIdMode.All), 0);
Check(sent == 0, $"a refused send is not counted as sent, got {sent}");
Check(d.PendingCount == 3, $"all three kept, pending {d.PendingCount}");
Check(d.Refused == 1, $"the first refusal ends the tick's sending (1 refused), got {d.Refused}");
w.Now += 100;
w.Refuse = false;
sent = d.Tick(Ctx(w, 1, AutoIdMode.All), 0);
Check(sent == 3 && w.Sent.Count == 3 && d.PendingCount == 0, $"sent once accepted (sent {sent}, pending {d.PendingCount})");
// The inventory cap counts only a send that was taken.
var v = new FakeWorld { Now = 1_000_000, Warm = true, Refuse = true };
var e = new AutoIdDrain(v);
v.Snapshot[0x8000B001] = (Me, 0); v.Snapshot[0x8000B002] = (Me, 0);
e.Offer(0x8000B001, 0); e.Offer(0x8000B002, 0);
e.Tick(Ctx(v, 1), 0);
v.Refuse = false; v.Now += 100;
e.Tick(Ctx(v, 1), 0);
Check(v.Sent.Count == 1, $"a refused inventory send did not use up the rate slot (sent {v.Sent.Count})");
}
// All mode keeps the old unbounded backlog; Limited is capped; _incoming is bounded.
private static void DrainBounds()
{
_case = "drain bounds";
var w = new FakeWorld { Now = 1_000, Warm = true };
var d = new AutoIdDrain(w);
int n = AutoIdDrain.MaxPendingLimited + 500;
for (uint i = 0; i < n; i++) { w.Snapshot[0x81000000 + i] = (0, 0); d.Offer(0x81000000 + i, w.Now); }
d.Tick(Ctx(w, 0, AutoIdMode.All), AutoIdDrain.MaxPerTick); // no sends: just take them in
Check(d.PendingCount == n && d.Overflow == 0, $"All: all {n} pending (got {d.PendingCount}, overflow {d.Overflow})");
var l = new FakeWorld { Now = 1_000, Warm = true };
var e = new AutoIdDrain(l);
for (uint i = 0; i < n; i++) e.Offer(0x82000000 + i, l.Now);
e.Tick(Ctx(l, 0, AutoIdMode.Limited), AutoIdDrain.MaxPerTick);
Check(e.PendingCount == AutoIdDrain.MaxPendingLimited && e.Overflow == 500,
$"Limited: capped at {AutoIdDrain.MaxPendingLimited}, 500 counted (got {e.PendingCount}, {e.Overflow})");
// While the drain is held (a long death), _incoming keeps the newest MaxIncoming.
var h = new FakeWorld { Now = 1_000, Warm = true };
var f = new AutoIdDrain(h);
int over = 37;
for (uint i = 0; i < AutoIdDrain.MaxIncoming + over; i++) f.Offer(0x83000000 + i, h.Now);
Check(f.IncomingDropped == over, $"{over} oldest dropped and counted, got {f.IncomingDropped}");
f.Tick(Ctx(h, 0, AutoIdMode.All), AutoIdDrain.MaxPerTick);
Check(f.PendingCount == AutoIdDrain.MaxIncoming, $"the newest {AutoIdDrain.MaxIncoming} kept, got {f.PendingCount}");
}
}

View file

@ -27,10 +27,10 @@ internal static partial class Program
// ---- the decision table ---------------------------------------------------------
private static readonly long[] Ages = { 0, AutoIdPolicy.MinAgeMs - 1, AutoIdPolicy.MinAgeMs, 60_000 };
private static readonly long[] Ages = { 0, AutoIdPolicy.MinAgeMs - 1, AutoIdPolicy.MinAgeMs, 60_000, AutoIdPolicy.UnknownMaxWaitMs - 1, AutoIdPolicy.UnknownMaxWaitMs };
/// <summary>The rule as the spec states it, written out independently of AutoIdPolicy.Decide.</summary>
private static V Expected(AutoIdMode mode, C cls, long age, bool defer, bool openedAfter, bool fresh, bool cached, bool rateOk)
private static V Expected(AutoIdMode mode, C cls, long age, bool defer, bool openedAfter, bool fresh, bool cached, bool rateOk, bool warm)
{
if (mode == AutoIdMode.Off) return V.SkipMode;
if (mode == AutoIdMode.All) return cls == C.Target && fresh ? V.SkipFresh : V.Send;
@ -40,7 +40,7 @@ internal static partial class Program
C.Target => fresh ? V.SkipFresh : V.Send,
C.Container => fresh ? V.SkipFresh : young ? V.WaitAge : defer && !openedAfter ? V.WaitDefer : V.Send,
C.Inventory => cached ? V.SkipFresh : young ? V.WaitAge : defer ? V.WaitDefer : !rateOk ? V.WaitRate : V.Send,
C.Unknown => young ? V.WaitAge : V.SkipMode,
C.Unknown => young ? V.WaitAge : !warm && age < AutoIdPolicy.UnknownMaxWaitMs ? V.WaitSnapshot : V.SkipMode,
_ => V.SkipMode,
};
}
@ -57,16 +57,17 @@ internal static partial class Program
foreach (bool cached in new[] { false, true })
foreach (bool fresh in new[] { false, true })
foreach (bool rateOk in new[] { false, true })
foreach (bool warm in new[] { false, true })
{
if (fresh && !cached) continue; // fresh implies cached
rows++;
V got = AutoIdPolicy.Decide(mode, cls, age, defer, opened, fresh, cached, rateOk);
V want = Expected(mode, cls, age, defer, opened, fresh, cached, rateOk);
V got = AutoIdPolicy.Decide(mode, cls, age, defer, opened, fresh, cached, rateOk, warm);
V want = Expected(mode, cls, age, defer, opened, fresh, cached, rateOk, warm);
if (got != want && wrong++ < 10)
Check(false, $"{mode} {cls} age={age} defer={defer} opened={opened} cached={cached} fresh={fresh} rateOk={rateOk}: want {want}, got {got}");
Check(false, $"{mode} {cls} age={age} defer={defer} opened={opened} cached={cached} fresh={fresh} rateOk={rateOk} warm={warm}: want {want}, got {got}");
}
Check(wrong == 0, $"{wrong} of {rows} rows wrong");
Check(rows == 3 * 5 * 4 * 2 * 2 * 3 * 2, $"row count {rows}");
Check(rows == 3 * 5 * 6 * 2 * 2 * 3 * 2 * 2, $"row count {rows}");
}
/// <summary>The same rules as named cases, so a mutation is easy to read off a failure.</summary>

View file

@ -17,6 +17,8 @@
CastSlot.cs the cast slot refuses during a world transition
CrashExitRule.cs which exit codes are crash exits (not ExitProcess(-1))
AutoIdPolicy.cs AutoIdMode All/Limited/Off: class, minimum age, post-transition defer
AutoIdDrain.cs the AutoId backlog against a fake world: login sweep, cold snapshot,
refused sends kept, bounds
IdRequester.cs the engine-send marker that tags every engine 0xC8
Run: dotnet run -c Release (exit 0 = pass, 1 = fail)
-->
@ -43,6 +45,7 @@
<Compile Include="..\..\src\RynthCore.Engine\Compatibility\CastSlot.cs" Link="Engine\CastSlot.cs" />
<Compile Include="..\..\src\RynthCore.Engine\Compatibility\CrashExitRule.cs" Link="Engine\CrashExitRule.cs" />
<Compile Include="..\..\src\RynthCore.Engine\Compatibility\AutoIdPolicy.cs" Link="Engine\AutoIdPolicy.cs" />
<Compile Include="..\..\src\RynthCore.Engine\Compatibility\AutoIdDrain.cs" Link="Engine\AutoIdDrain.cs" />
<Compile Include="..\..\src\RynthCore.Engine\Net\IdRequester.cs" Link="Engine\IdRequester.cs" />
</ItemGroup>

View file

@ -43,6 +43,7 @@ internal static partial class Program
RunRingAndGateTests();
RunAutoIdLimitTests();
RunAutoIdDrainTests();
Console.WriteLine($"{_checks} check(s), {_failed} failed.");
return _failed == 0 ? 0 : 1;

View file

@ -420,15 +420,21 @@ internal static unsafe class Program
Out(c, Identify(Corpse));
Has(Last(c), "[cli]", "a send without a requester is not registered");
// 64 sends in a burst do not push out other engine calls (their own table).
// 200 sends in a burst (a full RequestId queue drained at once) do not push out other
// engine calls (their own table), and every one of them is matched.
c.EngineCall("UseObject", Corpse, 0);
for (uint i = 0; i < 64; i++) c.EngineSend((byte)IdRequester.AutoIdWorld, 0x80100000 + i);
for (uint i = 0; i < 200; i++) c.EngineSend((byte)IdRequester.AutoIdWorld, 0x80100000 + i);
Out(c, Use(Corpse));
Has(Last(c), "[eng] Use", "an identify burst leaves the pending use intact");
Out(c, Identify(0x80100000 + 63));
Has(Last(c), "[eng:autoid-world]", "the newest send of the burst still matches");
Out(c, Identify(0x80100000));
Has(Last(c), "[eng:autoid-world]", "and so does the oldest: 64 sends inside the match window all keep their slot");
long foreignBefore = c.IdentifyForeignTotal;
int matched = 0;
for (uint i = 0; i < 200; i++)
{
Out(c, Identify(0x80100000 + i));
if (Last(c).Contains("[eng:autoid-world] IdentifyObject", StringComparison.Ordinal)) matched++;
}
Eq(matched, 200, "200 registrations, 200 tagged identifies (oldest to newest)");
Eq(c.IdentifyForeignTotal, foreignBefore, "none of the burst counted as foreign");
foreach (IdRequester who in Enum.GetValues<IdRequester>())
{

View file

@ -98,7 +98,7 @@ ENQUEUE = "AcMainThreadQueue.Enqueue"
# (file, method) pairs, each verified to do no off-thread AC mutation.
ENQUEUE_PRODUCER_ALLOW = {
("AutoIdService.cs", "DrainTick"), # appraisal: enqueues 0xC8, sent on main thread in DrainRequestIds
("AutoIdService.cs", "DrainPending"), # DrainTick's backlog half: only EnqueueRequestId; reads the PWD snapshot
("AutoIdService.cs", "Enqueue"), # LiveWorld.Enqueue, called from AutoIdDrain on the drain timer: only EnqueueRequestId
("RynthCoreChatCommands.cs", "Reply"), # /rc and /rv plates replies: only EnqueueWriteToChat
("AcMouseOver.cs", "Say"), # /rc acmouse watch lines: only EnqueueWriteToChat (and the log)
}