using System.Text.RegularExpressions; using RynthCore.Engine; using RynthCore.Engine.Compatibility; using RynthCore.Install; namespace EngineRobustnessTests; /// Checks for the action ring, the mutator gate, appraisal retention, the dump rules and the cast slot. internal static partial class Program { private static void RunRingAndGateTests() { RingTakesAStopWhenFullOfStarts(); RingRefusesStartsDuringATransition(); RingStopRunsFirstAfterTheWindow(); CastStopFindsAnOutOfOrderStop(); GateTruthTable(); GateCallSitesAllUseTheSameShape(); RequestIdNeverMergesIntoAHeldEntry(); ReleasedDataKeptSoRecreateSkips(); ReleasedDataExpiresAndServerDeleteEvicts(); TeleportMessageStartsTheWindow(); OutOfMemoryBoxMatchesOnlyAcsBox(); LauncherHoldsTheKillDuringADump(); } // ---- 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(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.Admit.Queued) queued++; else if (r == ActionRing.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.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.Admit.Full, "a completely full ring refuses even a stop"); } private static void RingRefusesStartsDuringATransition() { _case = "ring transition"; var ring = new ActionRing(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.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.Admit.Queued, "a stop during the hold is taken"); } /// /// 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. /// private static void RingStopRunsFirstAfterTheWindow() { _case = "ring drain"; var ring = new ActionRing(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.Admit.Queued, $"the stop is accepted ({stopAdmit})"); var ran = new List(); 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) ------ /// /// 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). /// private static void CastStopFindsAnOutOfOrderStop() { _case = "cast stop check"; static bool Any(ActionRing r, long at) => CastStopRules.AnyStopAtOrBefore(r, at, static e => e.At, static e => e.Teardown); var empty = new ActionRing(8, 2); Check(!Any(empty, 1000), "an empty ring has no stop"); var outOfOrder = new ActionRing(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(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(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(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 holding = () => { asked++; return true; }; Func 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"); } /// /// 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). /// 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" }; 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})"); } } } Check(sites == 45, $"45 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 --------------------------------- /// /// Wired as the engine wires them: AppraisalHooks' cache (here a set) keeps an object while /// ReleasedObjectRetention says so; AutoIdEligibility decides the re-create. /// private static void ReleasedDataKeptSoRecreateSkips() { _case = "release keeps data"; var cache = new HashSet(); 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(); 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"); } }