Engine robustness: appraisal merge, AutoId re-eligibility, freeze pause, OOM dump, crash logger, transition gate

Appraisals
- RequestId slot merges a pending request for the same object (PendingIdQueue), as the
  QueryHealth slot does.
- AutoId: per-object last-sent time kept across client releases; no re-appraisal within
  10 min while the data is cached, unless the server deleted the object (0xF747). Map
  bounded at 8192 with a prune off the create path. The sent mark is set at the real
  send in DrainRequestIds, not at queue time.
- The selected-target priority appraisal is skipped when its data is cached and fresh.

Main thread frozen
- Plugin ticks pause while AC's main thread is frozen (a main-thread message box, or no
  beat for the hang watchdog's threshold); events keep flowing. Exposed through
  GetEngineStatusJson (mainThreadFrozen, mainThreadStallMs, pluginTicksPausedMs) and the
  heartbeat (pump=paused).

Crashes
- AC's OUT OF MEMORY box: one full-memory dump to <install>\Dumps before the box shows,
  newest 3 kept.
- Native crash logger: pid, tid and date per entry; once per address; .NET Framework
  AVs never charged to the limit; last-chance handler; stack overflow and heap
  corruption codes. Build-SehTrampoline gains -NoDeploy.
- ProcessExitHooks: dead fail-fast detours removed; crash exit codes pass straight
  through TerminateProcess/NtTerminateProcess.
- CoreCLR's own crash dump is left to the loader's existing ConfigureCrashDumps
  (Loader.c, Logs\dumps\clr_*.dmp) and Publish-EngineCoreClr's createdump/DAC
  handling; this change adds no second setup.

World transitions
- AcMainThreadQueue holds queued game-mutating work while the player is dead, in portal
  space, or within 5 s after either or after a non-adjacent landblock jump. When the
  window ends, stale casts, uses, selects and appraisals are dropped and stops and
  cancels run in order. Walking across an adjacent landblock border never gates.
  State is re-sampled after AC's tick, before the post-tick drain.
- Inventory panel actions are held during a transition too.

Diagnostics
- Heartbeat valargest= (largest free VA block); free and largest logged before and after
  each plugin load and unload.
- CastSpell comments corrected to the actual main-thread paths.

Tests
- tools\EngineRobustnessTests and native\SehTrampoline\tests\CrashLogFilterTests.c.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Daniel Wallace 2026-10-10 20:46:37 -07:00
commit 55f7497065
30 changed files with 2202 additions and 419 deletions

View file

@ -6,6 +6,12 @@
// always-on procdump (which also dumped on every clean exit and every handled
// first-chance AV, so a .dmp's existence never meant a real crash).
//
// Also writes ONE full-memory dump when AC shows its OUT OF MEMORY box
// (MessageBoxHooks): that box is modal, so the process never crashes and Windows
// never writes a dump; the launcher later kills the client as wedged
// (AutoRestartWedgedClients, kept as it is). The hang dump is a small type and
// holds no heap, which is what an out-of-memory needs.
//
// Safe to call from a background thread: MiniDumpWriteDump suspends all other
// threads internally while it snapshots them, which is exactly what we want for
// a hang. The dbghelp.dll P/Invoke is lazy-bound (no cost unless we ever fire).
@ -14,6 +20,7 @@
using System;
using System.IO;
using System.Runtime.InteropServices;
using System.Threading;
namespace RynthCore.Engine;
@ -46,6 +53,14 @@ internal static class CrashDump
private const uint DumpTypePreferred = 0x00000000 | 0x00000004; // Normal + WithHandleData
private const uint DumpTypeFallback = 0x00000000; // Normal only (universally supported)
// MiniDumpWithFullMemory (0x2) is as old as MiniDumpNormal, so dbghelp 6.1 takes it.
private const uint DumpTypeFull = 0x00000002 | 0x00000004; // FullMemory + WithHandleData
private const uint DumpTypeFullFallback = 0x00000002; // FullMemory only
// dbghelp is single-threaded: every MiniDumpWriteDump in this process goes through this
// lock, so the hang watchdog's small dump can never run alongside the OOM full dump.
private static readonly object DumpLock = new();
/// <summary>
/// Write a minidump of the current process to Logs\dumps\. Best-effort;
/// never throws. Returns true on success and sets <paramref name="dumpPath"/>.
@ -60,40 +75,7 @@ internal static class CrashDump
string stamp = DateTime.Now.ToString("yyyyMMdd_HHmmss");
dumpPath = Path.Combine(dir, $"{prefix}_{Environment.ProcessId}_{stamp}.dmp");
using var fs = new FileStream(dumpPath, FileMode.Create, FileAccess.Write, FileShare.None);
bool ok = MiniDumpWriteDump(
GetCurrentProcess(), GetCurrentProcessId(), fs.SafeFileHandle,
DumpTypePreferred, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero);
int err = ok ? 0 : Marshal.GetLastWin32Error();
// ERROR_INVALID_PARAMETER (87) ⇒ AC's ancient dbghelp 6.1 rejected a flag.
// Retry with bare MiniDumpNormal (universally supported, still has every
// thread stack — what we need to read the deadlock's lock holder).
if (!ok && err == 87)
{
fs.SetLength(0);
ok = MiniDumpWriteDump(
GetCurrentProcess(), GetCurrentProcessId(), fs.SafeFileHandle,
DumpTypeFallback, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero);
err = ok ? 0 : Marshal.GetLastWin32Error();
if (ok) RynthLog.Error($"CrashDump: rich flags rejected by AC's old dbghelp 6.1 — wrote bare Normal dump, reason={reason}");
}
if (!ok)
{
RynthLog.Error($"CrashDump: MiniDumpWriteDump failed err={err} reason={reason}");
// Don't leave a 0-byte .dmp behind — it reads as a crash marker
// during triage (observed: hang_17692_20260611_114430.dmp, 0
// bytes, main thread suspended mid-exception-dispatch).
try { fs.Close(); File.Delete(dumpPath); } catch { }
return false;
}
long size = 0;
try { size = new FileInfo(dumpPath).Length; } catch { }
RynthLog.Error($"CrashDump: wrote {dumpPath} ({size / 1024}KB) reason={reason}");
return true;
return WriteDumpFile(dumpPath, DumpTypePreferred, DumpTypeFallback, reason);
}
catch (Exception ex)
{
@ -101,4 +83,159 @@ internal static class CrashDump
return false;
}
}
// Writes one dump to <paramref name="path"/>. On ERROR_INVALID_PARAMETER (87: AC's ancient
// dbghelp 6.1 rejected a flag) retries with <paramref name="fallbackType"/>. Never leaves a
// 0-byte or partial .dmp behind (it reads as a crash marker during triage; observed:
// hang_17692_20260611_114430.dmp, 0 bytes, main thread suspended mid-exception-dispatch).
private static bool WriteDumpFile(string path, uint type, uint fallbackType, string reason)
{
lock (DumpLock)
{
bool ok;
int err;
using (var fs = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None))
{
ok = MiniDumpWriteDump(GetCurrentProcess(), GetCurrentProcessId(), fs.SafeFileHandle,
type, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero);
err = ok ? 0 : Marshal.GetLastWin32Error();
if (!ok && err == 87 && fallbackType != type)
{
fs.SetLength(0);
ok = MiniDumpWriteDump(GetCurrentProcess(), GetCurrentProcessId(), fs.SafeFileHandle,
fallbackType, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero);
err = ok ? 0 : Marshal.GetLastWin32Error();
if (ok) RynthLog.Error($"CrashDump: flags 0x{type:X} rejected by AC's old dbghelp 6.1 - wrote type 0x{fallbackType:X}, reason={reason}");
}
}
if (!ok)
{
RynthLog.Error($"CrashDump: MiniDumpWriteDump failed err={err} type=0x{type:X} reason={reason}");
try { File.Delete(path); } catch { }
return false;
}
long size = 0;
try { size = new FileInfo(path).Length; } catch { }
RynthLog.Error($"CrashDump: wrote {path} ({size / 1024}KB) reason={reason}");
return true;
}
}
// ── OUT OF MEMORY full-memory dump ──────────────────────────────────────
/// <summary>Full dumps kept in the Dumps folder (a full dump is about the size of the process).</summary>
internal const int OutOfMemoryDumpsKept = 3;
internal const string OutOfMemoryDumpPrefix = "acclient_oom_";
// Longest the showing thread waits for the dump writer before letting the box open anyway.
private const int FullDumpWaitMs = 300_000;
private static int _oomDumpLatch;
private static volatile bool _fullDumpInProgress;
private static volatile string? _fullDumpWrittenPath;
/// <summary>True while the OUT OF MEMORY full dump is being written (the watchdog holds off).</summary>
internal static bool FullDumpInProgress => _fullDumpInProgress;
/// <summary>The OUT OF MEMORY full dump written this session, or null.</summary>
internal static string? FullDumpWrittenPath => _fullDumpWrittenPath;
/// <summary>C:\Games\RynthCore\Dumps by default (beside Logs, under the install folder).</summary>
internal static string OutOfMemoryDumpDirectory => Path.Combine(RynthCore.Install.RynthInstallPaths.CoreDir, "Dumps");
/// <summary>
/// Once per process: write a full-memory dump to <see cref="OutOfMemoryDumpDirectory"/>, log
/// its path, and keep only the newest <see cref="OutOfMemoryDumpsKept"/> of these dumps.
/// Called on the thread about to show AC's OUT OF MEMORY box, which waits here until the
/// dump is written (on its own thread, so the showing thread's stack is captured at rest).
/// Never throws.
/// </summary>
internal static void WriteOutOfMemoryDumpOnce(string? reason)
{
if (Interlocked.Exchange(ref _oomDumpLatch, 1) != 0) return;
string why = "AC OUT OF MEMORY box: " + (reason ?? "?");
_fullDumpInProgress = true;
try
{
RynthLog.Error("CrashDump: AC OUT OF MEMORY box opening - writing one full-memory dump before it shows.");
Thread? writer = null;
try
{
writer = new Thread(() => WriteOutOfMemoryDumpCore(why)) { IsBackground = true, Name = "RynthCore.OomDump" };
writer.Start();
}
catch (Exception ex)
{
// No thread to be had (out of memory, after all): write it from this one.
RynthLog.Error($"CrashDump: dump thread failed to start ({ex.GetType().Name}) - writing on the calling thread.");
writer = null;
}
if (writer == null)
WriteOutOfMemoryDumpCore(why);
else if (!writer.Join(FullDumpWaitMs))
RynthLog.Error($"CrashDump: full dump still writing after {FullDumpWaitMs / 1000}s - letting the box open.");
}
catch (Exception ex)
{
RynthLog.Error($"CrashDump: OOM dump failed {ex.GetType().Name}: {ex.Message}");
}
finally
{
_fullDumpInProgress = false;
}
}
private static void WriteOutOfMemoryDumpCore(string reason)
{
try
{
string dir = OutOfMemoryDumpDirectory;
Directory.CreateDirectory(dir);
// Room for the new one first: keep the newest (Kept - 1), so the folder never holds
// more than Kept full dumps even while this one is written.
PruneDumps(dir, OutOfMemoryDumpPrefix, OutOfMemoryDumpsKept - 1);
string path = Path.Combine(dir, $"{OutOfMemoryDumpPrefix}{Environment.ProcessId}_{DateTime.Now:yyyyMMdd_HHmmss}.dmp");
if (WriteDumpFile(path, DumpTypeFull, DumpTypeFullFallback, reason))
{
_fullDumpWrittenPath = path;
RynthLog.Error($"CrashDump: OUT OF MEMORY full-memory dump: {path}");
}
else
{
RynthLog.Error("CrashDump: OUT OF MEMORY full-memory dump FAILED; writing the small hang-type dump instead.");
WriteSelfDump(reason, out _, "oom-small");
}
PruneDumps(dir, OutOfMemoryDumpPrefix, OutOfMemoryDumpsKept);
}
catch (Exception ex)
{
RynthLog.Error($"CrashDump: OOM dump writer failed {ex.GetType().Name}: {ex.Message}");
}
}
/// <summary>Deletes all but the newest <paramref name="keep"/> <paramref name="prefix"/>*.dmp files in <paramref name="dir"/>. Never throws.</summary>
internal static int PruneDumps(string dir, string prefix, int keep)
{
int deleted = 0;
try
{
FileInfo[] files = new DirectoryInfo(dir).GetFiles(prefix + "*.dmp");
Array.Sort(files, (a, b) => b.LastWriteTimeUtc.CompareTo(a.LastWriteTimeUtc));
for (int i = Math.Max(0, keep); i < files.Length; i++)
{
try
{
files[i].Delete();
deleted++;
RynthLog.Info($"CrashDump: pruned old dump {files[i].Name} ({files[i].Length / (1024 * 1024)}MB).");
}
catch { /* in use by a debugger, or already gone */ }
}
}
catch { }
return deleted;
}
}