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=<TransitionRejectedCount>.

Tests: EngineRobustnessTests (adds CastSlot stop-wait and ActionRing.TryPeekAt checks),
CrashLogFilterTests.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Daniel Wallace 2026-10-10 21:53:42 -07:00
commit 636f5d307a
14 changed files with 585 additions and 60 deletions

View file

@ -3104,8 +3104,9 @@ internal partial class MainWindow : Window
// thread not draining the marshalled-action queue), and a stale heartbeat
// file.
private readonly Dictionary<int, DateTime> _wedgeZeroFpsSinceUtc = new();
// PIDs whose "dump in progress, kill held off" line was logged (once per dump).
private readonly HashSet<int> _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<int, DateTime> _dumpHoldSinceUtc = new();
// Last write of the newest acclient_oom_<pid>_*.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)
{

View file

@ -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)
/// <summary>Casts dropped after deferring CastDeferTickCap ticks (stuck gesture).</summary>
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;
/// <summary>Casts that waited one or more ticks for a stop queued ahead of them.</summary>
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);

View file

@ -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,
/// <summary>A cast is already pending; nothing changed.</summary>
Busy,
/// <summary>A world transition is in progress; nothing changed.</summary>
RejectedTransition,
}
public int Pending;
public uint TargetId;
public uint SpellId;
/// <summary>TickCount64 when the pending cast was queued.</summary>
public long QueuedAt;
/// <summary>
/// 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.
/// </summary>
public bool StopWaitNoted;
/// <summary>Under the caller's lock. The slot is written only when this returns Queued.</summary>
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;
}
}

View file

@ -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;
}

View file

@ -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

View file

@ -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 */ }
}

View file

@ -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]<uint, void>)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}"); }
}
/// <summary>
/// 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.
/// </summary>
public static unsafe void FlushCrashLog(uint exitCode)
{
nint fn = _flushCrashLog;
if (fn == 0 || exitCode == 0) return;
((delegate* unmanaged[Cdecl]<uint, void>)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;
/// <summary>

View file

@ -293,4 +293,5 @@ internal static class CrashDump
{
return false;
}
}}
}
}

View file

@ -13,6 +13,9 @@
// - the client's acclient_oom_<pid>_*.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
{
/// <summary>No dump in progress: the kill checks run.</summary>
None,
/// <summary>A dump is in progress: hold off the kills.</summary>
Holding,
/// <summary>Signs of a dump, but held for MaxHold already: the kill checks run.</summary>
Expired,
}
/// <summary>
/// <see cref="IsDumping"/>, capped: <paramref name="holdSinceUtc"/> 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.
/// </summary>
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;
}
/// <summary>
/// True while the launcher must not kill the client for a silent log.