From 636f5d307a333d848d95d0da9a30e36541142765 Mon Sep 17 00:00:00 2001 From: Daniel Wallace Date: Sat, 10 Oct 2026 21:53:42 -0700 Subject: [PATCH] Engine robustness re-review follow-ups: crash-log flush ring, cast refusal, dump hold cap - The native crash logger keeps the last 16 first-chance records in a static ring (pushed in the VEH: no I/O, no allocation, no loader call). A flush writes the ones not yet written, oldest first, each record once. Flushed from the last-chance filter and, through the new export RC_FlushCrashLog, from the engine's ExitProcess / TerminateProcess / RtlExitUserProcess / NtTerminateProcess detours on a crash code (raw unmanaged function pointer, resolved and primed at install). Recovers the fatal repeat of an address seen before, which the dedupe skips and which never reaches the last-chance filter when a handler terminates the process. - EnqueueCast refuses during a world transition (CastSlot, pure) and counts the refusal in TransitionRejectedCount. The cast slot now owns the stop-wait note the cast drain keeps per cast (CastSlot.StopWaitNoted, reset by each queued cast before the publishing Volatile.Write of Pending), and DrainCasts reads the queue time once. - The launcher's dump hold is capped at 15 min per client (DumpInProgressRule.Decide); past it the kill checks resume. - CrashExitRule: ExitProcess(-1) (0xFFFFFFFF) is no longer a crash exit; the rest of the 0xC0000000-and-up range is unchanged, so CLR/C++ unhandled-exception exits (0xE0434352, 0xE06D7363) still skip managed work. - The heartbeat line carries qrej=. Tests: EngineRobustnessTests (adds CastSlot stop-wait and ActionRing.TryPeekAt checks), CrashLogFilterTests. Co-Authored-By: Claude Opus 5.5 (1M context) --- native/SehTrampoline/CrashLogFilter.h | 63 ++++++++ native/SehTrampoline/SehTrampoline.c | 109 ++++++++++++-- .../SehTrampoline/tests/CrashLogFilterTests.c | 62 ++++++++ .../MainWindow.axaml.cs | 30 +++- .../Compatibility/AcMainThreadQueue.cs | 54 +++---- .../Compatibility/CastSlot.cs | 59 ++++++++ .../Compatibility/CrashExitRule.cs | 24 ++++ .../Compatibility/HeartbeatLogger.cs | 7 +- .../Compatibility/ProcessExitHooks.cs | 23 ++- .../Compatibility/SehTrampoline.cs | 42 ++++++ src/RynthCore.Engine/CrashDump.cs | 3 +- src/Shared/DumpInProgressRule.cs | 27 ++++ .../EngineRobustnessTests.csproj | 6 +- .../EngineRobustnessTests/RingAndGateTests.cs | 136 ++++++++++++++++++ 14 files changed, 585 insertions(+), 60 deletions(-) create mode 100644 src/RynthCore.Engine/Compatibility/CastSlot.cs create mode 100644 src/RynthCore.Engine/Compatibility/CrashExitRule.cs diff --git a/native/SehTrampoline/CrashLogFilter.h b/native/SehTrampoline/CrashLogFilter.h index a28e0d2..03014f0 100644 --- a/native/SehTrampoline/CrashLogFilter.h +++ b/native/SehTrampoline/CrashLogFilter.h @@ -33,6 +33,13 @@ * small one (it happens once in a dying process; the limit only stops a loop). * - A full address table evicts its least recently written NOISE slot. With no noise * slot to evict, an AC address is still written (under the limit), just not tracked. + * - The last CLF_RING first-chance records, written or not, are kept in a ring (no I/O + * at exception time). A flush writes those that were not written one by one: the + * last-chance filter flushes, and so does the engine's crash-exit path (TerminateProcess + * and friends, through RC_FlushCrashLog). That recovers the case the dedupe alone + * cannot: the fatal hit of an address seen before, at a count that is not due a + * write, followed by a terminate from a handler, so no last-chance filter ever runs + * (checked with 5, 100 and 1000 contained hits before the fatal one). * * Times are GetTickCount milliseconds (32-bit; unsigned subtraction survives the wrap). */ @@ -203,6 +210,62 @@ static clf_decision clf_first_chance(clf_state* s, unsigned int code, unsigned i return clf_new(s, code, addr, cls, nowMs); } +#define CLF_RING 16 + +/* One first-chance record kept for a later flush. */ +typedef struct { + unsigned int seq; /* 1-based push number; 0 = empty */ + unsigned int addr, code, eip, tid, tickMs, hits; + unsigned char written; /* written as an entry of its own when it happened */ +} clf_rec; + +/* + * The last CLF_RING first-chance records. Each record is offered to one flush only: + * a second flush (one exit path calling another) writes nothing new. Sequence numbers + * are 32-bit; a process would need 4 billion logged-code exceptions to wrap them. + */ +typedef struct { + clf_rec r[CLF_RING]; + unsigned int pushed; /* records pushed in total */ + unsigned int flushedTo; /* every record up to this seq has been offered to a flush */ +} clf_ring; + +static void clf_ring_push(clf_ring* g, unsigned int addr, unsigned int code, unsigned int eip, + unsigned int tid, unsigned int tickMs, unsigned int hits, int written) +{ + clf_rec* x = &g->r[g->pushed % CLF_RING]; + g->pushed++; + x->seq = g->pushed; + x->addr = addr; + x->code = code; + x->eip = eip; + x->tid = tid; + x->tickMs = tickMs; + x->hits = hits; + x->written = (unsigned char)(written ? 1 : 0); +} + +/* + * Flush: copies into out[CLF_RING], oldest first, the held records that were not written + * and not offered to an earlier flush, and marks everything pushed so far as offered. + * Returns how many were copied. *older gets the records pushed since the last flush that + * the ring no longer holds (written or not). + */ +static int clf_ring_take(clf_ring* g, clf_rec* out, unsigned int* older) +{ + unsigned int first = g->pushed > CLF_RING ? g->pushed - CLF_RING : 0; /* held: first+1..pushed */ + unsigned int from = g->flushedTo, s; + int n = 0; + if (older) *older = from < first ? first - from : 0; + if (from < first) from = first; + for (s = from + 1; s <= g->pushed; s++) { + const clf_rec* x = &g->r[(s - 1) % CLF_RING]; + if (!x->written) out[n++] = *x; + } + g->flushedTo = g->pushed; + return n; +} + /* The last-chance (unhandled) filter. Any code: whatever reaches it is fatal. */ static clf_decision clf_last_chance(clf_state* s) { diff --git a/native/SehTrampoline/SehTrampoline.c b/native/SehTrampoline/SehTrampoline.c index 4bbc3da..e445c78 100644 --- a/native/SehTrampoline/SehTrampoline.c +++ b/native/SehTrampoline/SehTrampoline.c @@ -277,6 +277,8 @@ static PVOID g_vehHandle = NULL; static LPTOP_LEVEL_EXCEPTION_FILTER g_prevFilter = NULL; static volatile LONG g_logOwner = 0; /* thread id holding the logger, 0 = free */ static clf_state g_filter; /* under g_logOwner */ +static clf_ring g_ring; /* under g_logOwner: recent first-chance records */ +static clf_rec g_flushRecs[CLF_RING];/* under g_logOwner */ static char g_buf[4096]; /* under g_logOwner */ static wchar_t g_wpath[MAX_PATH]; /* under g_logOwner */ static char g_fallbackLeaf[48]; /* under g_logOwner */ @@ -458,22 +460,10 @@ static void cl_write(const char* p, DWORD n) if (g_logHandle != INVALID_HANDLE_VALUE) WriteFile(g_logHandle, p, n, &wr, NULL); } -static void cl_write_entry(PEXCEPTION_POINTERS ep, const char* kind, unsigned int hits) +/* Append " pid=N tid=N date=YYYY-MM-DD time=HH:MM:SS" (local time). */ +static char* cl_stamp(char* p) { - char* p = g_buf; - CONTEXT* c = ep->ContextRecord; - DWORD code = ep->ExceptionRecord->ExceptionCode; - unsigned int exAddr = (unsigned int)(UINT_PTR)ep->ExceptionRecord->ExceptionAddress; SYSTEMTIME st; - if (g_logHandle == INVALID_HANDLE_VALUE) return; - - p = cl_str(p, "\r\n==== NATIVE CRASH LOGGER ("); - p = cl_str(p, kind); - p = cl_str(p, ") ====\r\n code="); - p = cl_hex(p, code); - p = cl_str(p, " exAddr="); - p = cl_sym(p, exAddr, 1); - if (hits > 1) { p = cl_str(p, " repeat="); p = cl_u(p, hits); } p = cl_str(p, " pid="); p = cl_u(p, GetCurrentProcessId()); p = cl_str(p, " tid="); @@ -487,6 +477,25 @@ static void cl_write_entry(PEXCEPTION_POINTERS ep, const char* kind, unsigned in p = cl_u2(p, st.wHour); p = cl_str(p, ":"); p = cl_u2(p, st.wMinute); p = cl_str(p, ":"); p = cl_u2(p, st.wSecond); + return p; +} + +static void cl_write_entry(PEXCEPTION_POINTERS ep, const char* kind, unsigned int hits) +{ + char* p = g_buf; + CONTEXT* c = ep->ContextRecord; + DWORD code = ep->ExceptionRecord->ExceptionCode; + unsigned int exAddr = (unsigned int)(UINT_PTR)ep->ExceptionRecord->ExceptionAddress; + if (g_logHandle == INVALID_HANDLE_VALUE) return; + + p = cl_str(p, "\r\n==== NATIVE CRASH LOGGER ("); + p = cl_str(p, kind); + p = cl_str(p, ") ====\r\n code="); + p = cl_hex(p, code); + p = cl_str(p, " exAddr="); + p = cl_sym(p, exAddr, 1); + if (hits > 1) { p = cl_str(p, " repeat="); p = cl_u(p, hits); } + p = cl_stamp(p); if ((code == 0xC0000005 || code == 0xC0000409) && ep->ExceptionRecord->NumberParameters >= 2) { unsigned int acc = (unsigned int)ep->ExceptionRecord->ExceptionInformation[0]; unsigned int dataAddr = (unsigned int)ep->ExceptionRecord->ExceptionInformation[1]; @@ -545,6 +554,53 @@ static void cl_write_entry(PEXCEPTION_POINTERS ep, const char* kind, unsigned in } } +/* + * Under the lock: write the recent first-chance records that were not written one by one + * (clf_ring_take), oldest first, so the log ends with the newest, usually the fatal hit. + * Module names from the cache only: no loader call on a dying process. + */ +static void cl_flush_locked(const char* reason, unsigned int code) +{ + unsigned int older = 0; + int n = clf_ring_take(&g_ring, g_flushRecs, &older), i; + char* p; + if (n == 0 || g_logHandle == INVALID_HANDLE_VALUE) return; + p = g_buf; + p = cl_str(p, "\r\n==== NATIVE CRASH LOGGER (flush: "); + p = cl_str(p, reason); + p = cl_str(p, ") ====\r\n code="); + p = cl_hex(p, code); + p = cl_stamp(p); + p = cl_str(p, "\r\n recent first-chance records not written one by one, oldest first ("); + p = cl_u(p, (unsigned int)n); + p = cl_str(p, " held"); + if (older) { p = cl_str(p, ", "); p = cl_u(p, older); p = cl_str(p, " older ones no longer held"); } + p = cl_str(p, "):\r\n"); + cl_write(g_buf, (DWORD)(p - g_buf)); + for (i = 0; i < n; i++) { + const clf_rec* x = &g_flushRecs[i]; + p = g_buf; + p = cl_str(p, " exAddr="); + p = cl_sym(p, x->addr, 0); + p = cl_str(p, " code="); + p = cl_hex(p, x->code); + p = cl_str(p, " eip="); + p = cl_sym(p, x->eip, 0); + p = cl_str(p, " tid="); + p = cl_u(p, x->tid); + p = cl_str(p, " tick="); + p = cl_u(p, x->tickMs); + p = cl_str(p, " repeat="); + p = cl_u(p, x->hits); + p = cl_str(p, "\r\n"); + cl_write(g_buf, (DWORD)(p - g_buf)); + } + { + const char* e = "==== END NATIVE CRASH ====\r\n"; + cl_write(e, (DWORD)lstrlenA(e)); + } +} + static LONG CALLBACK CrashVeh(PEXCEPTION_POINTERS ep) { DWORD code = ep->ExceptionRecord->ExceptionCode; @@ -556,11 +612,14 @@ static LONG CALLBACK CrashVeh(PEXCEPTION_POINTERS ep) unsigned int exAddr = (unsigned int)(UINT_PTR)ep->ExceptionRecord->ExceptionAddress; unsigned int now = GetTickCount(); unsigned int hits = 1; + int written = 0; clf_slot* slot = clf_find(&g_filter, exAddr); if (slot) { /* A repeat: decided without touching any module. */ - if (clf_repeat(&g_filter, slot, code, now, &hits) == CLF_LOG_REPEAT) + if (clf_repeat(&g_filter, slot, code, now, &hits) == CLF_LOG_REPEAT) { cl_write_entry(ep, slot->cls != CLF_CLASS_AC ? "first-chance, repeat, noise" : "first-chance, repeat", hits); + written = 1; + } } else { unsigned int base; clf_class faultCls = CLF_CLASS_AC; @@ -574,7 +633,10 @@ static LONG CALLBACK CrashVeh(PEXCEPTION_POINTERS ep) cl_write_entry(ep, cls == CLF_CLASS_NETFX ? "first-chance, .NET Framework noise, not counted" : "first-chance, managed (CoreCLR) noise, not counted", 1); + written = d == CLF_LOG_COUNTED || d == CLF_LOG_NOISE; } + /* Kept for a flush (memory only): the fatal hit is often one not written here. */ + clf_ring_push(&g_ring, exAddr, code, ep->ContextRecord->Eip, GetCurrentThreadId(), now, hits, written); } cl_unlock(); return EXCEPTION_CONTINUE_SEARCH; @@ -584,6 +646,7 @@ static LONG CALLBACK CrashVeh(PEXCEPTION_POINTERS ep) static LONG WINAPI CrashLastChance(PEXCEPTION_POINTERS ep) { if (cl_lock()) { + cl_flush_locked("last chance", ep->ExceptionRecord->ExceptionCode); if (clf_last_chance(&g_filter) == CLF_LOG_LAST_CHANCE) cl_write_entry(ep, "LAST-CHANCE, unhandled", 1); cl_unlock(); @@ -594,6 +657,22 @@ static LONG WINAPI CrashLastChance(PEXCEPTION_POINTERS ep) return EXCEPTION_CONTINUE_SEARCH; } +/* + * A crash exit is under way (the engine's TerminateProcess / NtTerminateProcess / + * ExitProcess / RtlExitUserProcess detours, for a crash code): write the recent + * first-chance records not written one by one. Each record is written once, so the + * second of two nested exit paths writes nothing. exitCode 0 is the engine's priming + * call and does nothing. + */ +__declspec(dllexport) void __cdecl +RC_FlushCrashLog(unsigned int exitCode) +{ + if (exitCode == 0) return; + if (!cl_lock()) return; + cl_flush_locked("crash exit", exitCode); + cl_unlock(); +} + /* * Install the VEH and the last-chance filter once. logPath = wide path to the dedicated * crash log, opened here for the life of the process (append, shared for reading and diff --git a/native/SehTrampoline/tests/CrashLogFilterTests.c b/native/SehTrampoline/tests/CrashLogFilterTests.c index 65c5dde..5c1469c 100644 --- a/native/SehTrampoline/tests/CrashLogFilterTests.c +++ b/native/SehTrampoline/tests/CrashLogFilterTests.c @@ -3,6 +3,7 @@ * filter). Build and run with Run-CrashLogFilterTests.ps1 (x86 MSVC). Exit 0 = pass. */ #include +#include #include #include "../CrashLogFilter.h" @@ -164,8 +165,69 @@ static void full_table_evicts_oldest_noise(void) check(clf_find(&s, 0x0055FA24u) != 0, "AC slots are never evicted"); } +#define FATAL_ADDR 0x00401234u + +/* N contained hits at one address, then the fatal one, then + * a terminate from a handler, so no last-chance filter runs. The fatal hit (N+1) is not due + * a write, so only the ring's flush can put it in the log. */ +static void fatal_repeat_recovered_by_flush(unsigned int n) +{ + clf_state s; + clf_ring g; + clf_rec out[CLF_RING]; + unsigned int hits, i, older, now = 5000; + clf_decision d; + int got; + memset(&s, 0, sizeof s); + memset(&g, 0, sizeof g); + for (i = 0; i < n; i++) { + d = FC(&s, AV, FATAL_ADDR, CLF_CLASS_AC, now + i); + clf_ring_push(&g, FATAL_ADDR, AV, FATAL_ADDR, 77, now + i, hits, is_write(d)); + } + d = FC(&s, AV, FATAL_ADDR, CLF_CLASS_AC, now + n + 1500); /* the fatal hit, 1.5 s later */ + check(d == CLF_SKIP_REPEAT && hits == n + 1, "fatal hit N+1 is not due a write: the dedupe alone loses it"); + clf_ring_push(&g, FATAL_ADDR, AV, FATAL_ADDR, 77, now + n + 1500, hits, is_write(d)); + got = clf_ring_take(&g, out, &older); + check(got >= 1, "the flush has records"); + check(got >= 1 && out[got - 1].addr == FATAL_ADDR && out[got - 1].hits == n + 1 + && out[got - 1].tickMs == now + n + 1500, "the flush ends with the fatal hit (N+1)"); + for (i = 0; i < (unsigned int)got; i++) + check(!out[i].written, "a flush never repeats a record written on its own"); + check(clf_ring_take(&g, out, &older) == 0, "a second flush writes nothing"); +} + +static void ring_order_overflow_and_written(void) +{ + clf_ring g; + clf_rec out[CLF_RING]; + unsigned int i, older; + int got; + memset(&g, 0, sizeof g); + clf_ring_push(&g, 0x10, AV, 0, 1, 1, 1, 1); /* written */ + clf_ring_push(&g, 0x20, AV, 0, 1, 2, 2, 0); + clf_ring_push(&g, 0x30, AV, 0, 1, 3, 1, 1); /* written */ + clf_ring_push(&g, 0x40, AV, 0, 1, 4, 3, 0); + got = clf_ring_take(&g, out, &older); + check(got == 2 && out[0].addr == 0x20 && out[1].addr == 0x40, "only unwritten records, oldest first"); + check(older == 0, "nothing lost under the ring size"); + + for (i = 0; i < 40; i++) clf_ring_push(&g, 0x1000 + i, AV, 0, 1, 100 + i, 2, 0); + got = clf_ring_take(&g, out, &older); + check(got == CLF_RING, "40 unwritten since the last flush: the ring holds the newest 16"); + check(older == 24, "and reports the 24 it no longer holds"); + check(out[0].addr == 0x1000 + 24 && out[CLF_RING - 1].addr == 0x1000 + 39, "newest 16, oldest first"); + + clf_ring_push(&g, 0x9999, AV, 0, 1, 500, 2, 0); + got = clf_ring_take(&g, out, &older); + check(got == 1 && out[0].addr == 0x9999 && older == 0, "after a flush, only what came since"); +} + int main(void) { + fatal_repeat_recovered_by_flush(5); + fatal_repeat_recovered_by_flush(100); + fatal_repeat_recovered_by_flush(1000); + ring_order_overflow_and_written(); netfx_noise_never_spends_the_limit(); known_address_going_fatal_is_written(); ac_faults_limited_per_distinct_address(); diff --git a/src/RynthCore.App.Avalonia/MainWindow.axaml.cs b/src/RynthCore.App.Avalonia/MainWindow.axaml.cs index 9c6698e..5208660 100644 --- a/src/RynthCore.App.Avalonia/MainWindow.axaml.cs +++ b/src/RynthCore.App.Avalonia/MainWindow.axaml.cs @@ -3104,8 +3104,9 @@ internal partial class MainWindow : Window // thread not draining the marshalled-action queue), and a stale heartbeat // file. private readonly Dictionary _wedgeZeroFpsSinceUtc = new(); - // PIDs whose "dump in progress, kill held off" line was logged (once per dump). - private readonly HashSet _dumpHoldLoggedPids = new(); + // PIDs held off for a full-memory dump, and since when (DumpInProgressRule.Decide caps the + // hold at MaxHold). Kept while held or expired, dropped once no dump is in progress. + private readonly Dictionary _dumpHoldSinceUtc = new(); // Last write of the newest acclient_oom__*.dmp in the shared Dumps folder, or null. private static DateTime? NewestOomDumpWriteUtc(int pid) @@ -3208,13 +3209,30 @@ internal partial class MainWindow : Window // the log goes silent and the main thread looks hung, but killing now would cut // the dump short. Hold off both kills below while it is being written // (DumpInProgressRule); the restart for the box that follows is unchanged. - if (RynthCore.Install.DumpInProgressRule.IsDumping(tail, fi.LastWriteTimeUtc, NewestOomDumpWriteUtc(pid), DateTime.UtcNow)) + DateTime holdNow = DateTime.UtcNow; + DateTime? heldSince = _dumpHoldSinceUtc.TryGetValue(pid, out DateTime hs) ? hs : null; + var hold = RynthCore.Install.DumpInProgressRule.Decide(tail, fi.LastWriteTimeUtc, NewestOomDumpWriteUtc(pid), heldSince, holdNow); + if (hold == RynthCore.Install.DumpInProgressRule.Hold.Holding) { - if (_dumpHoldLoggedPids.Add(pid)) - LauncherDiag.Info($"WEDGE: PID {pid} is writing a full-memory dump - kill held off until it ends."); + if (heldSince == null) + { + _dumpHoldSinceUtc[pid] = holdNow; + LauncherDiag.Info($"WEDGE: PID {pid} is writing a full-memory dump - kill held off until it ends (at most {RynthCore.Install.DumpInProgressRule.MaxHold.TotalMinutes:0} min)."); + } continue; } - _dumpHoldLoggedPids.Remove(pid); + if (hold == RynthCore.Install.DumpInProgressRule.Hold.Expired) + { + if (heldSince is DateTime heldAt && heldAt != DateTime.MinValue) + { + _dumpHoldSinceUtc[pid] = DateTime.MinValue; // logged; stays expired until the signs clear + LauncherDiag.Info($"WEDGE: PID {pid} dump hold expired after {RynthCore.Install.DumpInProgressRule.MaxHold.TotalMinutes:0} min - kill checks resume."); + } + } + else + { + _dumpHoldSinceUtc.Remove(pid); + } if (hbStale) { diff --git a/src/RynthCore.Engine/Compatibility/AcMainThreadQueue.cs b/src/RynthCore.Engine/Compatibility/AcMainThreadQueue.cs index 6f4a225..814ae0b 100644 --- a/src/RynthCore.Engine/Compatibility/AcMainThreadQueue.cs +++ b/src/RynthCore.Engine/Compatibility/AcMainThreadQueue.cs @@ -1098,9 +1098,7 @@ internal static class AcMainThreadQueue // tick — they already handle a false return without wedging. At ~frame-rate drain // the slot clears within ~1 frame. This is the LAST off-thread AC mutator to be // marshalled, closing the off-thread object-graph corruption class at its source. - private static int _castPending; - private static uint _castTargetId; - private static uint _castSpellId; + private static readonly CastSlot _cast = new(); // writes under _castLock private static readonly object _castLock = new(); // Ticks DrainCasts has deferred the pending cast because a motion gesture was @@ -1109,33 +1107,27 @@ internal static class AcMainThreadQueue // plugin's no-chat-resolve machinery already retries casts that produce no // chat, so a drop degrades to one retry cycle, never a wedge. private static long _castDeferDrops; - private static long _castQueuedAt; // TickCount64 when the pending cast was queued (2026-10-06) + /// Casts dropped after deferring CastDeferTickCap ticks (stuck gesture). public static long CastDeferDropCount => Interlocked.Read(ref _castDeferDrops); // Pump-thread enqueue. Returns false (caller retries next tick) if a cast is - // already pending. + // already pending, or during a world transition (CastSlot): the drain would only hold + // it and then drop it, and the slot would refuse every newer cast meanwhile. public static bool EnqueueCast(uint targetId, uint spellId) { + CastSlot.Admit admit; lock (_castLock) - { - if (_castPending != 0) return false; - _castTargetId = targetId; - _castSpellId = spellId; - // Volatile: DrainCasts reads both without the lock, and a plain 64-bit store can - // tear on x86. The time and the stop-wait reset first, then the flag that - // publishes them (a release store: the drain's Volatile.Read of the flag sees both). - Volatile.Write(ref _castQueuedAt, NowMs); - _castStopWaitNoted = false; - Volatile.Write(ref _castPending, 1); - return true; - } + admit = _cast.TryEnqueue(targetId, spellId, NowMs, PlayerLifecycleLog.InWorldTransition); + if (admit == CastSlot.Admit.RejectedTransition) + Interlocked.Increment(ref _transitionRejected); + return admit == CastSlot.Admit.Queued; } - // Casts that waited for a movement stop queued ahead of them (counted once per cast). + // Casts that waited for a movement stop queued ahead of them (counted once per cast; + // the per-cast flag is CastSlot.StopWaitNoted, reset by each new cast). private static long _castStopWaits; - private static bool _castStopWaitNoted; /// Casts that waited one or more ticks for a stop queued ahead of them. public static long CastStopWaitCount => Interlocked.Read(ref _castStopWaits); @@ -1172,7 +1164,7 @@ internal static class AcMainThreadQueue private static void DrainCastsCore() { if (_disarmed) return; // engine teardown in progress - if (Volatile.Read(ref _castPending) == 0) return; // alloc-free fast path + if (Volatile.Read(ref _cast.Pending) == 0) return; // alloc-free fast path // ── Anim-walk race guard (dump-proven 2026-06-12) ──────────────────── // DrainCasts runs PRE-tick (selection timing), but a cast initiates a @@ -1195,14 +1187,14 @@ internal static class AcMainThreadQueue // during it is dropped once it ends (WorldTransitionState). Before the gesture check: // nothing about the player's motion is read while AC is tearing the world down. long nowCast = NowMs; - long queuedAt = Volatile.Read(ref _castQueuedAt); + long queuedAt = Volatile.Read(ref _cast.QueuedAt); WorldTransitionState.Verdict castVerdict = PlayerLifecycleLog.DecideQueued(nowCast, queuedAt, teardown: false); if (castVerdict == WorldTransitionState.Verdict.Hold) return; if (castVerdict == WorldTransitionState.Verdict.Drop) { uint droppedSpell; - lock (_castLock) { droppedSpell = _castSpellId; _castPending = 0; } + lock (_castLock) { droppedSpell = _cast.SpellId; _cast.Pending = 0; } NoteTransitionDrop($"CastSpell({droppedSpell})", nowCast - queuedAt); return; } @@ -1215,7 +1207,7 @@ internal static class AcMainThreadQueue // Gesture stuck past the deadline — drop the cast instead of injecting // into a wedged motion graph; the plugin retries via no-chat-resolve. uint dropped; - lock (_castLock) { dropped = _castSpellId; _castPending = 0; } + lock (_castLock) { dropped = _cast.SpellId; _cast.Pending = 0; } Interlocked.Increment(ref _castDeferDrops); NoteStale($"CastSpell({dropped}) behind a gesture", castAge, dropped: true); return; @@ -1228,13 +1220,13 @@ internal static class AcMainThreadQueue // locomotion still on, and the queued stops followed as extra MoveToStates. Wait (at // most until EndScene drains the ring, about one frame; the ring's own gesture defer // is shorter than CastDeferMaxMs) while one is queued; past the limit cast anyway. - if (StopQueuedAtOrBefore(Volatile.Read(ref _castQueuedAt))) + if (StopQueuedAtOrBefore(queuedAt)) { if (castAge <= CastDeferMaxMs) { - if (!_castStopWaitNoted) + if (!_cast.StopWaitNoted) { - _castStopWaitNoted = true; + _cast.StopWaitNoted = true; Interlocked.Increment(ref _castStopWaits); try { Net.FlightRecorder.Mark(Net.FlightMark.Note, text: "cast waits for a movement stop queued before it"); } catch { } } @@ -1243,7 +1235,7 @@ internal static class AcMainThreadQueue } // ── The stop goes a server answer ahead of the cast (2026-10-12, PreCastStopRules) ── - long castStamp = Volatile.Read(ref _castQueuedAt); + long castStamp = queuedAt; if (_preStopFor != castStamp) { _preStopFor = castStamp; _preStopSent = false; } long nowMs = NowMs; PreCastStep step = PreCastStopRules.Decide( @@ -1280,10 +1272,10 @@ internal static class AcMainThreadQueue uint target, spell; lock (_castLock) { - if (_castPending == 0) return; - target = _castTargetId; - spell = _castSpellId; - _castPending = 0; + if (_cast.Pending == 0) return; + target = _cast.TargetId; + spell = _cast.SpellId; + _cast.Pending = 0; } if (castAge > LateActionLogMs) NoteStale($"CastSpell({spell})", castAge, dropped: false); diff --git a/src/RynthCore.Engine/Compatibility/CastSlot.cs b/src/RynthCore.Engine/Compatibility/CastSlot.cs new file mode 100644 index 0000000..1172107 --- /dev/null +++ b/src/RynthCore.Engine/Compatibility/CastSlot.cs @@ -0,0 +1,59 @@ +// ============================================================================ +// RynthCore.Engine - Compatibility/CastSlot.cs +// +// AcMainThreadQueue's single-outstanding cast slot (SelectItem + CastSpell pair): one +// pending cast at a time, taken by DrainCasts on AC's game-logic tick. +// +// A cast is refused outright during a world transition (dead, in portal space, or the +// settle window after a teleport): the drain would only hold it and then drop it, and +// meanwhile the slot would refuse every newer cast. The caller (BuffManager / +// CombatManager) already treats false as "retry next tick". Refused like the action ring +// refuses non-teardown work during a transition (ActionRing.Admit.RejectedTransition). +// +// Pure: no engine state, no locking (AcMainThreadQueue holds _castLock for every write; +// DrainCasts reads Pending and QueuedAt with Volatile, hence public fields). Compiled +// into tools\EngineRobustnessTests. +// ============================================================================ + +using System.Threading; + +namespace RynthCore.Engine.Compatibility; + +internal sealed class CastSlot +{ + public enum Admit + { + Queued, + /// A cast is already pending; nothing changed. + Busy, + /// A world transition is in progress; nothing changed. + RejectedTransition, + } + + public int Pending; + public uint TargetId; + public uint SpellId; + /// TickCount64 when the pending cast was queued. + public long QueuedAt; + /// + /// The drain has counted this cast's wait for a movement stop queued before it (once per + /// cast). Reset by every queued cast; set by DrainCasts on the main thread. + /// + public bool StopWaitNoted; + + /// Under the caller's lock. The slot is written only when this returns Queued. + public Admit TryEnqueue(uint targetId, uint spellId, long nowMs, bool inTransition) + { + if (inTransition) return Admit.RejectedTransition; + if (Pending != 0) return Admit.Busy; + TargetId = targetId; + SpellId = spellId; + // Volatile: DrainCasts reads both without the lock, and a plain 64-bit store can + // tear on x86. The time and the stop-wait reset first, then the flag that publishes + // them (a release store, so the drain's Volatile.Read of Pending sees both). + Volatile.Write(ref QueuedAt, nowMs); + StopWaitNoted = false; + Volatile.Write(ref Pending, 1); + return Admit.Queued; + } +} diff --git a/src/RynthCore.Engine/Compatibility/CrashExitRule.cs b/src/RynthCore.Engine/Compatibility/CrashExitRule.cs new file mode 100644 index 0000000..d4d724f --- /dev/null +++ b/src/RynthCore.Engine/Compatibility/CrashExitRule.cs @@ -0,0 +1,24 @@ +// ============================================================================ +// RynthCore.Engine - Compatibility/CrashExitRule.cs +// +// Is a process exit code a CRASH exit? ProcessExitHooks passes a crash exit straight to +// the original (no managed work on a dying process) after flushing the native crash +// logger's recent first-chance records. +// +// A crash exit is an error-severity status or exception code (both top bits set, +// 0xC0000000 and up): 0xC0000005 an access violation, 0xC0000409 a stack buffer overrun, +// 0xC0000374 heap corruption, and the software exception codes a runtime exits with on an +// unhandled exception, 0xE0434352 (CLR) and 0xE06D7363 (C++). +// EXCEPT 0xFFFFFFFF: ExitProcess(-1) is an ordinary "exit with failure", not a fault. The +// old rule (code >= 0xC0000000) took it for a crash and skipped the orderly shutdown +// of the process. +// +// Pure. Compiled into tools\EngineRobustnessTests. +// ============================================================================ + +namespace RynthCore.Engine.Compatibility; + +internal static class CrashExitRule +{ + public static bool IsCrashExit(uint code) => (code & 0xC0000000u) == 0xC0000000u && code != 0xFFFFFFFFu; +} diff --git a/src/RynthCore.Engine/Compatibility/HeartbeatLogger.cs b/src/RynthCore.Engine/Compatibility/HeartbeatLogger.cs index af86683..eaf9660 100644 --- a/src/RynthCore.Engine/Compatibility/HeartbeatLogger.cs +++ b/src/RynthCore.Engine/Compatibility/HeartbeatLogger.cs @@ -135,6 +135,11 @@ internal static class HeartbeatLogger // flooding the ring; flat = fine. long dropped = 0; try { dropped = AcMainThreadQueue.DroppedCount; } catch { } + // qrej = marshalled actions and casts refused during a world transition + // (dead / portal / settle window), a running total kept apart from qdrop: a + // jump in qrej around a teleport is the gate working, not a flood. + long rejected = 0; + try { rejected = AcMainThreadQueue.TransitionRejectedCount; } catch { } // rec = busy reconciles (cast/item-action), fcl = force-clears. // Soak health: rec climbs during combat/loot; fcl stays flat. long rec = 0, fcl = 0; @@ -188,7 +193,7 @@ internal static class HeartbeatLogger string vpField = ""; try { vpField = D3D9.VideoPatch.OnHeartbeat(draw); } catch { } - RynthLog.Info($"hb #{tick} up={(nowMs - startMs) / 1000}s fps={fps} draw={draw} plug={pps}/s ws={wsMb}MB login={login} qdrop={dropped} rec={rec} fcl={fcl}{idleField}{uiField}{vaField}{gateField}{vpField}"); + RynthLog.Info($"hb #{tick} up={(nowMs - startMs) / 1000}s fps={fps} draw={draw} plug={pps}/s ws={wsMb}MB login={login} qdrop={dropped} qrej={rejected} rec={rec} fcl={fcl}{idleField}{uiField}{vaField}{gateField}{vpField}"); // Every 60 s: garbage collections and the time they paused the process. // Under the CoreCLR host the engine and managed plugins share one GC, so a diff --git a/src/RynthCore.Engine/Compatibility/ProcessExitHooks.cs b/src/RynthCore.Engine/Compatibility/ProcessExitHooks.cs index 993f193..a8f95b1 100644 --- a/src/RynthCore.Engine/Compatibility/ProcessExitHooks.cs +++ b/src/RynthCore.Engine/Compatibility/ProcessExitHooks.cs @@ -179,6 +179,7 @@ internal static class ProcessExitHooks // native pass-through would remove that too; it is possible but not done here. if (IsCrashExit(exitCode)) { + SehTrampoline.FlushCrashLog(exitCode); // native, allocation-free _exitOriginal!(exitCode); return; } @@ -201,15 +202,22 @@ internal static class ProcessExitHooks // need managed code on the way out: the native crash logger (SehTrampoline.c, its vectored // handler sees the fault first) and CoreCLR's own createdump (native\Loader\Loader.c, ConfigureCrashDumps). This // replaces the managed crash dump written here before, which left nothing for real crashes. - private static bool IsCrashExit(uint code) => code >= 0xC0000000u; + // The one call made first, SehTrampoline.FlushCrashLog, is a raw native call: it writes + // the crash logger's recent first-chance records that were not written one by one (the + // fatal hit of an address seen before is usually among them; a terminate from a handler + // never reaches the last-chance filter). Which codes count: CrashExitRule. + private static bool IsCrashExit(uint code) => CrashExitRule.IsCrashExit(code); private static bool TerminateProcessDetour(IntPtr hProcess, uint exitCode) { // Only log when terminating ourselves: TerminateProcess on other process handles is a // normal Process.Kill and not what we're hunting. hProcess == -1 is the pseudo-handle. bool selfKill = hProcess == new IntPtr(-1) || hProcess == GetCurrentProcessHandle(); - if (selfKill && !IsCrashExit(exitCode)) - LogTermination("TerminateProcess", hProcess, exitCode); + if (selfKill) + { + if (IsCrashExit(exitCode)) SehTrampoline.FlushCrashLog(exitCode); + else LogTermination("TerminateProcess", hProcess, exitCode); + } try { return _terminateOriginal!(hProcess, exitCode); } catch { return false; } } @@ -221,6 +229,7 @@ internal static class ProcessExitHooks { if (IsCrashExit(exitStatus)) // see ExitProcessDetour { + SehTrampoline.FlushCrashLog(exitStatus); _rtlExitOriginal!(exitStatus); return; } @@ -234,8 +243,12 @@ internal static class ProcessExitHooks private static uint NtTerminateProcessDetour(IntPtr processHandle, uint exitStatus) { bool selfKill = processHandle == new IntPtr(-1) || processHandle == GetCurrentProcessHandle(); - if (selfKill && !IsCrashExit(exitStatus)) - LogTermination("NtTerminateProcess", processHandle, exitStatus); + if (selfKill) + { + // A second flush (TerminateProcess calls this) writes nothing: records are written once. + if (IsCrashExit(exitStatus)) SehTrampoline.FlushCrashLog(exitStatus); + else LogTermination("NtTerminateProcess", processHandle, exitStatus); + } try { return _ntTermOriginal!(processHandle, exitStatus); } catch { return 0xC0000001; /* STATUS_UNSUCCESSFUL */ } } diff --git a/src/RynthCore.Engine/Compatibility/SehTrampoline.cs b/src/RynthCore.Engine/Compatibility/SehTrampoline.cs index 59604ed..879fa3d 100644 --- a/src/RynthCore.Engine/Compatibility/SehTrampoline.cs +++ b/src/RynthCore.Engine/Compatibility/SehTrampoline.cs @@ -51,8 +51,50 @@ internal static class SehTrampoline { try { _InstallCrashLogger(logPath); } catch (Exception ex) { RynthLog.Compat($"SehTrampoline: InstallCrashLogger failed - {ex.GetType().Name}: {ex.Message}"); } + ResolveFlushCrashLog(); } + // RC_FlushCrashLog, resolved once here (0 = a DLL older than the export). Called through a + // raw unmanaged function pointer, so the crash path binds and compiles nothing: the call + // is primed below with code 0, which the native side ignores. + private static nint _flushCrashLog; + + private static unsafe void ResolveFlushCrashLog() + { + try + { + nint module = GetModuleHandleW("RynthCore.SehTrampoline.dll"); + nint fn = module == 0 ? 0 : GetProcAddress(module, "RC_FlushCrashLog"); + if (fn == 0) + { + RynthLog.Compat("SehTrampoline: RC_FlushCrashLog not exported (older DLL); crash exits will not flush the crash log's recent records."); + return; + } + ((delegate* unmanaged[Cdecl])fn)(0); // prime: code 0 is a no-op + _flushCrashLog = fn; + } + catch (Exception ex) { RynthLog.Compat($"SehTrampoline: RC_FlushCrashLog unavailable - {ex.GetType().Name}: {ex.Message}"); } + } + + /// + /// A crash exit is under way (ProcessExitHooks): write the crash logger's recent first-chance + /// records that were not written one by one, such as the fatal repeat of an address seen + /// before. Native and allocation-free; writes each record once, so a second call (one exit + /// path calling another) writes nothing. + /// + public static unsafe void FlushCrashLog(uint exitCode) + { + nint fn = _flushCrashLog; + if (fn == 0 || exitCode == 0) return; + ((delegate* unmanaged[Cdecl])fn)(exitCode); + } + + [DllImport("kernel32.dll", CharSet = CharSet.Unicode, EntryPoint = "GetModuleHandleW")] + private static extern nint GetModuleHandleW(string name); + + [DllImport("kernel32.dll", CharSet = CharSet.Ansi, EntryPoint = "GetProcAddress", ExactSpelling = true)] + private static extern nint GetProcAddress(nint module, string name); + private static int _moduleRefreshUnavailable; /// diff --git a/src/RynthCore.Engine/CrashDump.cs b/src/RynthCore.Engine/CrashDump.cs index af6fb8a..0507e2a 100644 --- a/src/RynthCore.Engine/CrashDump.cs +++ b/src/RynthCore.Engine/CrashDump.cs @@ -293,4 +293,5 @@ internal static class CrashDump { return false; } - }} + } +} diff --git a/src/Shared/DumpInProgressRule.cs b/src/Shared/DumpInProgressRule.cs index 41c5c68..ade35d0 100644 --- a/src/Shared/DumpInProgressRule.cs +++ b/src/Shared/DumpInProgressRule.cs @@ -13,6 +13,9 @@ // - the client's acclient_oom__*.dmp file is still being written (modified within // FileQuietMs). // The launcher's restart after the dump, for the OOM box that follows, is unchanged. +// A hold never lasts more than MaxHold per client (Decide, from the launcher's first hold +// of that pid): a log kept fresh by some other writer while a marker stays open must not +// shield a dead client forever. Past the cap the kills resume. // // Pure. Compiled into tools\EngineRobustnessTests. // ============================================================================ @@ -29,6 +32,30 @@ internal static class DumpInProgressRule public static readonly TimeSpan MaxMarkerAge = TimeSpan.FromMinutes(10); public static readonly TimeSpan FileQuietMs = TimeSpan.FromSeconds(30); + public static readonly TimeSpan MaxHold = TimeSpan.FromMinutes(15); + + public enum Hold + { + /// No dump in progress: the kill checks run. + None, + /// A dump is in progress: hold off the kills. + Holding, + /// Signs of a dump, but held for MaxHold already: the kill checks run. + Expired, + } + + /// + /// , capped: is when the launcher first + /// held this client (null = not held yet). The launcher keeps that time while the result is + /// Holding or Expired and forgets it on None, so an expired hold does not start again. + /// + public static Hold Decide(string? logTail, DateTime logLastWriteUtc, DateTime? newestOomDumpWriteUtc, + DateTime? holdSinceUtc, DateTime nowUtc) + { + if (!IsDumping(logTail, logLastWriteUtc, newestOomDumpWriteUtc, nowUtc)) return Hold.None; + if (holdSinceUtc is DateTime since && nowUtc - since >= MaxHold) return Hold.Expired; + return Hold.Holding; + } /// /// True while the launcher must not kill the client for a silent log. diff --git a/tools/EngineRobustnessTests/EngineRobustnessTests.csproj b/tools/EngineRobustnessTests/EngineRobustnessTests.csproj index 29122af..341bff5 100644 --- a/tools/EngineRobustnessTests/EngineRobustnessTests.csproj +++ b/tools/EngineRobustnessTests/EngineRobustnessTests.csproj @@ -13,7 +13,9 @@ 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 + 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)) Run: dotnet run -c Release (exit 0 = pass, 1 = fail) --> @@ -36,6 +38,8 @@ + + diff --git a/tools/EngineRobustnessTests/RingAndGateTests.cs b/tools/EngineRobustnessTests/RingAndGateTests.cs index b1676f8..e685a0c 100644 --- a/tools/EngineRobustnessTests/RingAndGateTests.cs +++ b/tools/EngineRobustnessTests/RingAndGateTests.cs @@ -27,6 +27,14 @@ internal static partial class Program 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) -------- @@ -329,4 +337,132 @@ internal static partial class Program 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(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(); + 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"); + } + } }