Snapshot for release 2026.10.13.1 (internal 90a2f4a)
This commit is contained in:
parent
b0f9d74b21
commit
1d86acdf27
218 changed files with 24019 additions and 1517 deletions
298
tools/EngineRobustnessTests/AutoIdDrainTests.cs
Normal file
298
tools/EngineRobustnessTests/AutoIdDrainTests.cs
Normal file
|
|
@ -0,0 +1,298 @@
|
|||
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 HashSet<uint> Containers = new();
|
||||
public readonly List<uint> Looked = new(); // every CollectOwned call
|
||||
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)
|
||||
{
|
||||
Looked.Add(container);
|
||||
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 IsContainer(uint id) => Containers.Contains(id);
|
||||
public bool QueueIdentify(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, bool combat = false) => new()
|
||||
{
|
||||
Now = w.Now, Mode = mode, PlayerId = Me, OpenContainer = 0, OpenedAtMs = 0, SettleUntilMs = settle, LoginCompleteAtMs = loginAt,
|
||||
CombatBusy = combat,
|
||||
};
|
||||
|
||||
/// <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();
|
||||
DrainCombatHoldsInventory();
|
||||
DrainSweepRetriesAfterOverflow();
|
||||
}
|
||||
|
||||
// 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); w.Containers.Add(SidePack);
|
||||
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); w.Containers.Add(SidePack);
|
||||
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");
|
||||
// Only containers are looked into: the player, then the side pack; never a sword.
|
||||
Check(w.Looked.All(x => x == Me || x == SidePack) && w.Looked.Contains(SidePack),
|
||||
$"only containers looked into ({string.Join(",", w.Looked.Distinct().Select(x => x.ToString("X8")))})");
|
||||
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}");
|
||||
}
|
||||
|
||||
// The pack waits through combat (a cast or attack in flight); kept, not
|
||||
// dropped; an open container is not held.
|
||||
private static void DrainCombatHoldsInventory()
|
||||
{
|
||||
_case = "drain combat";
|
||||
const uint Chest = 0x80000A00, Loot = 0x80000A01;
|
||||
var w = new FakeWorld { Now = 1_000_000, Warm = true };
|
||||
var d = new AutoIdDrain(w);
|
||||
for (uint i = 1; i <= 3; i++) { w.Snapshot[0x8000C000 + i] = (Me, 0); d.Offer(0x8000C000 + i, w.Now - 10_000); }
|
||||
w.Snapshot[Loot] = (Chest, 0); d.Offer(Loot, w.Now - 10_000);
|
||||
AutoIdDrain.Context Fight(bool combat) => new()
|
||||
{
|
||||
Now = w.Now, Mode = AutoIdMode.Limited, PlayerId = Me, OpenContainer = Chest, OpenedAtMs = w.Now - 5_000,
|
||||
SettleUntilMs = 0, LoginCompleteAtMs = 1, CombatBusy = combat,
|
||||
};
|
||||
for (int k = 0; k < 50; k++) { d.Tick(Fight(true), 0); w.Now += 100; }
|
||||
Check(w.Sent.Count == 1 && w.Sent[0].Id == Loot, $"in combat: only the open container's item is sent ({w.Sent.Count})");
|
||||
Check(d.PendingCount == 3, $"the pack is kept, pending {d.PendingCount}");
|
||||
Check(d.SkipCombat == 3, $"each counted once, got {d.SkipCombat}");
|
||||
for (int k = 0; k < 20; k++) { d.Tick(Fight(false), 0); w.Now += 100; }
|
||||
Check(w.Sent.Count == 4 && d.PendingCount == 0, $"out of combat: the pack goes out (sent {w.Sent.Count}, pending {d.PendingCount})");
|
||||
Check(w.Sent.Skip(1).All(s => s.Who == IdRequester.AutoIdInventory), "as autoid-inventory");
|
||||
}
|
||||
|
||||
// A sweep that overflowed the pending list is not marked done; it runs again once
|
||||
// there is room, and every pack item is still sent.
|
||||
private static void DrainSweepRetriesAfterOverflow()
|
||||
{
|
||||
_case = "drain sweep overflow";
|
||||
long loginAt = 100_000, sweepAt = loginAt + AutoIdPolicy.DeferMs;
|
||||
var pack = new List<uint>();
|
||||
for (uint i = 1; i <= 5; i++) pack.Add(0x8000D000 + i);
|
||||
|
||||
// Full: the sweep does not walk (no overflow counted) and is not done.
|
||||
var w = new FakeWorld { Now = sweepAt, Warm = true };
|
||||
foreach (uint id in pack) w.Snapshot[id] = (Me, 0);
|
||||
var d = new AutoIdDrain(w);
|
||||
for (uint i = 0; i < AutoIdDrain.MaxPendingLimited; i++) d.Offer(0x84000000 + i, w.Now); // young, unplaced: they wait
|
||||
d.Tick(Ctx(w, loginAt), AutoIdDrain.MaxPerTick);
|
||||
Check(d.PendingCount == AutoIdDrain.MaxPendingLimited && d.Swept == 0 && d.Overflow == 0,
|
||||
$"pending full: no sweep yet (pending {d.PendingCount}, swept {d.Swept}, overflow {d.Overflow})");
|
||||
RunUntil(d, w, sweepAt + 20_000, loginAt);
|
||||
Check(pack.All(id => w.Sent.Any(s => s.Id == id)), $"swept once there was room: all 5 sent ({w.Sent.Count})");
|
||||
|
||||
// Partly full: 2 fit, 3 overflow; the sweep runs again and the other 3 go out too.
|
||||
var v = new FakeWorld { Now = sweepAt, Warm = true };
|
||||
foreach (uint id in pack) v.Snapshot[id] = (Me, 0);
|
||||
var e = new AutoIdDrain(v);
|
||||
for (uint i = 0; i < AutoIdDrain.MaxPendingLimited - 2; i++) e.Offer(0x85000000 + i, v.Now);
|
||||
e.Tick(Ctx(v, loginAt), AutoIdDrain.MaxPerTick);
|
||||
Check(e.Swept == 2 && e.Overflow == 3, $"2 fit, 3 overflowed (swept {e.Swept}, overflow {e.Overflow})");
|
||||
RunUntil(e, v, sweepAt + 20_000, loginAt);
|
||||
Check(pack.All(id => v.Sent.Any(s => s.Id == id)), $"the overflowed 3 are swept again and sent ({v.Sent.Count})");
|
||||
Check(e.Swept == 5, $"5 swept in all, got {e.Swept}");
|
||||
}
|
||||
}
|
||||
347
tools/EngineRobustnessTests/AutoIdLimitTests.cs
Normal file
347
tools/EngineRobustnessTests/AutoIdLimitTests.cs
Normal file
|
|
@ -0,0 +1,347 @@
|
|||
using RynthCore.Engine.Compatibility;
|
||||
using RynthCore.Engine.Net;
|
||||
using V = RynthCore.Engine.Compatibility.AutoIdPolicy.Verdict;
|
||||
using C = RynthCore.Engine.Compatibility.AutoIdPolicy.Class;
|
||||
|
||||
namespace EngineRobustnessTests;
|
||||
|
||||
/// <summary>
|
||||
/// AutoId limiting: the mode decision table, the post-transition defer, where an
|
||||
/// object is, and the engine-send marker that tags every engine 0xC8.
|
||||
/// </summary>
|
||||
internal static partial class Program
|
||||
{
|
||||
private static void RunAutoIdLimitTests()
|
||||
{
|
||||
AutoIdDecisionTable();
|
||||
AutoIdDecisionSpotCases();
|
||||
AutoIdDeferWindow();
|
||||
AutoIdLoginDefer();
|
||||
AutoIdInventoryRate();
|
||||
AutoIdClassify();
|
||||
AutoIdModeParse();
|
||||
IdMarkerScopes();
|
||||
IdMarkerRidesTheQueue();
|
||||
IdHeartbeatNames();
|
||||
}
|
||||
|
||||
// ---- the decision table ---------------------------------------------------------
|
||||
|
||||
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, bool warm, bool combat)
|
||||
{
|
||||
if (mode == AutoIdMode.Off) return V.SkipMode;
|
||||
if (mode == AutoIdMode.All) return cls == C.Target && fresh ? V.SkipFresh : V.Send;
|
||||
bool young = age < AutoIdPolicy.MinAgeMs;
|
||||
return cls switch
|
||||
{
|
||||
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 : combat ? V.WaitCombat : !rateOk ? V.WaitRate : V.Send,
|
||||
C.Unknown => young ? V.WaitAge : !warm && age < AutoIdPolicy.UnknownMaxWaitMs ? V.WaitSnapshot : V.SkipMode,
|
||||
_ => V.SkipMode,
|
||||
};
|
||||
}
|
||||
|
||||
private static void AutoIdDecisionTable()
|
||||
{
|
||||
_case = "autoid decision table";
|
||||
int rows = 0, wrong = 0;
|
||||
foreach (AutoIdMode mode in Enum.GetValues<AutoIdMode>())
|
||||
foreach (C cls in Enum.GetValues<C>())
|
||||
foreach (long age in Ages)
|
||||
foreach (bool defer in new[] { false, true })
|
||||
foreach (bool opened in new[] { false, true })
|
||||
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 })
|
||||
foreach (bool combat in new[] { false, true })
|
||||
{
|
||||
if (fresh && !cached) continue; // fresh implies cached
|
||||
rows++;
|
||||
V got = AutoIdPolicy.Decide(mode, cls, age, defer, opened, fresh, cached, rateOk, warm, combat);
|
||||
V want = Expected(mode, cls, age, defer, opened, fresh, cached, rateOk, warm, combat);
|
||||
if (got != want && wrong++ < 10)
|
||||
Check(false, $"{mode} {cls} age={age} defer={defer} opened={opened} cached={cached} fresh={fresh} rateOk={rateOk} warm={warm} combat={combat}: want {want}, got {got}");
|
||||
}
|
||||
Check(wrong == 0, $"{wrong} of {rows} rows wrong");
|
||||
Check(rows == 3 * 5 * 6 * 2 * 2 * 3 * 2 * 2 * 2, $"row count {rows}");
|
||||
}
|
||||
|
||||
/// <summary>The same rules as named cases, so a mutation is easy to read off a failure.</summary>
|
||||
private static void AutoIdDecisionSpotCases()
|
||||
{
|
||||
_case = "autoid spot cases";
|
||||
const long Old = 10_000;
|
||||
// Off: nothing at all, the selected target included.
|
||||
Check(AutoIdPolicy.Decide(AutoIdMode.Off, C.Target, 0, false, false, false, false) == V.SkipMode, "off skips the target");
|
||||
Check(AutoIdPolicy.Decide(AutoIdMode.Off, C.Container, Old, false, true, false, false) == V.SkipMode, "off skips an open container");
|
||||
// All: the old behaviour.
|
||||
Check(AutoIdPolicy.Decide(AutoIdMode.All, C.World, 0, true, false, false, false) == V.Send, "all sends a fresh-born world object, deferred or not");
|
||||
Check(AutoIdPolicy.Decide(AutoIdMode.All, C.Target, 0, false, false, true, true) == V.SkipFresh, "all keeps the target fresh skip");
|
||||
Check(AutoIdPolicy.Decide(AutoIdMode.All, C.Inventory, 0, false, false, false, true) == V.Send, "all sends a cached pack item (old behaviour)");
|
||||
// Limited: target.
|
||||
Check(AutoIdPolicy.Decide(AutoIdMode.Limited, C.Target, 0, true, false, false, false) == V.Send, "target exempt from age and defer");
|
||||
Check(AutoIdPolicy.Decide(AutoIdMode.Limited, C.Target, 0, false, false, true, true) == V.SkipFresh, "target fresh skip");
|
||||
Check(AutoIdPolicy.Decide(AutoIdMode.Limited, C.Target, 0, false, false, false, true) == V.Send, "target cached but stale is sent");
|
||||
// Limited: world never.
|
||||
Check(AutoIdPolicy.Decide(AutoIdMode.Limited, C.World, Old, false, false, false, false) == V.SkipMode, "creature / ground item skipped");
|
||||
// Limited: container.
|
||||
Check(AutoIdPolicy.Decide(AutoIdMode.Limited, C.Container, AutoIdPolicy.MinAgeMs - 1, false, true, false, false) == V.WaitAge, "container item waits for the minimum age");
|
||||
Check(AutoIdPolicy.Decide(AutoIdMode.Limited, C.Container, AutoIdPolicy.MinAgeMs, false, false, false, false) == V.Send, "container item at the minimum age is sent");
|
||||
Check(AutoIdPolicy.Decide(AutoIdMode.Limited, C.Container, Old, true, false, false, false) == V.WaitDefer, "container opened before the settle ended waits out the defer");
|
||||
Check(AutoIdPolicy.Decide(AutoIdMode.Limited, C.Container, Old, true, true, false, false) == V.Send, "container opened after the settle is not deferred");
|
||||
Check(AutoIdPolicy.Decide(AutoIdMode.Limited, C.Container, Old, false, false, true, true) == V.SkipFresh, "fresh container item skipped");
|
||||
Check(AutoIdPolicy.Decide(AutoIdMode.Limited, C.Container, Old, false, false, false, true) == V.Send, "stale cached container item re-appraised");
|
||||
// Limited: inventory.
|
||||
Check(AutoIdPolicy.Decide(AutoIdMode.Limited, C.Inventory, Old, false, false, false, true) == V.SkipFresh, "pack item with any cached appraisal skipped");
|
||||
Check(AutoIdPolicy.Decide(AutoIdMode.Limited, C.Inventory, AutoIdPolicy.MinAgeMs - 1, false, false, false, false) == V.WaitAge, "pack item waits for the minimum age");
|
||||
Check(AutoIdPolicy.Decide(AutoIdMode.Limited, C.Inventory, Old, true, true, false, false) == V.WaitDefer, "pack item deferred (the opened-container exemption does not apply)");
|
||||
Check(AutoIdPolicy.Decide(AutoIdMode.Limited, C.Inventory, Old, false, false, false, false) == V.Send, "uncached pack item sent");
|
||||
Check(AutoIdPolicy.Decide(AutoIdMode.Limited, C.Inventory, Old, false, false, false, false, inventoryRateOk: false) == V.WaitRate, "pack item over the rate waits");
|
||||
Check(AutoIdPolicy.Decide(AutoIdMode.Limited, C.Container, Old, false, true, false, false, inventoryRateOk: false) == V.Send, "the rate cap is the inventory's only (container)");
|
||||
Check(AutoIdPolicy.Decide(AutoIdMode.Limited, C.Target, 0, true, false, false, false, inventoryRateOk: false) == V.Send, "the rate cap never holds the selected target");
|
||||
Check(AutoIdPolicy.Decide(AutoIdMode.All, C.Inventory, 0, false, false, false, false, inventoryRateOk: false) == V.Send, "All mode keeps the old behaviour (no cap)");
|
||||
// Combat: only the pack waits; the target and an open container do not.
|
||||
Check(AutoIdPolicy.Decide(AutoIdMode.Limited, C.Inventory, Old, false, false, false, false, combatBusy: true) == V.WaitCombat, "pack item waits while in combat");
|
||||
Check(AutoIdPolicy.Decide(AutoIdMode.Limited, C.Target, 0, false, false, false, false, combatBusy: true) == V.Send, "combat never holds the selected target");
|
||||
Check(AutoIdPolicy.Decide(AutoIdMode.Limited, C.Container, Old, false, true, false, false, combatBusy: true) == V.Send, "combat never holds an open container");
|
||||
Check(AutoIdPolicy.Decide(AutoIdMode.All, C.Inventory, Old, false, false, false, false, combatBusy: true) == V.Send, "All mode: no combat hold (old behaviour)");
|
||||
// What counts as combat: a cast or an attack, never a selection alone (a hunting bot
|
||||
// nearly always has one, and the pack would never be appraised).
|
||||
Check(!AutoIdPolicy.InCombat(0x80001234, 0, false), "target selected, no cast, no attack: not combat");
|
||||
bool selectedOnly = AutoIdPolicy.InCombat(0x80001234, 0, false);
|
||||
Check(AutoIdPolicy.Decide(AutoIdMode.Limited, C.Inventory, Old, false, false, false, false, combatBusy: selectedOnly) == V.Send, "target selected, no cast, no attack: the pack sends");
|
||||
Check(AutoIdPolicy.InCombat(0, 1, false), "a cast in flight is combat");
|
||||
Check(AutoIdPolicy.InCombat(0, 0, true), "an attack running is combat");
|
||||
Check(!AutoIdPolicy.InCombat(0, 0, false), "nothing at all: not combat");
|
||||
// Limited: unknown place.
|
||||
Check(AutoIdPolicy.Decide(AutoIdMode.Limited, C.Unknown, 100, false, false, false, false) == V.WaitAge, "unknown place waits while young");
|
||||
Check(AutoIdPolicy.Decide(AutoIdMode.Limited, C.Unknown, Old, false, false, false, false) == V.SkipMode, "still unknown when old: skipped");
|
||||
Check(AutoIdPolicy.DefaultMode == AutoIdMode.Limited, "default mode is Limited");
|
||||
}
|
||||
|
||||
// ---- the post-transition defer -----------------------------------------------------
|
||||
|
||||
private static void AutoIdDeferWindow()
|
||||
{
|
||||
_case = "autoid defer window";
|
||||
const long D = AutoIdPolicy.DeferMs;
|
||||
const long S = WorldTransitionState.SettleMs;
|
||||
// Login completed long before (at 1); every time below is shifted past its defer.
|
||||
const long B = 1_000_000;
|
||||
static bool Def(long now, long settle, bool inTransition) =>
|
||||
AutoIdPolicy.InDefer(now + B, settle == 0 ? 0 : settle + B, 1, inTransition);
|
||||
|
||||
// No transition yet: nothing is deferred.
|
||||
var w = new WorldTransitionState();
|
||||
w.Sample(1000, dead: false, portaling: false, landblock: 0xA9B4);
|
||||
Check(!Def(1000, w.SettleUntilMs, w.InTransition(1000)), "no transition, no defer");
|
||||
|
||||
// Walking into the next landblock never defers.
|
||||
w.Sample(2000, false, false, 0xAAB4);
|
||||
w.Sample(3000, false, false, 0xAAB5);
|
||||
Check(w.SettleUntilMs == 0, "an adjacent walk sets no settle window");
|
||||
Check(!Def(3000, w.SettleUntilMs, w.InTransition(3000)), "adjacent walk: no defer");
|
||||
|
||||
// A portal: deferred through portal space, the settle window, and DeferMs after it.
|
||||
w.Sample(10_000, false, true, 0xAAB5);
|
||||
Check(Def(10_000, w.SettleUntilMs, w.InTransition(10_000)), "in portal space: deferred");
|
||||
w.Sample(12_000, false, false, 0x0007);
|
||||
long settleEnd = w.SettleUntilMs;
|
||||
Check(settleEnd == 12_000 + S, $"settle ends {S} ms after the portal exit, got {settleEnd}");
|
||||
Check(Def(settleEnd + D - 1, settleEnd, w.InTransition(settleEnd + D - 1)), "deferred until DeferMs after the settle");
|
||||
Check(!Def(settleEnd + D, settleEnd, w.InTransition(settleEnd + D)), "not deferred at DeferMs after the settle");
|
||||
|
||||
// A container opened after the settle ended is exempt; one opened before is not.
|
||||
Check(AutoIdPolicy.OpenedAfterSettle(settleEnd + 1, settleEnd), "opened after the settle: exempt");
|
||||
Check(!AutoIdPolicy.OpenedAfterSettle(settleEnd - 1, settleEnd), "opened during the settle: not exempt");
|
||||
Check(!AutoIdPolicy.OpenedAfterSettle(0, settleEnd), "never opened: not exempt");
|
||||
|
||||
// Death defers too.
|
||||
var d = new WorldTransitionState();
|
||||
d.Sample(1000, false, false, 0x1234);
|
||||
d.Sample(2000, true, false, 0x1234);
|
||||
d.Sample(3000, false, false, 0x1234);
|
||||
Check(Def(3000 + S + D - 1, d.SettleUntilMs, false), "death: deferred");
|
||||
Check(!Def(3000 + S + D, d.SettleUntilMs, false), "death: defer ends");
|
||||
|
||||
// A landblock jump without portal space defers.
|
||||
var j = new WorldTransitionState();
|
||||
j.Sample(1000, false, false, 0x00AE);
|
||||
j.Sample(1100, false, false, 0xA9B4);
|
||||
Check(Def(1100 + S + D - 1, j.SettleUntilMs, false), "landblock jump: deferred");
|
||||
|
||||
// A PlayerTeleport message (a recall into the next landblock) defers.
|
||||
var t = new WorldTransitionState();
|
||||
t.Sample(1000, false, false, 0x1234);
|
||||
t.OnTeleportMessage(5000);
|
||||
Check(Def(5000 + S + D - 1, t.SettleUntilMs, false), "teleport message: deferred");
|
||||
Check(!Def(5000 + S + D, t.SettleUntilMs, false), "teleport message: defer ends");
|
||||
|
||||
// In a transition right now: deferred whatever the settle time says.
|
||||
Check(Def(1, 0, inTransition: true), "in a transition: deferred");
|
||||
}
|
||||
|
||||
// ---- login is a transition (a client crashed in the login create burst) ----------------
|
||||
|
||||
private static void AutoIdLoginDefer()
|
||||
{
|
||||
_case = "autoid login defer";
|
||||
const long D = AutoIdPolicy.DeferMs;
|
||||
const long Login = 500_000;
|
||||
|
||||
// Before login completes (the create burst): everything background is deferred.
|
||||
Check(AutoIdPolicy.InDefer(Login - 1, 0, 0, false), "login not complete: deferred");
|
||||
Check(AutoIdPolicy.InDefer(10_000_000, 0, 0, false), "login never completed: still deferred");
|
||||
// After: DeferMs past login-complete, exactly like the post-teleport defer.
|
||||
Check(AutoIdPolicy.InDefer(Login, 0, Login, false), "at login-complete: deferred");
|
||||
Check(AutoIdPolicy.InDefer(Login + D - 1, 0, Login, false), "deferred until DeferMs after login");
|
||||
Check(!AutoIdPolicy.InDefer(Login + D, 0, Login, false), "not deferred at DeferMs after login");
|
||||
// The later of login and the last settle window decides.
|
||||
Check(AutoIdPolicy.TransitionEndMs(0, Login) == Login, "no transition yet: the login is the last one");
|
||||
Check(AutoIdPolicy.TransitionEndMs(Login + 9_000, Login) == Login + 9_000, "a portal after login: the portal's settle");
|
||||
Check(AutoIdPolicy.TransitionEndMs(Login - 9_000, Login) == Login, "a portal before login: the login");
|
||||
Check(AutoIdPolicy.InDefer(Login + 9_000 + D - 1, Login + 9_000, Login, false), "portal after login: its own defer");
|
||||
Check(AutoIdPolicy.InDefer(Login + D - 1, Login - 9_000, Login, false), "a settle before login does not shorten the login defer");
|
||||
// A container the player opens after login-complete is exempt; one opened before it is not.
|
||||
Check(AutoIdPolicy.OpenedAfterSettle(Login + 1, AutoIdPolicy.TransitionEndMs(0, Login)), "opened after login: exempt");
|
||||
Check(!AutoIdPolicy.OpenedAfterSettle(Login - 1, AutoIdPolicy.TransitionEndMs(0, Login)), "opened before login completed: not exempt");
|
||||
// The decision during the login defer: pack and container items wait, the target does not.
|
||||
bool inDefer = AutoIdPolicy.InDefer(Login + 1_000, 0, Login, false);
|
||||
Check(AutoIdPolicy.Decide(AutoIdMode.Limited, C.Inventory, 60_000, inDefer, false, false, false) == V.WaitDefer, "login: pack item waits");
|
||||
Check(AutoIdPolicy.Decide(AutoIdMode.Limited, C.Container, 60_000, inDefer, false, false, false) == V.WaitDefer, "login: container item waits");
|
||||
Check(AutoIdPolicy.Decide(AutoIdMode.Limited, C.Target, 0, inDefer, false, false, false) == V.Send, "login: the selected target is exempt");
|
||||
}
|
||||
|
||||
private static void AutoIdInventoryRate()
|
||||
{
|
||||
_case = "autoid inventory rate";
|
||||
const long I = AutoIdPolicy.InventoryMinIntervalMs;
|
||||
Check(I == 200, "5 a second");
|
||||
Check(AutoIdPolicy.InventoryRateAllows(1_000, 0), "the first send is allowed");
|
||||
Check(!AutoIdPolicy.InventoryRateAllows(1_000 + I - 1, 1_000), "not again inside the interval");
|
||||
Check(AutoIdPolicy.InventoryRateAllows(1_000 + I, 1_000), "again at the interval");
|
||||
|
||||
// Simulate the drain: a 100 ms timer, 3 sends a tick at most, 50 uncached pack items
|
||||
// past their age and the defer. Sends per second never pass 5.
|
||||
long last = 0;
|
||||
int pending = 50;
|
||||
var sendTimes = new List<long>();
|
||||
for (long now = 100; now <= 20_000 && pending > 0; now += 100)
|
||||
{
|
||||
int sentThisTick = 0;
|
||||
for (int k = 0; k < pending && sentThisTick < 3; k++)
|
||||
{
|
||||
bool ok = AutoIdPolicy.InventoryRateAllows(now, last);
|
||||
V v = AutoIdPolicy.Decide(AutoIdMode.Limited, C.Inventory, 60_000, false, false, false, false, ok);
|
||||
if (v != V.Send) continue;
|
||||
last = now;
|
||||
sentThisTick++;
|
||||
sendTimes.Add(now);
|
||||
}
|
||||
pending -= sentThisTick;
|
||||
}
|
||||
Check(pending == 0, $"all 50 sent eventually, {pending} left");
|
||||
int worst = 0;
|
||||
foreach (long t0 in sendTimes)
|
||||
worst = Math.Max(worst, sendTimes.Count(t => t >= t0 && t < t0 + 1_000));
|
||||
Check(worst <= 5, $"at most 5 inventory sends in any second, got {worst}");
|
||||
Check(worst == 5, $"and the cap is reached (5), got {worst}");
|
||||
}
|
||||
|
||||
// ---- where an object is ------------------------------------------------------------
|
||||
|
||||
private static void AutoIdClassify()
|
||||
{
|
||||
_case = "autoid classify";
|
||||
const uint Me = 0x50000001, Corpse = 0x80000100, Pack = 0x80000200, Monster = 0x80000300, Chest = 0x80000400;
|
||||
Check(AutoIdPolicy.Classify(false, Me, Corpse, Corpse, 0, 0) == C.Unknown, "not in the snapshot: unknown");
|
||||
Check(AutoIdPolicy.Classify(true, Me, 0, Me, 0, 0) == C.Inventory, "in the main pack");
|
||||
Check(AutoIdPolicy.Classify(true, Me, 0, 0, Me, 0) == C.Inventory, "worn");
|
||||
Check(AutoIdPolicy.Classify(true, Me, 0, Pack, 0, Me) == C.Inventory, "in a side pack");
|
||||
Check(AutoIdPolicy.Classify(true, Me, Pack, Pack, 0, Me) == C.Inventory, "in an opened own side pack: inventory");
|
||||
Check(AutoIdPolicy.Classify(true, Me, Corpse, Corpse, 0, 0) == C.Container, "in the open corpse");
|
||||
Check(AutoIdPolicy.Classify(true, Me, Chest, Pack, 0, Chest) == C.Container, "in a pack inside the open chest");
|
||||
Check(AutoIdPolicy.Classify(true, Me, Chest, Corpse, 0, 0) == C.World, "in a corpse that is not open");
|
||||
Check(AutoIdPolicy.Classify(true, Me, 0, 0, 0, 0) == C.World, "on the ground, nothing open");
|
||||
Check(AutoIdPolicy.Classify(true, Me, Corpse, 0, 0, 0) == C.World, "on the ground while a corpse is open (container 0 is not the open one)");
|
||||
Check(AutoIdPolicy.Classify(true, Me, Corpse, 0, Monster, 0) == C.World, "wielded by a monster");
|
||||
Check(AutoIdPolicy.Classify(true, 0, 0, 0, 0, 0) == C.World, "player unknown: nothing is inventory");
|
||||
}
|
||||
|
||||
private static void AutoIdModeParse()
|
||||
{
|
||||
_case = "autoid mode parse";
|
||||
Check(AutoIdPolicy.TryParseMode("ALL", out AutoIdMode m) && m == AutoIdMode.All, "all");
|
||||
Check(AutoIdPolicy.TryParseMode(" limited ", out m) && m == AutoIdMode.Limited, "limited");
|
||||
Check(AutoIdPolicy.TryParseMode("off", out m) && m == AutoIdMode.Off, "off");
|
||||
Check(!AutoIdPolicy.TryParseMode("sometimes", out m) && m == AutoIdPolicy.DefaultMode, "unknown: false, default");
|
||||
foreach (AutoIdMode mode in Enum.GetValues<AutoIdMode>())
|
||||
Check(AutoIdPolicy.TryParseMode(AutoIdPolicy.Name(mode), out m) && m == mode, $"{mode} round-trips by name");
|
||||
foreach (AutoIdMode mode in Enum.GetValues<AutoIdMode>())
|
||||
Check(AutoIdPolicy.TryParseMode(mode.ToString(), out m) && m == mode, $"{mode} round-trips as engine.json writes it");
|
||||
}
|
||||
|
||||
// ---- the engine-send marker --------------------------------------------------------
|
||||
|
||||
private static void IdMarkerScopes()
|
||||
{
|
||||
_case = "id marker";
|
||||
Check(EngineSendMarker.Current == IdRequester.None, "no marker outside a scope");
|
||||
using (EngineSendMarker.Enter(IdRequester.Plugin))
|
||||
{
|
||||
Check(EngineSendMarker.Current == IdRequester.Plugin, "marked inside");
|
||||
using (EngineSendMarker.Enter(IdRequester.AutoIdContainer))
|
||||
Check(EngineSendMarker.Current == IdRequester.AutoIdContainer, "nested scope");
|
||||
Check(EngineSendMarker.Current == IdRequester.Plugin, "outer marker restored");
|
||||
|
||||
IdRequester seenElsewhere = IdRequester.Self;
|
||||
var th = new Thread(() => seenElsewhere = EngineSendMarker.Current);
|
||||
th.Start();
|
||||
th.Join();
|
||||
Check(seenElsewhere == IdRequester.None, "another thread is not marked (thread-local)");
|
||||
}
|
||||
Check(EngineSendMarker.Current == IdRequester.None, "cleared after the scope");
|
||||
try
|
||||
{
|
||||
using (EngineSendMarker.Enter(IdRequester.Ui))
|
||||
throw new InvalidOperationException();
|
||||
}
|
||||
catch (InvalidOperationException) { }
|
||||
Check(EngineSendMarker.Current == IdRequester.None, "cleared after an exception");
|
||||
}
|
||||
|
||||
private static void IdMarkerRidesTheQueue()
|
||||
{
|
||||
_case = "id marker queue";
|
||||
var q = new PendingIdQueue(8);
|
||||
q.Enqueue(1, 1000, 1, MergeMax, 0, (byte)IdRequester.AutoIdContainer);
|
||||
q.Enqueue(2, 1000, 1, MergeMax, 0, (byte)IdRequester.Plugin);
|
||||
Check(q.Enqueue(1, 1100, 1, MergeMax, 0, (byte)IdRequester.Plugin) == PendingIdQueue.Result.Merged, "merged");
|
||||
Check(q.TryDequeue(out var a) && a.Source == (byte)IdRequester.AutoIdContainer, "the requester rides with the entry; a merge keeps the first");
|
||||
Check(q.TryDequeue(out var b) && b.Source == (byte)IdRequester.Plugin, "second entry's requester");
|
||||
q.Enqueue(3, 1200, 1, MergeMax);
|
||||
Check(q.TryDequeue(out var c) && c.Source == 0, "unmarked stays None");
|
||||
}
|
||||
|
||||
private static void IdHeartbeatNames()
|
||||
{
|
||||
_case = "id heartbeat names";
|
||||
foreach (IdRequester who in Enum.GetValues<IdRequester>())
|
||||
{
|
||||
string s = IdRequesters.Short(who) + "=";
|
||||
foreach (string bad in new[] { "fps=", "plug=", "login=", "qd=" })
|
||||
Check(!s.Contains(bad) && !bad.Contains(s), $"{who}: \"{s}\" vs {bad}");
|
||||
if (who != IdRequester.None)
|
||||
Check(IdRequesters.Label((uint)who).Length > 0, $"{who} has a flight label");
|
||||
}
|
||||
Check(IdRequesters.Label(0) == "" && IdRequesters.Label(99) == "", "no label for none or an unknown code");
|
||||
var regex = new System.Text.RegularExpressions.Regex(@"hb #\d+ .*?fps=(\d+) .*?plug=(\d+)/s .*?login=(\d)(?:.*?qd=(\d+))?");
|
||||
string sample = "autoid 60s: mode=limited sent tgt=1 ctr=2 inv=0 wld=0 plg=5 slf=0 ui=0 cli=3 tot=11 skip mode=900 age=4 defer=0 fresh=1 pend=2";
|
||||
Check(!regex.IsMatch(sample), "the minute line does not match the launcher's heartbeat regex");
|
||||
}
|
||||
}
|
||||
55
tools/EngineRobustnessTests/EngineRobustnessTests.csproj
Normal file
55
tools/EngineRobustnessTests/EngineRobustnessTests.csproj
Normal file
|
|
@ -0,0 +1,55 @@
|
|||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<!--
|
||||
Offline checks for the engine-robustness pass, the pure parts compiled in:
|
||||
PendingIdQueue.cs the RequestId slot merges a pending appraisal for the same object
|
||||
AutoIdEligibility.cs no re-appraisal within 10 min of a client release; server delete
|
||||
re-arms; the map stays bounded
|
||||
MainThreadFreezeRule.cs plugin ticks pause while AC's main thread is frozen
|
||||
WorldTransitionState.cs queued game actions are held through a death / portal / landblock
|
||||
jump, then stale ones dropped while stops and cancels still run
|
||||
AddressSpace.cs the largest-free-block fold (and one live walk of this process)
|
||||
ActionRing.cs the action ring itself: teardown reserve, refusal in a transition
|
||||
CastStopRules.cs a cast waits for a movement stop queued at or before it
|
||||
MutatorGate.cs queue-or-call for every mutator (plus a source scan of the call sites)
|
||||
ReleasedObjectRetention identify data kept 10 min after a client release
|
||||
DumpInProgressRule.cs the launcher holds its wedge kill while an OOM dump is written (capped)
|
||||
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
|
||||
PumpGuards.cs TickAll's own steps are caught (logged once, then counted); the hang
|
||||
report names the plugin call the pump is inside
|
||||
Run: dotnet run -c Release (exit 0 = pass, 1 = fail)
|
||||
-->
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<Nullable>enable</Nullable>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<InvariantGlobalization>true</InvariantGlobalization>
|
||||
<RootNamespace>EngineRobustnessTests</RootNamespace>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Compile Include="..\..\src\RynthCore.Engine\Compatibility\PendingIdQueue.cs" Link="Engine\PendingIdQueue.cs" />
|
||||
<Compile Include="..\..\src\RynthCore.Engine\Compatibility\AutoIdEligibility.cs" Link="Engine\AutoIdEligibility.cs" />
|
||||
<Compile Include="..\..\src\RynthCore.Engine\MainThreadFreezeRule.cs" Link="Engine\MainThreadFreezeRule.cs" />
|
||||
<Compile Include="..\..\src\RynthCore.Engine\Compatibility\WorldTransitionState.cs" Link="Engine\WorldTransitionState.cs" />
|
||||
<Compile Include="..\..\src\RynthCore.Engine\Compatibility\AddressSpace.cs" Link="Engine\AddressSpace.cs" />
|
||||
<Compile Include="..\..\src\RynthCore.Engine\Compatibility\ActionRing.cs" Link="Engine\ActionRing.cs" />
|
||||
<Compile Include="..\..\src\RynthCore.Engine\Compatibility\CastStopRules.cs" Link="Engine\CastStopRules.cs" />
|
||||
<Compile Include="..\..\src\RynthCore.Engine\Compatibility\MutatorGate.cs" Link="Engine\MutatorGate.cs" />
|
||||
<Compile Include="..\..\src\RynthCore.Engine\Compatibility\ReleasedObjectRetention.cs" Link="Engine\ReleasedObjectRetention.cs" />
|
||||
<Compile Include="..\..\src\Shared\DumpInProgressRule.cs" Link="Shared\DumpInProgressRule.cs" />
|
||||
<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" />
|
||||
<Compile Include="..\..\src\RynthCore.Engine\Plugins\PumpGuards.cs" Link="Engine\PumpGuards.cs" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
417
tools/EngineRobustnessTests/Program.cs
Normal file
417
tools/EngineRobustnessTests/Program.cs
Normal file
|
|
@ -0,0 +1,417 @@
|
|||
using RynthCore.Engine;
|
||||
using RynthCore.Engine.Compatibility;
|
||||
|
||||
namespace EngineRobustnessTests;
|
||||
|
||||
/// <summary>
|
||||
/// The pure decision parts of the engine-robustness pass. Every clock is a plain
|
||||
/// number; nothing touches AC.
|
||||
/// </summary>
|
||||
internal static partial class Program
|
||||
{
|
||||
private static int _checks, _failed;
|
||||
private static string _case = "";
|
||||
|
||||
private static int Main()
|
||||
{
|
||||
QueueMergesSameObject();
|
||||
QueueDoesNotMergeAcrossLoginOrWhenStale();
|
||||
QueueFullStillMerges();
|
||||
|
||||
EligibilityCreateAndDuplicate();
|
||||
EligibilityWindowAfterClientRelease();
|
||||
EligibilityServerDeleteReArms();
|
||||
EligibilityUncachedIsAppraised();
|
||||
EligibilityReleaseBeforeSendRecordsNothing();
|
||||
EligibilityMapStaysBounded();
|
||||
PriorityFreshRule();
|
||||
|
||||
FreezeRule();
|
||||
PauseTracker();
|
||||
|
||||
TransitionHoldsWhileDead();
|
||||
TransitionLandblockJumpWithoutPortalHolds();
|
||||
TransitionAdjacentCrossingDoesNotHold();
|
||||
TransitionPortalHolds();
|
||||
TransitionShortTeleportToAdjacentLandblockHolds();
|
||||
TransitionDiagonalAndBorderWalksNeverHold();
|
||||
TransitionTwoLandblockJumpHolds();
|
||||
TransitionDrainHoldThenStopsSurvive();
|
||||
|
||||
AddressSpaceFold();
|
||||
|
||||
RunRingAndGateTests();
|
||||
|
||||
RunAutoIdLimitTests();
|
||||
RunAutoIdDrainTests();
|
||||
|
||||
RunPumpGuardTests();
|
||||
|
||||
Console.WriteLine($"{_checks} check(s), {_failed} failed.");
|
||||
return _failed == 0 ? 0 : 1;
|
||||
}
|
||||
|
||||
private static void Check(bool ok, string what)
|
||||
{
|
||||
_checks++;
|
||||
if (ok) return;
|
||||
_failed++;
|
||||
Console.WriteLine($"[FAIL] {_case}: {what}");
|
||||
}
|
||||
|
||||
// ---- fix 1: the RequestId slot merges ---------------------------------------------
|
||||
|
||||
private const long MergeMax = 15_000;
|
||||
|
||||
private static void QueueMergesSameObject()
|
||||
{
|
||||
_case = "queue merge";
|
||||
var q = new PendingIdQueue(8);
|
||||
Check(q.Enqueue(0x80000001, 1000, 1, MergeMax) == PendingIdQueue.Result.Queued, "first request queued");
|
||||
Check(q.Enqueue(0x80000002, 1010, 1, MergeMax) == PendingIdQueue.Result.Queued, "other object queued");
|
||||
Check(q.Enqueue(0x80000001, 1100, 1, MergeMax) == PendingIdQueue.Result.Merged, "same object merged");
|
||||
Check(q.Enqueue(0x80000001, 1200, 1, MergeMax) == PendingIdQueue.Result.Merged, "merged again");
|
||||
Check(q.Count == 2, $"two pending, got {q.Count}");
|
||||
Check(q.MergedTotal == 2, $"two merges counted, got {q.MergedTotal}");
|
||||
Check(q.TryDequeue(out var a) && a.Id == 0x80000001 && a.At == 1000, "FIFO head is the first request, original time");
|
||||
Check(q.TryDequeue(out var b) && b.Id == 0x80000002, "then the second object");
|
||||
Check(!q.TryDequeue(out _), "empty");
|
||||
// Once sent (dequeued), a new request for the same object queues again.
|
||||
Check(q.Enqueue(0x80000001, 1300, 1, MergeMax) == PendingIdQueue.Result.Queued, "re-queued after the send");
|
||||
}
|
||||
|
||||
private static void QueueDoesNotMergeAcrossLoginOrWhenStale()
|
||||
{
|
||||
_case = "queue no merge";
|
||||
var q = new PendingIdQueue(8);
|
||||
q.Enqueue(7, 1000, 1, MergeMax);
|
||||
Check(q.Enqueue(7, 1100, 2, MergeMax) == PendingIdQueue.Result.Queued, "a new login's request is not absorbed by the old one");
|
||||
Check(q.Enqueue(7, 1200, 1, MergeMax) == PendingIdQueue.Result.Merged,
|
||||
"a later epoch-1 request still merges into the epoch-1 entry");
|
||||
Check(q.Enqueue(7, 1300, 2, MergeMax) == PendingIdQueue.Result.Merged,
|
||||
"and an epoch-2 one into the epoch-2 entry");
|
||||
Check(q.Count == 2, $"one entry per login, got {q.Count}");
|
||||
var r = new PendingIdQueue(8);
|
||||
r.Enqueue(9, 1000, 1, MergeMax);
|
||||
Check(r.Enqueue(9, 1000 + MergeMax + 1, 1, MergeMax) == PendingIdQueue.Result.Queued, "a stale pending entry takes no merge");
|
||||
Check(r.Count == 2, "both kept");
|
||||
}
|
||||
|
||||
private static void QueueFullStillMerges()
|
||||
{
|
||||
_case = "queue full";
|
||||
var q = new PendingIdQueue(3);
|
||||
q.Enqueue(1, 0, 1, MergeMax); q.Enqueue(2, 0, 1, MergeMax); q.Enqueue(3, 0, 1, MergeMax);
|
||||
Check(q.Enqueue(4, 1, 1, MergeMax) == PendingIdQueue.Result.Full, "a new object is refused when full");
|
||||
Check(q.Enqueue(2, 1, 1, MergeMax) == PendingIdQueue.Result.Merged, "a pending object still merges when full");
|
||||
// Wrap-around: dequeue one, add one, order holds.
|
||||
q.TryDequeue(out _);
|
||||
q.Enqueue(5, 2, 1, MergeMax);
|
||||
var order = new List<uint>();
|
||||
while (q.TryDequeue(out var it)) order.Add(it.Id);
|
||||
Check(string.Join(",", order) == "2,3,5", $"FIFO across the wrap, got {string.Join(",", order)}");
|
||||
}
|
||||
|
||||
// ---- fix 3: re-eligibility ---------------------------------------------------------
|
||||
|
||||
private const long Min = 60_000;
|
||||
|
||||
private static void EligibilityCreateAndDuplicate()
|
||||
{
|
||||
_case = "eligibility create";
|
||||
var e = new AutoIdEligibility();
|
||||
Check(e.OnCreate(10, 1000, false) == AutoIdEligibility.CreateDecision.Appraise, "a new object is appraised");
|
||||
Check(e.OnCreate(10, 1001, false) == AutoIdEligibility.CreateDecision.SkipDuplicate, "a second create while live is a duplicate");
|
||||
Check(e.IsLive(10), "live");
|
||||
e.OnClientRelease(10);
|
||||
Check(!e.IsLive(10), "released");
|
||||
Check(e.IsLive(999), "an untracked id counts as live (the drain sends it)");
|
||||
}
|
||||
|
||||
private static void EligibilityWindowAfterClientRelease()
|
||||
{
|
||||
_case = "eligibility window";
|
||||
var e = new AutoIdEligibility();
|
||||
e.OnCreate(10, 0, false);
|
||||
e.OnSent(10, 1000);
|
||||
e.OnClientRelease(10);
|
||||
Check(e.OnCreate(10, 1000 + 1 * Min, true) == AutoIdEligibility.CreateDecision.SkipRecent, "re-created 1 min later, cached: skipped");
|
||||
e.OnClientRelease(10);
|
||||
Check(e.OnCreate(10, 1000 + 9 * Min, true) == AutoIdEligibility.CreateDecision.SkipRecent, "9 min later: still skipped");
|
||||
e.OnClientRelease(10);
|
||||
Check(e.OnCreate(10, 1000 + 10 * Min, true) == AutoIdEligibility.CreateDecision.Appraise, "10 min later: appraised again");
|
||||
}
|
||||
|
||||
private static void EligibilityServerDeleteReArms()
|
||||
{
|
||||
_case = "eligibility server delete";
|
||||
var e = new AutoIdEligibility();
|
||||
e.OnCreate(20, 0, false);
|
||||
e.OnSent(20, 1000);
|
||||
e.OnServerDelete(20);
|
||||
e.OnClientRelease(20);
|
||||
Check(e.OnCreate(20, 2000, true) == AutoIdEligibility.CreateDecision.Appraise, "server delete then re-create inside the window: appraised");
|
||||
// Client release first, server delete after: same result.
|
||||
e.OnSent(20, 3000);
|
||||
e.OnClientRelease(20);
|
||||
e.OnServerDelete(20);
|
||||
Check(e.OnCreate(20, 4000, true) == AutoIdEligibility.CreateDecision.Appraise, "release then server delete: appraised");
|
||||
}
|
||||
|
||||
private static void EligibilityUncachedIsAppraised()
|
||||
{
|
||||
_case = "eligibility uncached";
|
||||
var e = new AutoIdEligibility();
|
||||
e.OnCreate(30, 0, false);
|
||||
e.OnSent(30, 1000);
|
||||
e.OnClientRelease(30);
|
||||
Check(e.OnCreate(30, 2000, false) == AutoIdEligibility.CreateDecision.Appraise, "nothing cached any more: appraised even inside the window");
|
||||
}
|
||||
|
||||
private static void EligibilityReleaseBeforeSendRecordsNothing()
|
||||
{
|
||||
_case = "eligibility unsent";
|
||||
var e = new AutoIdEligibility();
|
||||
e.OnCreate(40, 0, false);
|
||||
e.OnClientRelease(40); // released before the drain sent its appraisal
|
||||
Check(e.OnCreate(40, 500, true) == AutoIdEligibility.CreateDecision.Appraise, "never sent: the next create is appraised");
|
||||
}
|
||||
|
||||
private static void EligibilityMapStaysBounded()
|
||||
{
|
||||
_case = "eligibility bound";
|
||||
var e = new AutoIdEligibility(10 * Min, 100);
|
||||
for (uint i = 1; i <= 100; i++) e.OnCreate(i, 0, false);
|
||||
Check(e.Count == 100, $"100 tracked, got {e.Count}");
|
||||
Check(e.OnCreate(101, 0, false) == AutoIdEligibility.CreateDecision.Appraise, "past the bound a create is still appraised");
|
||||
Check(e.Count == 100 && e.UntrackedAdmits == 1, $"but not tracked (count {e.Count}, untracked {e.UntrackedAdmits})");
|
||||
Check(e.Prune(1000) == 0, "all live: nothing pruned");
|
||||
|
||||
// 80 of them appraised (sent at different times) and released, all inside the window.
|
||||
for (uint i = 1; i <= 80; i++) { e.OnSent(i, 1000 + i); e.OnClientRelease(i); }
|
||||
int removed = e.Prune(2 * Min);
|
||||
Check(e.Count <= 75, $"pruned to three quarters of the bound, count {e.Count} (removed {removed})");
|
||||
bool liveKept = true;
|
||||
for (uint i = 81; i <= 100; i++) liveKept &= e.IsLive(i) && e.OnCreate(i, 2 * Min, true) == AutoIdEligibility.CreateDecision.SkipDuplicate;
|
||||
Check(liveKept, "the 20 live entries are never pruned");
|
||||
// The newest-sent released entries survive the age passes before the oldest.
|
||||
Check(e.OnCreate(80, 2 * Min, true) == AutoIdEligibility.CreateDecision.SkipRecent, "the most recently sent released entry survived");
|
||||
|
||||
// Outside the window everything released goes.
|
||||
var f = new AutoIdEligibility(10 * Min, 100);
|
||||
for (uint i = 1; i <= 50; i++) { f.OnCreate(i, 0, false); f.OnSent(i, 1); f.OnClientRelease(i); }
|
||||
f.Prune(11 * Min);
|
||||
Check(f.Count == 0, $"expired released entries are pruned, count {f.Count}");
|
||||
}
|
||||
|
||||
private static void PriorityFreshRule()
|
||||
{
|
||||
_case = "priority fresh";
|
||||
long now = 1_800_000_000;
|
||||
Check(AutoIdEligibility.IsAppraisalFresh(true, now - 60, now, 10 * Min), "cached, 1 min old: fresh (skip)");
|
||||
Check(!AutoIdEligibility.IsAppraisalFresh(true, now - 601, now, 10 * Min), "cached, 10 min+ old: stale (appraise)");
|
||||
Check(!AutoIdEligibility.IsAppraisalFresh(false, now - 60, now, 10 * Min), "not cached: appraise");
|
||||
Check(!AutoIdEligibility.IsAppraisalFresh(true, 0, now, 10 * Min), "no receive time: appraise");
|
||||
}
|
||||
|
||||
// ---- fix 4: the plugin pump pauses while AC is frozen --------------------------------
|
||||
|
||||
private static void FreezeRule()
|
||||
{
|
||||
_case = "freeze rule";
|
||||
const long T = 4000;
|
||||
Check(!MainThreadFreezeRule.IsFrozen(100_000, 0, false, 0, T), "no beat yet: not frozen");
|
||||
Check(!MainThreadFreezeRule.IsFrozen(100_000, 99_000, true, 0, T), "beat 1 s ago: running");
|
||||
Check(MainThreadFreezeRule.IsFrozen(100_000, 96_000, true, 0, T), "beat 4 s ago: frozen (the hang watchdog's threshold)");
|
||||
Check(MainThreadFreezeRule.IsFrozen(100_000, 99_900, true, 1, T), "a main-thread message box: frozen at once");
|
||||
Check(MainThreadFreezeRule.IsFrozen(100_000, 0, false, 1, T), "a message box before the first beat: frozen");
|
||||
}
|
||||
|
||||
private static void PauseTracker()
|
||||
{
|
||||
_case = "pause tracker";
|
||||
var t = new PumpPauseTracker();
|
||||
Check(t.Update(false, 1000) == PumpPauseTracker.Transition.None && !t.Paused, "running");
|
||||
Check(t.Update(true, 2000) == PumpPauseTracker.Transition.Paused && t.Paused, "pauses");
|
||||
Check(t.Update(true, 2016) == PumpPauseTracker.Transition.None, "stays paused");
|
||||
Check(t.TicksSkippedThisPause == 2, $"2 ticks skipped, got {t.TicksSkippedThisPause}");
|
||||
Check(t.TotalPausedMs(5000) == 3000, $"3000 ms paused in progress, got {t.TotalPausedMs(5000)}");
|
||||
Check(t.Update(false, 14000) == PumpPauseTracker.Transition.Resumed && !t.Paused, "resumes");
|
||||
Check(t.FinishedPausedMs == 12000 && t.TotalPausedMs(20000) == 12000, $"12 s in total, got {t.FinishedPausedMs}");
|
||||
t.Update(true, 30000); t.Update(false, 30500);
|
||||
Check(t.Pauses == 2 && t.FinishedPausedMs == 12500 && t.TicksSkippedTotal == 3, "second pause adds up");
|
||||
}
|
||||
|
||||
// ---- the world-transition gate (coordinator items c and g) --------------------------
|
||||
|
||||
private static WorldTransitionState Started(uint landblock = 0x00AE)
|
||||
{
|
||||
var s = new WorldTransitionState();
|
||||
s.Sample(1000, false, false, landblock);
|
||||
return s;
|
||||
}
|
||||
|
||||
private static void TransitionHoldsWhileDead()
|
||||
{
|
||||
_case = "transition dead";
|
||||
var s = Started();
|
||||
Check(!s.InTransition(1100), "alive and still: no transition");
|
||||
Check(s.Decide(1100, 1050, false) == WorldTransitionState.Verdict.Run, "work runs normally");
|
||||
var edges = s.Sample(2000, true, false, 0x00AE);
|
||||
Check((edges & WorldTransitionState.Edge.Died) != 0, "death edge");
|
||||
Check(s.Decide(2000, 1900, false) == WorldTransitionState.Verdict.Hold, "a cast queued before the death is held");
|
||||
Check(s.Decide(2000, 1900, true) == WorldTransitionState.Verdict.Hold, "a stop is held too (never run into the death)");
|
||||
s.Sample(9000, false, false, 0x00AE); // revived
|
||||
Check(s.InTransition(9000 + WorldTransitionState.SettleMs - 1), "settle window after revival");
|
||||
Check(!s.InTransition(9000 + WorldTransitionState.SettleMs), "window ends");
|
||||
}
|
||||
|
||||
private static void TransitionLandblockJumpWithoutPortalHolds()
|
||||
{
|
||||
_case = "transition jump";
|
||||
// A real case: a death recall jumped 0x00AE -> 0xA9B4 with no portal-space edge.
|
||||
var s = Started(0x00AE);
|
||||
var edges = s.Sample(5000, false, false, 0xA9B4);
|
||||
Check((edges & WorldTransitionState.Edge.LandblockJump) != 0, "jump edge");
|
||||
Check(s.InTransition(5000) && s.InTransition(5000 + WorldTransitionState.SettleMs - 1), "the jump alone starts the settle window");
|
||||
Check(s.Decide(6000, 4900, false) == WorldTransitionState.Verdict.Hold, "queued work is held after the jump");
|
||||
Check(WorldTransitionState.IsJump(0x00AE, 0xA9B4) && !WorldTransitionState.IsJump(0xA9B4, 0xA9B5) && !WorldTransitionState.IsJump(0xA9B4, 0xAAB5),
|
||||
"adjacent (including diagonal) is not a jump");
|
||||
}
|
||||
|
||||
private static void TransitionAdjacentCrossingDoesNotHold()
|
||||
{
|
||||
_case = "transition adjacent";
|
||||
var s = Started(0xA9B4);
|
||||
var edges = s.Sample(5000, false, false, 0xA9B5);
|
||||
Check(edges == WorldTransitionState.Edge.None, "walking into the next landblock: no edge");
|
||||
Check(!s.InTransition(5000) && s.Decide(5000, 4990, false) == WorldTransitionState.Verdict.Run, "and no hold");
|
||||
}
|
||||
|
||||
private static void TransitionPortalHolds()
|
||||
{
|
||||
_case = "transition portal";
|
||||
var s = Started();
|
||||
s.Sample(2000, false, true, 0x00AE);
|
||||
Check(s.Decide(2500, 1990, false) == WorldTransitionState.Verdict.Hold, "held in portal space");
|
||||
s.Sample(4000, false, false, 0x00AE);
|
||||
Check(s.InTransition(4000 + WorldTransitionState.SettleMs - 1), "settle window after portal exit");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A recall or portal into the NEXT landblock (a lifestone just over the border): no
|
||||
/// non-adjacent jump, but teleport_in_progress (the portaling flag) is the signal, and the
|
||||
/// full settle follows it.
|
||||
/// </summary>
|
||||
private static void TransitionShortTeleportToAdjacentLandblockHolds()
|
||||
{
|
||||
_case = "transition short teleport";
|
||||
var s = Started(0xA9B4);
|
||||
s.Sample(2000, false, true, 0xA9B4); // teleport_in_progress set
|
||||
s.Sample(2500, false, true, 0xA9B5); // lands one landblock over
|
||||
var edges = s.Sample(3000, false, false, 0xA9B5);
|
||||
Check((edges & WorldTransitionState.Edge.PortalExited) != 0, "portal exit edge");
|
||||
Check(s.Decide(3000 + WorldTransitionState.SettleMs - 1, 2900, false) == WorldTransitionState.Verdict.Hold,
|
||||
"full 5 s settle after a teleport to an adjacent landblock");
|
||||
Check(s.Decide(3000 + WorldTransitionState.SettleMs, 2900, false) == WorldTransitionState.Verdict.Drop,
|
||||
"then the stale action is dropped");
|
||||
}
|
||||
|
||||
/// <summary>Walking across a border never gates, not even for a tick.</summary>
|
||||
private static void TransitionDiagonalAndBorderWalksNeverHold()
|
||||
{
|
||||
_case = "transition walk";
|
||||
var s = Started(0xA9B4);
|
||||
long now = 2000;
|
||||
foreach (uint lb in new uint[] { 0xA9B5, 0xAAB6, 0xA9B5, 0xA8B4, 0xA9B4, 0xAAB3 })
|
||||
{
|
||||
var edges = s.Sample(now, false, false, lb);
|
||||
Check(edges == WorldTransitionState.Edge.None, $"walk into 0x{lb:X4}: no edge");
|
||||
Check(!s.InTransition(now) && s.Decide(now, now - 1, false) == WorldTransitionState.Verdict.Run, $"walk into 0x{lb:X4}: runs at once");
|
||||
now += 16;
|
||||
}
|
||||
// A cell read of 0 (pose not available for a tick) is not a jump to 0x0000 and back.
|
||||
s.Sample(now, false, false, 0);
|
||||
var back = s.Sample(now + 16, false, false, 0xAAB3);
|
||||
Check(back == WorldTransitionState.Edge.None && !s.InTransition(now + 16), "an unknown pose for one tick is not a jump");
|
||||
}
|
||||
|
||||
private static void TransitionTwoLandblockJumpHolds()
|
||||
{
|
||||
_case = "transition two-block jump";
|
||||
var sx = Started(0xA9B4);
|
||||
Check((sx.Sample(2000, false, false, 0xABB4) & WorldTransitionState.Edge.LandblockJump) != 0 && sx.InTransition(2000), "2 apart in x: a teleport");
|
||||
var sy = Started(0xA9B4);
|
||||
Check((sy.Sample(2000, false, false, 0xA9B2) & WorldTransitionState.Edge.LandblockJump) != 0 && sy.InTransition(2000), "2 apart in y: a teleport");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The drain the gate sits in (AcMainThreadQueue.Drain): a FIFO walked head to tail, each
|
||||
/// entry's verdict asked of the gate. While held, nothing runs and nothing is lost; once
|
||||
/// the transition ends the stale cast and use are dropped, and both stops run, in order.
|
||||
/// </summary>
|
||||
private static void TransitionDrainHoldThenStopsSurvive()
|
||||
{
|
||||
_case = "transition drain";
|
||||
var s = Started();
|
||||
var fifo = new List<(string What, long At, bool Teardown)>
|
||||
{
|
||||
("cast", 1500, false),
|
||||
("autorun-off", 1600, true),
|
||||
("use", 1700, false),
|
||||
("cancel-attack", 1800, true),
|
||||
};
|
||||
s.Sample(2000, true, false, 0x00AE); // dies
|
||||
|
||||
var ran = new List<string>(); var dropped = new List<string>();
|
||||
long revivedAt = 0;
|
||||
bool queuedNew = false;
|
||||
for (long now = 2000; now < 20_000; now += 16)
|
||||
{
|
||||
// Game tick sample: dead until 9 s, alive after.
|
||||
s.Sample(now, now < 9000, false, 0x00AE);
|
||||
if (now >= 9000 && revivedAt == 0) revivedAt = now;
|
||||
if (!queuedNew && revivedAt != 0 && now >= revivedAt + WorldTransitionState.SettleMs + 500)
|
||||
{
|
||||
fifo.Add(("cast-new", now, false)); // queued after the window
|
||||
queuedNew = true;
|
||||
}
|
||||
Drain(s, now, fifo, ran, dropped);
|
||||
if (revivedAt == 0 || now < revivedAt + WorldTransitionState.SettleMs)
|
||||
Check(ran.Count == 0 && dropped.Count == 0 && fifo.Count == 4, $"held: nothing runs or drops (t={now})");
|
||||
}
|
||||
Check(dropped.SequenceEqual(new[] { "cast", "use" }), $"stale cast and use dropped, got [{string.Join(",", dropped)}]");
|
||||
Check(ran.SequenceEqual(new[] { "autorun-off", "cancel-attack", "cast-new" }),
|
||||
$"stops run in queue order as a group, then new work, got [{string.Join(",", ran)}]");
|
||||
Check(fifo.Count == 0, "queue empty");
|
||||
}
|
||||
|
||||
private static void Drain(WorldTransitionState s, long now, List<(string What, long At, bool Teardown)> fifo,
|
||||
List<string> ran, List<string> dropped)
|
||||
{
|
||||
while (fifo.Count > 0)
|
||||
{
|
||||
var e = fifo[0];
|
||||
var v = s.Decide(now, e.At, e.Teardown);
|
||||
if (v == WorldTransitionState.Verdict.Hold) return;
|
||||
fifo.RemoveAt(0);
|
||||
if (v == WorldTransitionState.Verdict.Drop) dropped.Add(e.What);
|
||||
else ran.Add(e.What);
|
||||
}
|
||||
}
|
||||
|
||||
// ---- fix 7: largest free block -------------------------------------------------------
|
||||
|
||||
private static void AddressSpaceFold()
|
||||
{
|
||||
_case = "address space";
|
||||
ulong free = 0, largest = 0;
|
||||
AddressSpace.Accumulate(true, 10, ref free, ref largest);
|
||||
AddressSpace.Accumulate(false, 500, ref free, ref largest);
|
||||
AddressSpace.Accumulate(true, 40, ref free, ref largest);
|
||||
AddressSpace.Accumulate(true, 30, ref free, ref largest);
|
||||
Check(free == 80 && largest == 40, $"free 80 largest 40, got {free}/{largest}");
|
||||
var (f, l) = AddressSpace.FreeAndLargestMb();
|
||||
Check(f > 0 && l > 0 && l <= f, $"live walk of this process: free {f} MB, largest {l} MB");
|
||||
}
|
||||
}
|
||||
89
tools/EngineRobustnessTests/PumpGuardTests.cs
Normal file
89
tools/EngineRobustnessTests/PumpGuardTests.cs
Normal file
|
|
@ -0,0 +1,89 @@
|
|||
using System.Text.RegularExpressions;
|
||||
using RynthCore.Engine.Plugins;
|
||||
|
||||
namespace EngineRobustnessTests;
|
||||
|
||||
/// <summary>
|
||||
/// TickAll's step guards and the pump-dispatch line for the hang watchdog (Plugins/PumpGuards.cs),
|
||||
/// plus a source scan that TickAll catches every one of its own steps.
|
||||
/// </summary>
|
||||
internal static partial class Program
|
||||
{
|
||||
private static void RunPumpGuardTests()
|
||||
{
|
||||
StepFaultLogCadence();
|
||||
StepFaultLogText();
|
||||
PumpDispatchLine();
|
||||
TickAllGuardsEveryStep();
|
||||
}
|
||||
|
||||
private static void StepFaultLogCadence()
|
||||
{
|
||||
_case = "step fault log cadence";
|
||||
var log = new StepFaultLog((int)TickStep.Count);
|
||||
Check(log.Record((int)TickStep.Nav3DCommit, out int c1) && c1 == 1, "the first throw is logged");
|
||||
int logged = 0;
|
||||
for (int i = 2; i <= 2500; i++)
|
||||
if (log.Record((int)TickStep.Nav3DCommit, out _)) logged++;
|
||||
Check(logged == 2, $"then only every {StepFaultLog.RepeatEvery}th (1000, 2000): got {logged}");
|
||||
Check(log.CountOf((int)TickStep.Nav3DCommit) == 2500, "every throw counted");
|
||||
Check(log.Record((int)TickStep.FreezeCheck, out int other) && other == 1, "steps are counted apart");
|
||||
}
|
||||
|
||||
private static void StepFaultLogText()
|
||||
{
|
||||
_case = "step fault log text";
|
||||
string first = StepFaultLog.Describe(TickStep.DropFailedOwners, "InvalidOperationException", "Collection was modified", 1);
|
||||
Check(first.Contains("DropFailedOwners threw InvalidOperationException: Collection was modified"), "names the step and the exception");
|
||||
Check(first.Contains("the pump carries on"), "says the pump carries on");
|
||||
string later = StepFaultLog.Describe(TickStep.DropFailedOwners, "InvalidOperationException", "x", 3000);
|
||||
Check(later.Contains("3000 times"), "a repeat carries the count");
|
||||
}
|
||||
|
||||
private static void PumpDispatchLine()
|
||||
{
|
||||
_case = "pump dispatch line";
|
||||
Check(PumpDispatchInfo.Describe("RynthAi", "Tick", 1_000, 13_375) == "inside RynthAi Tick for 12375 ms",
|
||||
"names plugin, export and how long");
|
||||
Check(PumpDispatchInfo.Describe(null, "Tick", 1_000, 13_375) == null, "no plugin call in progress: nothing");
|
||||
Check(PumpDispatchInfo.Describe("RynthAi", "Tick", 0, 13_375) == null, "no start time: nothing");
|
||||
Check(PumpDispatchInfo.Describe("RynthAi", "Tick", 13_000, 13_375) == null, "a call under a second old is normal: nothing");
|
||||
Check(PumpDispatchInfo.Describe("RynthNav", null, 1_000, 3_000) == "inside RynthNav call for 2000 ms", "unnamed export");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// TickAll may let nothing of its own escape: each step is wrapped and reported through
|
||||
/// TickStepFailed, every TickStep is used, and the plugin Tick is dispatched as "Tick".
|
||||
/// </summary>
|
||||
private static void TickAllGuardsEveryStep()
|
||||
{
|
||||
_case = "TickAll guards";
|
||||
string? plugins = FindRepoDir(Path.Combine("src", "RynthCore.Engine", "Plugins"));
|
||||
Check(plugins != null, "found src\\RynthCore.Engine\\Plugins by walking up");
|
||||
if (plugins == null) return;
|
||||
string src = File.ReadAllText(Path.Combine(plugins, "PluginManager.cs")).Replace("\r\n", "\n");
|
||||
int start = src.IndexOf("public static void TickAll()", StringComparison.Ordinal);
|
||||
Check(start >= 0, "TickAll found");
|
||||
if (start < 0) return;
|
||||
int end = src.IndexOf("\n }\n", start, StringComparison.Ordinal);
|
||||
string body = end > start ? src[start..end] : src[start..];
|
||||
|
||||
foreach (TickStep step in Enum.GetValues<TickStep>())
|
||||
{
|
||||
if (step == TickStep.Count) continue;
|
||||
Check(body.Contains($"TickStepFailed(TickStep.{step}, ex)"), $"{step} is caught and reported");
|
||||
}
|
||||
Check(body.Contains("EnterDispatch(plugin, \"Tick\")"), "the plugin Tick is dispatched as \"Tick\" (the hang watchdog's line)");
|
||||
Check(!Regex.IsMatch(body, @"catch\s*\{\s*\}"), "no silent catch {} left in TickAll");
|
||||
// The engine calls outside the plugin loop each sit inside a try.
|
||||
foreach (string call in new[] { "MainThreadFreeze.ShouldPausePluginTick()", "D3D9.Nav3DRenderer.ClearFrame()",
|
||||
"ScriptWindowRegistry.DropFailedOwners()", "D3D9.Nav3DRenderer.CommitFrame()" })
|
||||
{
|
||||
int at = body.IndexOf(call, StringComparison.Ordinal);
|
||||
string line = at < 0 ? "" : body[body.LastIndexOf('\n', at)..at];
|
||||
Check(at >= 0 && line.Contains("try {"), $"{call} is called inside try {{ }}");
|
||||
}
|
||||
string watchdog = File.ReadAllText(Path.Combine(Path.GetDirectoryName(plugins)!, "MainThreadHangWatchdog.cs"));
|
||||
Check(watchdog.Contains("PluginManager.DescribePumpDispatch()"), "the hang report names the plugin call the pump is inside");
|
||||
}
|
||||
}
|
||||
470
tools/EngineRobustnessTests/RingAndGateTests.cs
Normal file
470
tools/EngineRobustnessTests/RingAndGateTests.cs
Normal file
|
|
@ -0,0 +1,470 @@
|
|||
using System.Text.RegularExpressions;
|
||||
using RynthCore.Engine;
|
||||
using RynthCore.Engine.Compatibility;
|
||||
using RynthCore.Install;
|
||||
|
||||
namespace EngineRobustnessTests;
|
||||
|
||||
/// <summary>Checks for the action ring, the mutator gate, appraisal retention, the dump rules and the cast slot.</summary>
|
||||
internal static partial class Program
|
||||
{
|
||||
private static void RunRingAndGateTests()
|
||||
{
|
||||
RingTakesAStopWhenFullOfStarts();
|
||||
RingRefusesStartsDuringATransition();
|
||||
RingStopRunsFirstAfterTheWindow();
|
||||
CastStopFindsAnOutOfOrderStop();
|
||||
|
||||
GateTruthTable();
|
||||
GateCallSitesAllUseTheSameShape();
|
||||
|
||||
RequestIdNeverMergesIntoAHeldEntry();
|
||||
|
||||
ReleasedDataKeptSoRecreateSkips();
|
||||
ReleasedDataExpiresAndServerDeleteEvicts();
|
||||
|
||||
TeleportMessageStartsTheWindow();
|
||||
|
||||
OutOfMemoryBoxMatchesOnlyAcsBox();
|
||||
LauncherHoldsTheKillDuringADump();
|
||||
|
||||
// The cast slot, the dump hold cap and the crash exits
|
||||
CastRefusedDuringATransition();
|
||||
RingPeekAtWalksWithoutRemoving();
|
||||
EnqueueCastPassesTheTransitionState();
|
||||
LauncherDumpHoldIsCapped();
|
||||
CrashExitExcludesExitMinusOne();
|
||||
CrashExitPathsFlushTheCrashLog();
|
||||
}
|
||||
|
||||
// ---- the action ring (the real ActionRing, the one AcMainThreadQueue uses) --------
|
||||
|
||||
private readonly record struct Act(string What, long At, bool Teardown);
|
||||
|
||||
private static void RingTakesAStopWhenFullOfStarts()
|
||||
{
|
||||
_case = "ring reserve";
|
||||
var ring = new ActionRing<Act>(256, 32);
|
||||
int queued = 0, full = 0;
|
||||
for (int i = 0; i < 300; i++)
|
||||
{
|
||||
var r = ring.TryEnqueue(new Act("start", 1000, false), teardown: false, inTransition: false);
|
||||
if (r == ActionRing<Act>.Admit.Queued) queued++;
|
||||
else if (r == ActionRing<Act>.Admit.Full) full++;
|
||||
}
|
||||
Check(queued == 224 && full == 76, $"300 starts: 224 taken, the rest refused at the reserve (got {queued}/{full})");
|
||||
Check(ring.TryEnqueue(new Act("stop", 1001, true), teardown: true, inTransition: false) == ActionRing<Act>.Admit.Queued,
|
||||
"a stop is still taken");
|
||||
for (int i = 0; i < 31; i++)
|
||||
ring.TryEnqueue(new Act("cancel", 1002, true), teardown: true, inTransition: false);
|
||||
Check(ring.Count == 256, $"the reserve fills only with teardown (count {ring.Count})");
|
||||
Check(ring.TryEnqueue(new Act("stop", 1003, true), teardown: true, inTransition: false) == ActionRing<Act>.Admit.Full,
|
||||
"a completely full ring refuses even a stop");
|
||||
}
|
||||
|
||||
private static void RingRefusesStartsDuringATransition()
|
||||
{
|
||||
_case = "ring transition";
|
||||
var ring = new ActionRing<Act>(256, 32);
|
||||
int rejected = 0;
|
||||
for (int i = 0; i < 300; i++)
|
||||
if (ring.TryEnqueue(new Act("start", 2000, false), teardown: false, inTransition: true) == ActionRing<Act>.Admit.RejectedTransition)
|
||||
rejected++;
|
||||
Check(rejected == 300 && ring.Count == 0, $"300 starts during a hold are refused, none stored (rejected {rejected}, count {ring.Count})");
|
||||
Check(ring.TryEnqueue(new Act("stop", 2001, true), teardown: true, inTransition: true) == ActionRing<Act>.Admit.Queued,
|
||||
"a stop during the hold is taken");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The flood scenario against the real ring: a bot floods starts before the transition is
|
||||
/// seen (the ring fills to the reserve), the player dies, 300 more starts arrive during the
|
||||
/// hold, then a stop. Nothing runs during the hold; after it the stale starts are dropped and
|
||||
/// the stops are the first things to run.
|
||||
/// </summary>
|
||||
private static void RingStopRunsFirstAfterTheWindow()
|
||||
{
|
||||
_case = "ring drain";
|
||||
var ring = new ActionRing<Act>(256, 32);
|
||||
var s = new WorldTransitionState();
|
||||
s.Sample(900, false, false, 0x00AE);
|
||||
for (int i = 0; i < 300; i++)
|
||||
ring.TryEnqueue(new Act("start", 1000, false), false, s.InTransition(1000));
|
||||
s.Sample(1500, true, false, 0x00AE); // dies
|
||||
for (int i = 0; i < 300; i++)
|
||||
ring.TryEnqueue(new Act("start-held", 2000, false), false, s.InTransition(2000));
|
||||
var stopAdmit = ring.TryEnqueue(new Act("stop", 2500, true), true, s.InTransition(2500));
|
||||
Check(stopAdmit == ActionRing<Act>.Admit.Queued, $"the stop is accepted ({stopAdmit})");
|
||||
|
||||
var ran = new List<string>();
|
||||
int dropped = 0;
|
||||
bool heldClean = true;
|
||||
for (long now = 1500; now < 20_000; now += 16)
|
||||
{
|
||||
s.Sample(now, now < 9000, false, 0x00AE);
|
||||
int before = ring.Count;
|
||||
if (s.CheckHolding(now)) { heldClean &= ring.Count == before; continue; } // Drain's early return
|
||||
while (ring.TryDequeue(out Act e))
|
||||
{
|
||||
var v = s.Decide(now, e.At, e.Teardown);
|
||||
if (v == WorldTransitionState.Verdict.Drop) dropped++;
|
||||
else ran.Add(e.What);
|
||||
}
|
||||
}
|
||||
Check(heldClean, "nothing leaves the ring while held");
|
||||
Check(ran.Count > 0 && ran[0] == "stop", $"the stop runs first after the window (ran [{string.Join(",", ran.Take(3))}])");
|
||||
Check(ran.Count == 1 && dropped == 224, $"the 224 stale starts are dropped, nothing else runs (ran {ran.Count}, dropped {dropped})");
|
||||
}
|
||||
|
||||
// ---- the cast drain's stop check (the real CastStopRules over the real ActionRing) ------
|
||||
|
||||
/// <summary>
|
||||
/// A stop queued at or before the cast is found wherever it sits in the ring, including
|
||||
/// behind an entry stamped after the cast (two producers can land out of time order).
|
||||
/// </summary>
|
||||
private static void CastStopFindsAnOutOfOrderStop()
|
||||
{
|
||||
_case = "cast stop check";
|
||||
static bool Any(ActionRing<Act> r, long at) =>
|
||||
CastStopRules.AnyStopAtOrBefore(r, at, static e => e.At, static e => e.Teardown);
|
||||
|
||||
var empty = new ActionRing<Act>(8, 2);
|
||||
Check(!Any(empty, 1000), "an empty ring has no stop");
|
||||
|
||||
var outOfOrder = new ActionRing<Act>(8, 2);
|
||||
outOfOrder.TryEnqueue(new Act("start", 1200, false), false, false); // newer than the cast
|
||||
outOfOrder.TryEnqueue(new Act("stop", 900, true), true, false); // older, queued behind it
|
||||
Check(Any(outOfOrder, 1000), "a stop older than the cast, behind a newer entry, is found");
|
||||
|
||||
var onlyNewer = new ActionRing<Act>(8, 2);
|
||||
onlyNewer.TryEnqueue(new Act("start", 500, false), false, false);
|
||||
onlyNewer.TryEnqueue(new Act("stop", 1500, true), true, false);
|
||||
Check(!Any(onlyNewer, 1000), "a stop queued after the cast does not count");
|
||||
|
||||
var sameTime = new ActionRing<Act>(8, 2);
|
||||
sameTime.TryEnqueue(new Act("stop", 1000, true), true, false);
|
||||
Check(Any(sameTime, 1000), "a stop queued at the cast's own time counts");
|
||||
|
||||
var noStop = new ActionRing<Act>(8, 2);
|
||||
noStop.TryEnqueue(new Act("start", 100, false), false, false);
|
||||
noStop.TryEnqueue(new Act("start", 200, false), false, false);
|
||||
Check(!Any(noStop, 1000), "older entries that are not stops do not count");
|
||||
Check(noStop.Count == 2 && outOfOrder.Count == 2, "the check removes nothing");
|
||||
}
|
||||
|
||||
// ---- the mutator gate --------------------------------------------------------
|
||||
|
||||
private static void GateTruthTable()
|
||||
{
|
||||
_case = "mutator gate";
|
||||
int asked = 0;
|
||||
Func<bool> holding = () => { asked++; return true; };
|
||||
Func<bool> clear = () => { asked++; return false; };
|
||||
Check(MutatorGate.MustQueue(false, false, false, clear), "off the main thread: queue");
|
||||
Check(MutatorGate.MustQueue(false, true, true, clear), "off the main thread, even teardown in a drain: queue");
|
||||
Check(!MutatorGate.MustQueue(true, false, false, clear), "main thread, no transition: call now");
|
||||
Check(MutatorGate.MustQueue(true, false, false, holding), "main thread in a transition (render-thread host action): queue");
|
||||
Check(!MutatorGate.MustQueue(true, true, false, holding), "main thread in a transition, a stop: call now");
|
||||
asked = 0;
|
||||
Check(!MutatorGate.MustQueue(true, false, true, holding) && asked == 0, "called by a drain: call now, without asking the transition state");
|
||||
asked = 0;
|
||||
MutatorGate.MustQueue(false, false, false, holding);
|
||||
Check(asked == 0, "off the main thread the (main-thread-only) transition state is never asked");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Every AC-mutating helper opens with the same gate: no helper may still decide with the old
|
||||
/// bare IsOnMainThread() check before an AcMainThreadQueue.Enqueue*, and each stop/cancel
|
||||
/// passes teardown: true while every other passes false (or !enabled for the two toggles).
|
||||
/// </summary>
|
||||
private static void GateCallSitesAllUseTheSameShape()
|
||||
{
|
||||
_case = "gate call sites";
|
||||
string? compat = FindRepoDir(Path.Combine("src", "RynthCore.Engine", "Compatibility"));
|
||||
Check(compat != null, "found src\\RynthCore.Engine\\Compatibility by walking up");
|
||||
if (compat == null) return;
|
||||
string[] files = { "ClientCombatHooks.cs", "CommandInterpreterHooks.cs", "ClientHelperHooks.cs", "CombatActionHooks.cs",
|
||||
"MovementActionHooks.cs", "PlayerPhysicsHooks.cs", "PlayerTrade.cs", "PlayerTraining.cs",
|
||||
"DeleteObjectHooks.cs" };
|
||||
var enqueue = new Regex(@"AcMainThreadQueue\.(Enqueue\w+)\(");
|
||||
var gate = new Regex(@"AcMainThreadQueue\.MustQueue\(teardown: (true|false|!enabled)\)");
|
||||
string[] teardownTrue = { "EnqueueStopCompletely", "EnqueueStopMovement", "EnqueueCancelAttack", "EnqueueCloseContainer" };
|
||||
string[] toggles = { "EnqueueSetAutoRun", "EnqueueSetMotion" };
|
||||
int sites = 0, bad = 0;
|
||||
foreach (string f in files)
|
||||
{
|
||||
string[] lines = File.ReadAllLines(Path.Combine(compat, f));
|
||||
for (int i = 0; i < lines.Length; i++)
|
||||
{
|
||||
Match m = enqueue.Match(lines[i]);
|
||||
if (!m.Success) continue;
|
||||
string name = m.Groups[1].Value;
|
||||
if (name is "EnqueueWriteToChat" or "EnqueueChatCommand") continue;
|
||||
sites++;
|
||||
// The gate line is the nearest "if (" line above the enqueue (within 3 lines).
|
||||
string? gateLine = null;
|
||||
for (int j = i; j >= Math.Max(0, i - 3); j--)
|
||||
if (lines[j].TrimStart().StartsWith("if (", StringComparison.Ordinal)) { gateLine = lines[j]; break; }
|
||||
Match g = gateLine == null ? Match.Empty : gate.Match(gateLine);
|
||||
string want = teardownTrue.Contains(name) ? "true" : toggles.Contains(name) ? "!enabled" : "false";
|
||||
if (!g.Success || g.Groups[1].Value != want || gateLine!.Contains("IsOnMainThread"))
|
||||
{
|
||||
bad++;
|
||||
Console.WriteLine($"[gate] {f}:{i + 1} {name}: gate line '{gateLine?.Trim()}' (want teardown: {want})");
|
||||
}
|
||||
}
|
||||
}
|
||||
// 45 in PR #8, + SalvageDirect (v82, ClientHelperHooks) + RemoveClientObject (v83, DeleteObjectHooks).
|
||||
Check(sites == 47, $"47 gated mutator call sites found (got {sites})");
|
||||
Check(bad == 0, $"every one opens with AcMainThreadQueue.MustQueue(teardown: ...) and the right teardown value ({bad} wrong)");
|
||||
}
|
||||
|
||||
private static string? FindRepoDir(string relative)
|
||||
{
|
||||
string? dir = AppContext.BaseDirectory;
|
||||
while (dir != null)
|
||||
{
|
||||
string candidate = Path.Combine(dir, relative);
|
||||
if (Directory.Exists(candidate)) return candidate;
|
||||
dir = Path.GetDirectoryName(dir);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
// ---- no merge into an entry a transition will drop -------------------------------
|
||||
|
||||
private static void RequestIdNeverMergesIntoAHeldEntry()
|
||||
{
|
||||
_case = "requestid merge floor";
|
||||
var q = new PendingIdQueue(8);
|
||||
q.Enqueue(42, 1000, 1, 7_500);
|
||||
// A transition held the drains up to 1500: the entry from 1000 will be dropped.
|
||||
Check(q.Enqueue(42, 2000, 1, 7_500, mergeOnlyAfterMs: 1500) == PendingIdQueue.Result.Queued,
|
||||
"a request after the window does not merge into the doomed entry");
|
||||
Check(q.Count == 2, "so it survives the drop");
|
||||
Check(q.Enqueue(42, 2100, 1, 7_500, mergeOnlyAfterMs: 1500) == PendingIdQueue.Result.Merged,
|
||||
"it merges into the new one");
|
||||
var r = new PendingIdQueue(8);
|
||||
r.Enqueue(43, 1000, 1, 7_500);
|
||||
Check(r.Enqueue(43, 2000, 1, 7_500, mergeOnlyAfterMs: 0) == PendingIdQueue.Result.Merged, "no transition: merges as before");
|
||||
}
|
||||
|
||||
// ---- identify data kept across a client release ---------------------------------
|
||||
|
||||
/// <summary>
|
||||
/// Wired as the engine wires them: AppraisalHooks' cache (here a set) keeps an object while
|
||||
/// ReleasedObjectRetention says so; AutoIdEligibility decides the re-create.
|
||||
/// </summary>
|
||||
private static void ReleasedDataKeptSoRecreateSkips()
|
||||
{
|
||||
_case = "release keeps data";
|
||||
var cache = new HashSet<uint>();
|
||||
var keep = new ReleasedObjectRetention();
|
||||
var elig = new AutoIdEligibility();
|
||||
long t = 1000;
|
||||
Check(elig.OnCreate(50, t, cache.Contains(50)) == AutoIdEligibility.CreateDecision.Appraise, "first create: appraised");
|
||||
elig.OnSent(50, t + 100);
|
||||
cache.Add(50); // the identify arrived
|
||||
// Client release (BeingDeleted): AppraisalHooks.OnClientRelease
|
||||
if (!keep.OnRelease(50, t + 60_000)) cache.Remove(50);
|
||||
elig.OnClientRelease(50);
|
||||
// Re-created 5 minutes later: AutoIdService.Enqueue (MarkLive, then the decision)
|
||||
keep.Forget(50);
|
||||
var d = elig.OnCreate(50, t + 5 * 60_000, cache.Contains(50));
|
||||
Check(d == AutoIdEligibility.CreateDecision.SkipRecent, $"re-created within 10 min with the data kept: skipped ({d})");
|
||||
Check(elig.SkippedRecentTotal == 1, $"SkippedRecentCount moves (got {elig.SkippedRecentTotal})");
|
||||
}
|
||||
|
||||
private static void ReleasedDataExpiresAndServerDeleteEvicts()
|
||||
{
|
||||
_case = "release expiry";
|
||||
var keep = new ReleasedObjectRetention(10 * 60_000, 4);
|
||||
var expired = new List<uint>();
|
||||
keep.OnRelease(1, 1000);
|
||||
keep.OnRelease(2, 2000);
|
||||
Check(keep.Expire(1000 + 10 * 60_000 - 1, expired) == 0, "kept inside the 10 minutes");
|
||||
Check(keep.Expire(2000 + 10 * 60_000, expired) == 2 && expired.SequenceEqual(new uint[] { 1, 2 }), "both dropped once past it");
|
||||
Check(keep.Count == 0, "and no longer tracked");
|
||||
for (uint i = 10; i < 14; i++) keep.OnRelease(i, 5000);
|
||||
Check(!keep.OnRelease(99, 5000), "at the bound a release is not kept (the caller evicts it at once)");
|
||||
keep.Forget(10);
|
||||
Check(keep.OnRelease(99, 5000), "room again once one is forgotten (re-created or server-deleted)");
|
||||
}
|
||||
|
||||
// ---- 0xF751: the teleport message as its own signal ----------------------------------
|
||||
|
||||
private static void TeleportMessageStartsTheWindow()
|
||||
{
|
||||
_case = "teleport message";
|
||||
var s = new WorldTransitionState();
|
||||
s.Sample(1000, false, false, 0xA9B4);
|
||||
Check(!s.InTransition(2000), "no transition before the message");
|
||||
Check(s.OnTeleportMessage(2000), "PlayerTeleport received: the window starts");
|
||||
// No portal flag, no landblock change, alive: only the message.
|
||||
s.Sample(2016, false, false, 0xA9B4);
|
||||
Check(s.InTransition(2000 + WorldTransitionState.SettleMs - 1), "held for the full settle on the message alone");
|
||||
Check(s.Decide(3000, 2500, false) == WorldTransitionState.Verdict.Hold, "queued work held");
|
||||
Check(!s.InTransition(2000 + WorldTransitionState.SettleMs), "window ends 5 s after it");
|
||||
Check(s.Decide(2000 + WorldTransitionState.SettleMs, 2500, false) == WorldTransitionState.Verdict.Drop, "then stale work is dropped");
|
||||
Check(!s.OnTeleportMessage(1500), "an older message never shortens a running window");
|
||||
}
|
||||
|
||||
// ---- the OOM dump trigger ------------------------------------------------------
|
||||
|
||||
private static void OutOfMemoryBoxMatchesOnlyAcsBox()
|
||||
{
|
||||
_case = "oom box rule";
|
||||
// The real text, from a real log line.
|
||||
const string real = "OUT OF MEMORY: Failed to allocate -778718788 bytes.";
|
||||
Check(OutOfMemoryBoxRule.IsOutOfMemoryBox(real, onMainThread: true), "AC's box on its main thread: dump");
|
||||
Check(!OutOfMemoryBoxRule.IsOutOfMemoryBox(real, onMainThread: false), "the same text off the main thread: no dump");
|
||||
Check(!OutOfMemoryBoxRule.IsOutOfMemoryBox("Plugin X: OUT OF MEMORY: Failed to allocate 4 bytes.", true), "prefix not at the start: no dump");
|
||||
Check(!OutOfMemoryBoxRule.IsOutOfMemoryBox("out of memory: failed to allocate 4 bytes.", true), "other case: no dump (ordinal)");
|
||||
Check(!OutOfMemoryBoxRule.IsOutOfMemoryBox("OUT OF MEMORY", true), "the bare words: no dump");
|
||||
Check(!OutOfMemoryBoxRule.IsOutOfMemoryBox(null, true), "no text: no dump");
|
||||
}
|
||||
|
||||
// ---- the launcher holds its kill while a dump is written ---------------------------
|
||||
|
||||
private static void LauncherHoldsTheKillDuringADump()
|
||||
{
|
||||
_case = "dump in progress";
|
||||
var now = new DateTime(2026, 10, 10, 22, 18, 30, DateTimeKind.Utc);
|
||||
string started = $"[18:18:16] {DumpInProgressRule.MarkerStarted} pid=123 - ...\n";
|
||||
string ended = $"[18:20:01] {DumpInProgressRule.MarkerEnded} pid=123.\n";
|
||||
Check(DumpInProgressRule.IsDumping("hb #1\n" + started, now.AddMinutes(-3), null, now), "marker 3 min old, no end: hold the kill");
|
||||
Check(!DumpInProgressRule.IsDumping("hb #1\n" + started, now.AddMinutes(-11), null, now), "marker over 10 min old: a client that died mid-dump is killed");
|
||||
Check(!DumpInProgressRule.IsDumping(started + ended, now.AddMinutes(-3), null, now), "dump ended: no hold");
|
||||
Check(DumpInProgressRule.IsDumping(started + ended + started, now.AddMinutes(-1), null, now), "the LAST marker decides");
|
||||
Check(DumpInProgressRule.IsDumping("hb #1\n", now.AddMinutes(-5), now.AddSeconds(-10), now), "no marker, but the dump file was written 10 s ago: hold");
|
||||
Check(!DumpInProgressRule.IsDumping("hb #1\n", now.AddMinutes(-5), now.AddMinutes(-2), now), "a dump file quiet for 2 min: no hold");
|
||||
Check(!DumpInProgressRule.IsDumping(null, now, null, now), "nothing at all: no hold");
|
||||
}
|
||||
|
||||
// ---- the cast slot refuses during a transition (the real CastSlot) -------------
|
||||
|
||||
private static void CastRefusedDuringATransition()
|
||||
{
|
||||
_case = "cast slot transition";
|
||||
var slot = new CastSlot();
|
||||
Check(slot.TryEnqueue(0x50000001, 1234, 1000, inTransition: true) == CastSlot.Admit.RejectedTransition,
|
||||
"an empty slot refuses a cast during a transition");
|
||||
Check(slot.Pending == 0 && slot.TargetId == 0 && slot.SpellId == 0 && slot.QueuedAt == 0,
|
||||
"and stays untouched");
|
||||
|
||||
Check(slot.TryEnqueue(0x50000002, 99, 2000, inTransition: false) == CastSlot.Admit.Queued, "outside one, a cast is queued");
|
||||
Check(slot.TryEnqueue(0x50000003, 77, 2500, inTransition: true) == CastSlot.Admit.RejectedTransition,
|
||||
"a transition refuses even with a cast pending (counted as a transition refusal, not busy)");
|
||||
Check(slot.Pending == 1 && slot.TargetId == 0x50000002 && slot.SpellId == 99 && slot.QueuedAt == 2000,
|
||||
"the pending cast is unchanged");
|
||||
Check(slot.TryEnqueue(0x50000004, 55, 2600, inTransition: false) == CastSlot.Admit.Busy, "busy outside a transition");
|
||||
slot.Pending = 0;
|
||||
Check(slot.TryEnqueue(0x50000005, 66, 9000, inTransition: false) == CastSlot.Admit.Queued
|
||||
&& slot.SpellId == 66 && slot.QueuedAt == 9000, "after the transition, casts queue again");
|
||||
|
||||
// The drain's once-per-cast stop-wait note belongs to the cast: a new cast clears it, a
|
||||
// refused one leaves the pending cast's note alone.
|
||||
slot.StopWaitNoted = true;
|
||||
Check(slot.TryEnqueue(0x50000006, 67, 9100, inTransition: false) == CastSlot.Admit.Busy && slot.StopWaitNoted,
|
||||
"a busy refusal keeps the pending cast's stop-wait note");
|
||||
slot.Pending = 0;
|
||||
Check(slot.TryEnqueue(0x50000007, 68, 9200, inTransition: false) == CastSlot.Admit.Queued && !slot.StopWaitNoted,
|
||||
"a newly queued cast starts with no stop-wait note");
|
||||
}
|
||||
|
||||
// ---- The cast drain's walk of the ring (ActionRing.TryPeekAt) --------------------------
|
||||
|
||||
private static void RingPeekAtWalksWithoutRemoving()
|
||||
{
|
||||
_case = "ring peek-at";
|
||||
var ring = new ActionRing<Act>(8, 2);
|
||||
Check(!ring.TryPeekAt(0, out _), "an empty ring has nothing at 0");
|
||||
// Wrap the ring once so the walk crosses the end of the storage.
|
||||
for (int i = 0; i < 5; i++) ring.TryEnqueue(new Act("old" + i, i, false), false, false);
|
||||
for (int i = 0; i < 5; i++) ring.TryDequeue(out _);
|
||||
for (int i = 0; i < 6; i++) ring.TryEnqueue(new Act("e" + i, 100 + i, i == 4), i == 4, false);
|
||||
var seen = new List<string>();
|
||||
for (int i = 0; ring.TryPeekAt(i, out Act e); i++) seen.Add(e.What);
|
||||
Check(string.Join(",", seen) == "e0,e1,e2,e3,e4,e5", $"oldest first across the wrap, got [{string.Join(",", seen)}]");
|
||||
Check(ring.Count == 6, $"nothing removed (count {ring.Count})");
|
||||
Check(!ring.TryPeekAt(6, out _) && !ring.TryPeekAt(-1, out _), "out of range is false");
|
||||
Check(ring.TryDequeue(out Act head) && head.What == "e0" && ring.TryPeekAt(0, out Act next) && next.What == "e1",
|
||||
"after a dequeue, offset 0 is the new oldest");
|
||||
}
|
||||
|
||||
private static void EnqueueCastPassesTheTransitionState()
|
||||
{
|
||||
_case = "EnqueueCast wiring";
|
||||
string? compat = FindRepoDir(Path.Combine("src", "RynthCore.Engine", "Compatibility"));
|
||||
Check(compat != null, "found src\\RynthCore.Engine\\Compatibility by walking up");
|
||||
if (compat == null) return;
|
||||
string src = File.ReadAllText(Path.Combine(compat, "AcMainThreadQueue.cs"));
|
||||
int start = src.IndexOf("public static bool EnqueueCast(", StringComparison.Ordinal);
|
||||
int end = start < 0 ? -1 : src.IndexOf("\n }", start, StringComparison.Ordinal);
|
||||
string body = start < 0 || end < 0 ? "" : src.Substring(start, end - start);
|
||||
Check(body.Contains("_cast.TryEnqueue(targetId, spellId, NowMs, PlayerLifecycleLog.InWorldTransition)", StringComparison.Ordinal),
|
||||
"EnqueueCast hands CastSlot the live transition state");
|
||||
Check(Regex.IsMatch(body, @"RejectedTransition\)\s*Interlocked\.Increment\(ref _transitionRejected\)"),
|
||||
"and counts a refusal in TransitionRejectedCount (the heartbeat's qrej)");
|
||||
Check(!Regex.IsMatch(src, @"_cast\.(TargetId|SpellId|QueuedAt)\s*=[^=]"),
|
||||
"nothing else writes the slot's cast fields");
|
||||
}
|
||||
|
||||
// ---- the launcher's dump hold is capped per client --------------------------------
|
||||
|
||||
private static void LauncherDumpHoldIsCapped()
|
||||
{
|
||||
_case = "dump hold cap";
|
||||
var now = new DateTime(2026, 10, 10, 22, 18, 30, DateTimeKind.Utc);
|
||||
string open = $"hb #1\n[18:00:00] {DumpInProgressRule.MarkerStarted} pid=123 - ...\nhb #2\n";
|
||||
DateTime freshLog = now.AddSeconds(-5);
|
||||
Check(DumpInProgressRule.Decide(open, freshLog, null, null, now) == DumpInProgressRule.Hold.Holding,
|
||||
"an open marker, first seen now: hold");
|
||||
Check(DumpInProgressRule.Decide(open, freshLog, null, now.AddMinutes(-5), now) == DumpInProgressRule.Hold.Holding,
|
||||
"held 5 min: still holding");
|
||||
Check(DumpInProgressRule.Decide(open, freshLog, null, now.AddMinutes(-16), now) == DumpInProgressRule.Hold.Expired,
|
||||
"fresh log, marker held over 15 min: the kill checks run");
|
||||
Check(DumpInProgressRule.Decide("hb #1\n", freshLog, now.AddSeconds(-3), now.AddMinutes(-16), now) == DumpInProgressRule.Hold.Expired,
|
||||
"a dump file still being written does not extend the cap either");
|
||||
Check(DumpInProgressRule.Decide(open, freshLog, null, DateTime.MinValue, now) == DumpInProgressRule.Hold.Expired,
|
||||
"the launcher's 'expired, logged' mark stays expired");
|
||||
Check(DumpInProgressRule.Decide("hb #1\n", freshLog, null, now.AddMinutes(-16), now) == DumpInProgressRule.Hold.None,
|
||||
"no sign of a dump: None (the launcher forgets the pid)");
|
||||
}
|
||||
|
||||
// ---- which exit codes are crash exits ---------------------------------------------
|
||||
|
||||
private static void CrashExitExcludesExitMinusOne()
|
||||
{
|
||||
_case = "crash exit rule";
|
||||
Check(CrashExitRule.IsCrashExit(0xC0000005u), "0xC0000005 access violation: crash");
|
||||
Check(CrashExitRule.IsCrashExit(0xC0000409u), "0xC0000409 stack buffer overrun: crash");
|
||||
Check(CrashExitRule.IsCrashExit(0xC0000374u), "0xC0000374 heap corruption: crash");
|
||||
Check(CrashExitRule.IsCrashExit(0xC00000FDu), "0xC00000FD stack overflow: crash");
|
||||
Check(CrashExitRule.IsCrashExit(0xE0434352u), "0xE0434352 CLR unhandled exception: crash (as before)");
|
||||
Check(!CrashExitRule.IsCrashExit(0xFFFFFFFFu), "ExitProcess(-1): not a crash");
|
||||
Check(!CrashExitRule.IsCrashExit(0u), "0: not a crash");
|
||||
Check(!CrashExitRule.IsCrashExit(1u), "1: not a crash");
|
||||
Check(!CrashExitRule.IsCrashExit(0x80000003u), "0x80000003 (warning severity): not a crash");
|
||||
Check(!CrashExitRule.IsCrashExit(0x40010004u), "0x40010004 (informational): not a crash");
|
||||
}
|
||||
|
||||
private static void CrashExitPathsFlushTheCrashLog()
|
||||
{
|
||||
_case = "crash exit flush";
|
||||
string? compat = FindRepoDir(Path.Combine("src", "RynthCore.Engine", "Compatibility"));
|
||||
Check(compat != null, "found src\\RynthCore.Engine\\Compatibility by walking up");
|
||||
if (compat == null) return;
|
||||
string src = File.ReadAllText(Path.Combine(compat, "ProcessExitHooks.cs"));
|
||||
Check(src.Contains("private static bool IsCrashExit(uint code) => CrashExitRule.IsCrashExit(code);", StringComparison.Ordinal),
|
||||
"ProcessExitHooks uses CrashExitRule");
|
||||
foreach (string detour in new[] { "ExitProcessDetour", "TerminateProcessDetour", "RtlExitUserProcessDetour", "NtTerminateProcessDetour" })
|
||||
{
|
||||
int start = src.IndexOf($"private static {(detour.Contains("Terminate") ? (detour.StartsWith("Nt") ? "uint" : "bool") : "void")} {detour}(", StringComparison.Ordinal);
|
||||
int end = start < 0 ? -1 : src.IndexOf("\n }", start, StringComparison.Ordinal);
|
||||
string body = start < 0 || end < 0 ? "" : src.Substring(start, end - start);
|
||||
int flush = body.IndexOf("SehTrampoline.FlushCrashLog(", StringComparison.Ordinal);
|
||||
int orig = body.IndexOf("Original!(", StringComparison.Ordinal);
|
||||
Check(flush >= 0 && orig > flush, $"{detour}: a crash exit flushes the crash log before the original");
|
||||
}
|
||||
}
|
||||
}
|
||||
Loading…
Reference in a new issue