Engine robustness review fixes: crash-log repeats, teardown reserve, mutator gate, OOM dump safety

Native crash logger
- Per-address slots keep hit counts and a last-write tick; a repeat relogs at powers of
  two, after 30 s, or for any non-AV code. The oldest noise slot is evicted when the
  table is full.
- The logger checks its dedupe first, caches the module table, and opens the log
  handle once at install. Managed-noise bucket (coreclr, clrjit, System.Private.CoreLib).

Main-thread queue
- The action ring (ActionRing) rejects non-teardown work during a world transition and
  reserves its top 32 slots for teardown, so a stop is never lost behind held work.
  IsTeardownKind is shared by the enqueue and drain sides. ActionRing.TryPeekAt lets the
  cast drain's StopQueuedAtOrBefore walk the ring it no longer owns directly; the walk
  now checks every queued entry, since an entry's time is taken before the ring's lock.
- MutatorGate: every AC-mutating helper opens with the same gate,
  AcMainThreadQueue.MustQueue(teardown: X); IsDraining and ShouldDefer added; teardown
  helpers are exempt from the hold. tools\check_offthread_mutators.py accepts MustQueue
  as the gate (it asks MainThreadGuard.IsOnMainThread itself).
- MasteryFeed and VaultFeed pause during a transition. The heading slot drops a stale
  heading; the overlay select is kept.
- RequestId never merges into an entry queued at or before the last transition hold;
  EnqueueRequestId returns false during a transition.
- 0xF751 PlayerTeleport starts the 5 s settle window.
- Cast slot: the queue time and Pending are published with Volatile.Write (a plain 64-bit
  store can tear on x86 and the drain reads both without the lock); the stop-wait flag is
  reset before the publishing store.

Appraisals
- Appraisal data survives a client release for 10 min (bounded at 4096); evicted on
  server delete (0xF747) and at session clear. 0xF747 is detected in SmartBox dispatch,
  independent of capture.

Dumps
- Dump start/end markers in the log; the launcher holds its wedge kill while a dump is
  in progress (DumpInProgressRule). The in-progress flag is cleared only when the writer
  thread exits.
- The OOM dump triggers only on the main thread with AC's exact text, before stacks are
  built. Dumps are pruned only after a successful write, and other live clients' dumps
  are kept. CrashDump reads the file length before Delete.
- ExitProcess/RtlExitUserProcess detours forward crash codes first.
- The message box count is decremented first in a finally; 30 s safety reset when no box
  is visible on the main thread.
- UsageStats counts the loader's CoreCLR fatal-error dumps (Logs\dumps\clr_*.dmp) as
  crashes alongside crash_*.dmp.

Tests: EngineRobustnessTests, CrashLogFilterTests, UsageStatsTests.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Daniel Wallace 2026-10-10 21:32:31 -07:00
commit 8c7201dc25
41 changed files with 1797 additions and 448 deletions

View file

@ -250,10 +250,16 @@ internal static class AcMainThreadQueue
/// Stops and cancels: the teardown group that still runs after a world transition (every
/// other entry queued during one is dropped). Never dropped as stale either.
/// </summary>
private static bool IsTeardown(in Entry e) => e.Kind switch
private static bool IsTeardown(in Entry e) => IsTeardownKind(e.Kind, e.A, e.B);
/// <summary>
/// The ONE teardown predicate: the enqueue side (ActionRing admission, the teardown reserve)
/// and the drain side (which entries survive a world transition) both ask it.
/// </summary>
internal static bool IsTeardownKind(ActionKind kind, uint a, uint b) => kind switch
{
ActionKind.SetAutoRun => e.A == 0,
ActionKind.SetMotion => e.B == 0,
ActionKind.SetAutoRun => a == 0,
ActionKind.SetMotion => b == 0,
ActionKind.StopMovement or ActionKind.StopCompletely or ActionKind.CancelAttack
or ActionKind.CloseContainer => true,
_ => false,
@ -279,38 +285,64 @@ internal static class AcMainThreadQueue
_ => e.Kind.ToString(),
};
// The ring (ActionRing: storage, FIFO, admission). 256 entries, the top 32 for teardown
// only, so a ring a bot filled with starts still takes its stops and cancels.
private const int Capacity = 256; // power of two
private const int Mask = Capacity - 1;
private static readonly Entry[] _slots = new Entry[Capacity];
private static readonly object _producerLock = new();
// Monotonic counters. Producers advance _tail under _producerLock; the sole
// consumer (main thread) advances _head.
private static int _head;
private static int _tail;
private const int TeardownReserve = 32;
private static readonly ActionRing<Entry> _ring = new(Capacity, TeardownReserve);
private static long _dropped;
private static long _transitionRejected;
/// <summary>Entries refused because the ring was full (a running total; the heartbeat's qdrop).</summary>
public static long DroppedCount => Interlocked.Read(ref _dropped);
/// <summary>Non-teardown entries refused while the player was in a world transition.</summary>
public static long TransitionRejectedCount => Interlocked.Read(ref _transitionRejected);
// -- The mutator gate ----------------------------------------------------------
// Every AC-mutating helper (ClientHelperHooks, CombatActionHooks, MovementActionHooks,
// CommandInterpreterHooks, ClientCombatHooks, PlayerPhysicsHooks, PlayerTrade,
// PlayerTraining) opens with the same line:
// if (AcMainThreadQueue.MustQueue(teardown: <is this a stop/cancel>)) return Enqueue...;
// Off AC's main thread it queues (as always). ON the main thread it also queues while a
// world transition holds the drains, unless it is being called BY a drain (IsDraining)
// or is teardown: render-thread host actions (ImGui panels, the EndScene plugin calls)
// used to run straight into a world AC was tearing down, around the gate. The queue
// then refuses or holds it like any other queued work (WorldTransitionState).
private static int _drainDepth; // AC main thread only
/// <summary>AC main thread only: a drain is dispatching queued work right now.</summary>
public static bool IsDraining => _drainDepth > 0;
/// <summary>AC main thread only: a direct call now would run into a world transition.</summary>
public static bool ShouldDefer() => !IsDraining && PlayerLifecycleLog.HoldQueuedWork(NowMs);
/// <summary>
/// The one gate every mutator opens with: true = queue instead of calling AC now.
/// <paramref name="teardown"/>: a stop or cancel (IsTeardownKind), which runs at once on
/// the main thread even in a transition.
/// </summary>
public static bool MustQueue(bool teardown) =>
MutatorGate.MustQueue(MainThreadGuard.IsOnMainThread(), teardown, IsDraining, HoldNow);
// Cached (no allocation per call): main thread only, asked only by MutatorGate on it.
private static readonly Func<bool> HoldNow = () => PlayerLifecycleLog.HoldQueuedWork(NowMs);
private static bool Enqueue(ActionKind kind, uint a, uint b, uint c, uint d = 0)
{
lock (_producerLock)
{
int tail = _tail;
int head = Volatile.Read(ref _head);
if (tail - head >= Capacity)
{
// Full. Drop rather than block or fall back to an off-thread AC
// mutation — a dropped movement/attack tick self-corrects on the
// next bot tick; an off-thread mutation can crash the client.
Interlocked.Increment(ref _dropped);
return false;
}
_slots[tail & Mask] = new Entry(kind, a, b, c, d, NowMs, Volatile.Read(ref _loginEpoch));
Volatile.Write(ref _tail, tail + 1);
return true;
}
bool teardown = IsTeardownKind(kind, a, b);
// Dead / portaling / settling: a start queued now would be dropped when the window
// ends anyway (WorldTransitionState), so it is refused here and never takes a slot a
// stop needs. Stops and cancels are always taken (the reserve keeps room for them).
var r = _ring.TryEnqueue(new Entry(kind, a, b, c, d, NowMs, Volatile.Read(ref _loginEpoch)),
teardown, PlayerLifecycleLog.InWorldTransition);
if (r == ActionRing<Entry>.Admit.Queued) return true;
// Full: drop rather than block or fall back to an off-thread AC mutation - a dropped
// movement/attack tick self-corrects on the next bot tick; an off-thread mutation can
// crash the client.
if (r == ActionRing<Entry>.Admit.Full) Interlocked.Increment(ref _dropped);
else Interlocked.Increment(ref _transitionRejected);
return false;
}
// ── Typed enqueue helpers (called by the public action methods when they
@ -359,19 +391,33 @@ internal static class AcMainThreadQueue
// CommandInterpreter turn, which would change the steering behaviour.
private static int _directHeadingPending;
private static uint _directHeadingBits;
private static long _directHeadingAt;
public static bool EnqueueDirectHeading(float headingDegrees)
{
Volatile.Write(ref _directHeadingBits, BitConverter.SingleToUInt32Bits(headingDegrees));
Interlocked.Exchange(ref _directHeadingAt, NowMs);
Volatile.Write(ref _directHeadingPending, 1);
return true;
}
// Main thread only (from Drain). Same order as the pre-queue code: the direct
// snap first, the CommandInterpreter turn only when there is no player.
// World transition: the pending heading is held; once the window ends a heading set
// during it is stale (the bot steers again from where it landed) and is dropped.
private static void DrainDirectHeading()
{
if (Volatile.Read(ref _directHeadingPending) == 0) return;
long now = NowMs;
long at = Interlocked.Read(ref _directHeadingAt);
WorldTransitionState.Verdict v = PlayerLifecycleLog.DecideQueued(now, at, teardown: false);
if (v == WorldTransitionState.Verdict.Hold) return;
if (Interlocked.Exchange(ref _directHeadingPending, 0) == 0) return;
if (v == WorldTransitionState.Verdict.Drop)
{
NoteTransitionDrop("heading", now - at);
return;
}
float heading = BitConverter.UInt32BitsToSingle(Volatile.Read(ref _directHeadingBits));
try
{
@ -394,18 +440,25 @@ internal static class AcMainThreadQueue
// selects mid-gesture too). Lock-free and allocation-free.
private static int _overlaySelectPending;
private static uint _overlaySelectId;
private static long _overlaySelectAt;
public static bool EnqueueOverlaySelect(uint objectId)
{
if (objectId == 0) return false;
Volatile.Write(ref _overlaySelectId, objectId);
Interlocked.Exchange(ref _overlaySelectAt, NowMs);
Volatile.Write(ref _overlaySelectPending, 1);
return true;
}
// Main thread only (from Drain).
// Main thread only (from Drain). World transition: held, and kept when the window ends:
// it is the user's own click, and SelectFromOverlay re-checks the object still exists.
private static void DrainOverlaySelect()
{
if (Volatile.Read(ref _overlaySelectPending) == 0) return;
if (PlayerLifecycleLog.DecideQueued(NowMs, Interlocked.Read(ref _overlaySelectAt), teardown: true)
== WorldTransitionState.Verdict.Hold)
return;
if (Interlocked.Exchange(ref _overlaySelectPending, 0) == 0) return;
uint id = Volatile.Read(ref _overlaySelectId);
try { ClientHelperHooks.SelectFromOverlay(id); }
@ -514,6 +567,14 @@ internal static class AcMainThreadQueue
private static long _drainDeferSinceMs;
public static void Drain()
{
// IsDraining: the helpers this dispatches run their AC call directly (MustQueue).
_drainDepth++;
try { DrainCore(); }
finally { _drainDepth--; }
}
private static void DrainCore()
{
if (_disarmed)
{
@ -573,22 +634,14 @@ internal static class AcMainThreadQueue
// Plugin heading snap (coalesced slot). Before the ring and its gesture
// defer: the pre-queue raw write landed immediately, gesture or not, and
// ahead of the SetAutoRun a nav tick queues right after it. Keep both.
// Both are latest-value slots (a heading, a select): in a world transition the
// pending value is discarded, never applied late in the next world.
if (holding)
{
if (Interlocked.Exchange(ref _directHeadingPending, 0) != 0) NoteTransitionDrop("heading", 0);
if (Interlocked.Exchange(ref _overlaySelectPending, 0) != 0) NoteTransitionDrop("overlay select", 0);
}
// Both are latest-value slots (a heading, a select): held through a world transition,
// then decided by their own drains (a stale heading dropped, a user's select kept).
DrainDirectHeading();
// Overlay click-to-select (Radar dot / nameplate click): also before the
// gesture defer, so a click selects at once even while the bot swings.
DrainOverlaySelect();
int head = _head; // only the main thread writes _head
int tail = Volatile.Read(ref _tail);
// In a world transition the ring is held whole (FIFO kept): nothing runs, nothing is
// dropped yet. Once it ends, the loop below drops what was queued during it, except
// stops and cancels, which run in order as one teardown group.
@ -607,7 +660,7 @@ internal static class AcMainThreadQueue
// drop: dropping arbitrary item/movement actions desyncs the bot far
// worse than a late injection, and the pre-2026-06-12 behavior was
// "always inject" anyway, so proceeding past the cap is never worse).
if (head != tail)
if (_ring.Count > 0)
{
// In milliseconds (was 250 Drain calls: 2 s to over 10 s depending on the frame rate).
if (PlayerPhysicsHooks.TryGetCastGestureInProgress(out bool gestureInFlight) && gestureInFlight)
@ -621,22 +674,20 @@ internal static class AcMainThreadQueue
}
long runAt = NowMs;
int epochNow = Volatile.Read(ref _loginEpoch);
while (head != tail)
// Bounded to what is queued now plus a capacity's worth: an action that re-queues
// itself can never spin the main thread.
int budget = Capacity * 2;
while (budget-- > 0 && _ring.TryDequeue(out Entry e))
{
Entry e = _slots[head & Mask];
Volatile.Write(ref _head, ++head);
long age = runAt - e.At;
if (PlayerLifecycleLog.DecideQueued(runAt, e.At, IsTeardown(e)) == WorldTransitionState.Verdict.Drop)
{
NoteTransitionDrop(Describe(e), age);
tail = Volatile.Read(ref _tail);
continue;
}
if (e.Epoch != epochNow || (age > StaleActionMs && DropsWhenStale(e)))
{
NoteStale(Describe(e) + (e.Epoch != epochNow ? " (queued before this login)" : ""), age, dropped: true);
tail = Volatile.Read(ref _tail);
continue;
}
if (age > LateActionLogMs)
@ -770,8 +821,6 @@ internal static class AcMainThreadQueue
// not managed exceptions and won't be caught here — but these
// now run on the correct thread, which is the whole point.)
}
tail = Volatile.Read(ref _tail);
}
}
@ -804,9 +853,16 @@ internal static class AcMainThreadQueue
public static bool EnqueueRequestId(uint objectId)
{
if (objectId == 0) return false;
// Dead / portaling / settling: an appraisal queued now is dropped when the window
// ends, so it is refused here (the caller sees false and may ask again later). Nor
// does a request merge into an entry from before the last held drain: that entry is
// dropped when the drain reaches it, and the merged request would go with it.
if (PlayerLifecycleLog.InWorldTransition) return false;
long mergeOnlyAfter = PlayerLifecycleLog.LastBlockedMs;
lock (_requestIdLock)
{
PendingIdQueue.Result r = _requestIdQueue.Enqueue(objectId, NowMs, Volatile.Read(ref _loginEpoch), RequestIdMergeMaxAgeMs);
PendingIdQueue.Result r = _requestIdQueue.Enqueue(objectId, NowMs, Volatile.Read(ref _loginEpoch),
RequestIdMergeMaxAgeMs, mergeOnlyAfter);
if (r == PendingIdQueue.Result.Full)
{
Interlocked.Increment(ref _dropped);
@ -1067,9 +1123,12 @@ internal static class AcMainThreadQueue
if (_castPending != 0) return false;
_castTargetId = targetId;
_castSpellId = spellId;
_castQueuedAt = NowMs;
// 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;
_castPending = 1;
Volatile.Write(ref _castPending, 1);
return true;
}
}
@ -1092,27 +1151,25 @@ internal static class AcMainThreadQueue
/// <summary>
/// True when the action ring holds a movement stop queued at or before <paramref name="castQueuedAt"/>.
/// Main thread only (the ring's sole consumer). Entries are stamped under the producer lock, so
/// their times rise from head to tail and the walk stops at the first newer one.
/// Main thread only (the ring's sole consumer). An entry's time is taken before ActionRing's
/// producer lock, so two producers can land slightly out of time order: the walk checks every
/// queued entry (at most Capacity) instead of stopping at the first newer one (CastStopRules).
/// </summary>
private static bool StopQueuedAtOrBefore(long castQueuedAt)
{
int head = _head;
int tail = Volatile.Read(ref _tail);
for (int i = head; i != tail; i++)
{
ref readonly Entry e = ref _slots[i & Mask];
if (e.At > castQueuedAt) return false;
if (IsMovementStop(e)) return true;
}
return false;
}
private static bool StopQueuedAtOrBefore(long castQueuedAt) =>
CastStopRules.AnyStopAtOrBefore(_ring, castQueuedAt, static e => e.At, static e => IsMovementStop(e));
// Drained on AC's MAIN thread from the Client::UseTime detour (game-logic tick).
// Re-invokes CombatActionHooks.CastSpell, which on the main thread executes the
// cast directly via the SEH trampoline (targeted: FreeHandsAndCastSpell with the target
// passed explicitly, no SelectItem; self: ClientMagicSystem::CastSpell).
public static void DrainCasts()
{
_drainDepth++;
try { DrainCastsCore(); }
finally { _drainDepth--; }
}
private static void DrainCastsCore()
{
if (_disarmed) return; // engine teardown in progress
if (Volatile.Read(ref _castPending) == 0) return; // alloc-free fast path

View file

@ -0,0 +1,123 @@
// ============================================================================
// RynthCore.Engine - Compatibility/ActionRing.cs
//
// The storage and admission policy of AcMainThreadQueue's action ring: a fixed ring of
// entries, many producers (under one lock), ONE consumer (AC's main thread), FIFO.
//
// Admission: during a world transition the drain holds the ring
// (WorldTransitionState), and a bot keeps queueing starts at ~60 Hz meanwhile, so the
// ring used to fill and then refuse the stops and cancels that matter most. Now:
// - while the caller says a transition is on, non-teardown entries are refused at
// once (they would be dropped when it ends anyway);
// - the top TeardownReserve slots only take teardown entries (stops and cancels), so a
// ring filled by starts before the transition was seen still takes a stop.
// What counts as teardown is the caller's (AcMainThreadQueue.IsTeardownKind, the same
// predicate its drain uses).
//
// Pure: no engine state. Compiled into tools\EngineRobustnessTests.
// ============================================================================
using System.Threading;
namespace RynthCore.Engine.Compatibility;
internal sealed class ActionRing<T> where T : struct
{
public enum Admit
{
Queued,
/// <summary>No room (for a non-teardown entry: none below the teardown reserve).</summary>
Full,
/// <summary>A world transition is on and the entry is not teardown.</summary>
RejectedTransition,
}
private readonly T[] _slots;
private readonly int _mask;
private readonly int _reserve;
private readonly object _lock = new();
// Monotonic counters. Producers advance _tail under _lock; the sole consumer advances _head.
private int _head;
private int _tail;
public ActionRing(int capacityPowerOfTwo, int teardownReserve)
{
if (capacityPowerOfTwo <= 0 || (capacityPowerOfTwo & (capacityPowerOfTwo - 1)) != 0)
throw new System.ArgumentOutOfRangeException(nameof(capacityPowerOfTwo));
if (teardownReserve < 0 || teardownReserve >= capacityPowerOfTwo)
throw new System.ArgumentOutOfRangeException(nameof(teardownReserve));
_slots = new T[capacityPowerOfTwo];
_mask = capacityPowerOfTwo - 1;
_reserve = teardownReserve;
}
public int Capacity => _slots.Length;
public int TeardownReserve => _reserve;
/// <summary>Entries waiting (any thread; a snapshot).</summary>
public int Count => Volatile.Read(ref _tail) - Volatile.Read(ref _head);
/// <summary>Producer side, any thread.</summary>
public Admit TryEnqueue(in T entry, bool teardown, bool inTransition)
{
lock (_lock)
{
if (inTransition && !teardown)
return Admit.RejectedTransition;
int tail = _tail;
int used = tail - Volatile.Read(ref _head);
int limit = teardown ? _slots.Length : _slots.Length - _reserve;
if (used >= limit)
return Admit.Full;
_slots[tail & _mask] = entry;
Volatile.Write(ref _tail, tail + 1);
return Admit.Queued;
}
}
/// <summary>Consumer only: the oldest entry, without removing it.</summary>
public bool TryPeek(out T entry)
{
int head = _head;
if (head == Volatile.Read(ref _tail))
{
entry = default;
return false;
}
entry = _slots[head & _mask];
return true;
}
/// <summary>
/// Consumer only: the entry <paramref name="offset"/> places behind the oldest (0 = the
/// oldest), without removing anything. False past the newest entry.
/// </summary>
public bool TryPeekAt(int offset, out T entry)
{
int head = _head;
if (offset < 0 || offset >= Volatile.Read(ref _tail) - head)
{
entry = default;
return false;
}
entry = _slots[(head + offset) & _mask];
return true;
}
/// <summary>Consumer only: removes the oldest entry (after a successful TryPeek).</summary>
public void Pop()
{
int head = _head;
if (head == Volatile.Read(ref _tail)) return;
_slots[head & _mask] = default;
Volatile.Write(ref _head, head + 1);
}
/// <summary>Consumer only: removes and returns the oldest entry.</summary>
public bool TryDequeue(out T entry)
{
if (!TryPeek(out entry)) return false;
Pop();
return true;
}
}

View file

@ -80,6 +80,9 @@ internal static class AppraisalHooks
// Spell book cache: guid → spell ID array (from AppraisalProfile._spellBook PSmartArray<UInt32> at +0x30)
private static readonly Dictionary<uint, uint[]> _spellIdCache = new();
private static readonly object _cacheLock = new();
// Objects the CLIENT released, whose data is kept a while (ReleasedObjectRetention).
private static readonly ReleasedObjectRetention _released = new();
private static readonly List<uint> _expiredScratch = new();
public static bool IsInstalled => _hookInstalled;
public static string StatusMessage => _statusMessage;
@ -114,19 +117,64 @@ internal static class AppraisalHooks
_bags.Clear();
_spellIdCache.Clear();
_failedRollLogged.Clear();
_released.Clear();
}
}
/// <summary>Drops everything cached for an object AC deleted (PropertyUpdateHooks' BeingDeleted hook).</summary>
/// <summary>
/// Drops everything cached for an object: the SERVER deleted it (0xF747, SmartBoxHooks /
/// ServerMessageStream), or its kept-after-release time ran out. Any thread.
/// </summary>
public static void EvictObject(uint guid)
{
lock (_cacheLock)
EvictLocked(guid);
}
// Caller holds _cacheLock.
private static void EvictLocked(uint guid)
{
_appraisedGuids.Remove(guid);
_lastIdTime.Remove(guid);
_bags.Remove(guid);
_spellIdCache.Remove(guid);
_failedRollLogged.Remove(guid);
_released.Forget(guid);
}
/// <summary>
/// The CLIENT released an object (AC's BeingDeleted: it left the client's view). Its data is
/// kept for ReleasedObjectRetention.RetainMs, so a re-create inside that time still finds it
/// (AutoId then skips the re-appraisal). Main thread (the BeingDeleted detour).
/// </summary>
public static void OnClientRelease(uint guid, long nowMs)
{
lock (_cacheLock)
{
_appraisedGuids.Remove(guid);
_lastIdTime.Remove(guid);
_bags.Remove(guid);
_spellIdCache.Remove(guid);
_failedRollLogged.Remove(guid);
if (!_appraisedGuids.Contains(guid) && !_bags.ContainsKey(guid)) return;
if (!_released.OnRelease(guid, nowMs))
EvictLocked(guid); // the kept-released bound is full: drop it now
}
}
/// <summary>The object was created again: its data is current, not merely kept.</summary>
public static void MarkLive(uint guid)
{
lock (_cacheLock)
_released.Forget(guid);
}
/// <summary>Drops the data of objects released longer ago than the retention time. Timer thread.</summary>
public static int ExpireReleased(long nowMs)
{
lock (_cacheLock)
{
_expiredScratch.Clear();
int n = _released.Expire(nowMs, _expiredScratch);
foreach (uint g in _expiredScratch)
EvictLocked(g);
_expiredScratch.Clear();
return n;
}
}
@ -150,10 +198,7 @@ internal static class AppraisalHooks
if (t < oldestTime) { oldestTime = t; oldest = g; }
}
if (oldest == 0) return;
_bags.Remove(oldest);
_appraisedGuids.Remove(oldest);
_lastIdTime.Remove(oldest);
_spellIdCache.Remove(oldest);
EvictLocked(oldest);
}
}

View file

@ -68,6 +68,9 @@ internal sealed class AutoIdEligibility
public int MaxTracked => _maxTracked;
public long WindowMs => _windowMs;
/// <summary>Re-creates skipped because the last appraisal is recent and still cached.</summary>
public long SkippedRecentTotal { get; private set; }
/// <summary>Creates admitted while the map was full (appraised, not tracked).</summary>
public long UntrackedAdmits { get; private set; }
@ -84,7 +87,12 @@ internal sealed class AutoIdEligibility
e.Live = true;
bool recent = e.LastSentMs != 0 && nowMs - e.LastSentMs < _windowMs;
_map[id] = e;
return recent && appraisalCached ? CreateDecision.SkipRecent : CreateDecision.Appraise;
if (recent && appraisalCached)
{
SkippedRecentTotal++;
return CreateDecision.SkipRecent;
}
return CreateDecision.Appraise;
}
if (_map.Count >= _maxTracked)

View file

@ -44,10 +44,13 @@ internal static class AutoIdService
private static Timer? _drainTimer;
private static bool _started;
private static long _skippedRecent, _skippedPriorityFresh;
private static long _skippedPriorityFresh;
/// <summary>Re-creates not appraised because a recent appraisal is still cached.</summary>
public static long SkippedRecentCount => Interlocked.Read(ref _skippedRecent);
public static long SkippedRecentCount
{
get { lock (_gate) return _eligibility.SkippedRecentTotal; }
}
/// <summary>Selected-target priority appraisals skipped because the target's data is cached and fresh.</summary>
public static long SkippedPriorityFreshCount => Interlocked.Read(ref _skippedPriorityFresh);
@ -89,6 +92,9 @@ internal static class AutoIdService
if (playerId != 0 && objectId == playerId)
return;
// Created again: data kept since a client release is current again (and still cached
// if the release was inside ReleasedObjectRetention's time).
AppraisalHooks.MarkLive(objectId);
bool cached = AppraisalHooks.HasAppraisalData(objectId);
AutoIdEligibility.CreateDecision decision;
lock (_gate)
@ -96,8 +102,6 @@ internal static class AutoIdService
if (decision == AutoIdEligibility.CreateDecision.Appraise)
_queue.Enqueue(objectId);
else if (decision == AutoIdEligibility.CreateDecision.SkipRecent)
Interlocked.Increment(ref _skippedRecent);
}
/// <summary>
@ -121,6 +125,8 @@ internal static class AutoIdService
if (objectId == 0) return;
lock (_gate)
_eligibility.OnServerDelete(objectId);
// It really went away: its kept identify data goes too.
AppraisalHooks.EvictObject(objectId);
}
/// <summary>
@ -144,6 +150,10 @@ internal static class AutoIdService
{
if (!CombatActionHooks.HasRequestId)
return;
// Dead / portaling / settling: AcMainThreadQueue refuses appraisals now, so the
// backlog waits here instead of being dequeued into a refusal and lost.
if (PlayerLifecycleLog.InWorldTransition)
return;
long now = Environment.TickCount64;
int sent = 0;
@ -206,6 +216,10 @@ internal static class AutoIdService
removed = _eligibility.Count > _eligibility.MaxTracked / 2 ? _eligibility.Prune(now) : 0;
if (removed > 0)
RynthLog.Verbose($"Compat: AutoIdService pruned {removed} appraisal record(s).");
// Identify data kept after a client release: dropped once its time is up.
int expired = AppraisalHooks.ExpireReleased(now);
if (expired > 0)
RynthLog.Verbose($"Compat: AppraisalHooks dropped {expired} released object(s) past the retention time.");
}
}
catch { }

View file

@ -0,0 +1,38 @@
// ============================================================================
// RynthCore.Engine - Compatibility/CastStopRules.cs
//
// The cast drain's question about the action ring: is a movement stop queued at or
// before the pending cast? (AcMainThreadQueue.StopQueuedAtOrBefore: such a stop runs
// first, so the cast's own stop is not sent while AC's locomotion is still on.)
//
// Every queued entry is checked. An entry's time is taken before ActionRing's producer
// lock, so two producers can land slightly out of time order, and a walk that stopped
// at the first entry newer than the cast could miss an older stop queued behind it.
//
// Pure: no engine state. Consumer side of the ring only (AC's main thread). Compiled
// into tools\EngineRobustnessTests.
// ============================================================================
using System;
namespace RynthCore.Engine.Compatibility;
internal static class CastStopRules
{
/// <summary>
/// True when any entry in <paramref name="ring"/> was queued at or before
/// <paramref name="castQueuedAt"/> (by <paramref name="queuedAt"/>) and is a movement stop
/// (by <paramref name="isStop"/>). Pass static lambdas: nothing is allocated per call.
/// </summary>
public static bool AnyStopAtOrBefore<T>(ActionRing<T> ring, long castQueuedAt,
Func<T, long> queuedAt, Func<T, bool> isStop) where T : struct
{
int count = ring.Count;
for (int i = 0; i < count; i++)
{
if (!ring.TryPeekAt(i, out T e)) break;
if (queuedAt(e) <= castQueuedAt && isStop(e)) return true;
}
return false;
}
}

View file

@ -177,7 +177,7 @@ internal static class ClientCombatHooks
// MeleeAttack/MissileAttack, this ran un-marshalled every fight. Marshal
// as ONE queue entry (not split into four) so the sequence stays atomic
// relative to the drain loop's other actions.
if (!MainThreadGuard.IsOnMainThread())
if (AcMainThreadQueue.MustQueue(teardown: false))
return AcMainThreadQueue.EnqueueNativeAttack(attackHeight, power);
try

View file

@ -371,7 +371,7 @@ internal static class ClientHelperHooks
// (every UseObject/MoveItem/cast sibling already marshals). Drain re-invokes
// this on the main thread, where the gate is satisfied and it runs directly.
// SelectItem() funnels through here, so this one gate covers both.
if (!MainThreadGuard.IsOnMainThread())
if (AcMainThreadQueue.MustQueue(teardown: false))
return AcMainThreadQueue.EnqueueSetSelectedObject(objectId);
if (_setSelectedObject == null)
@ -400,7 +400,7 @@ internal static class ClientHelperHooks
/// </summary>
public static bool SelectFromOverlay(uint objectId)
{
if (!MainThreadGuard.IsOnMainThread())
if (AcMainThreadQueue.MustQueue(teardown: false))
return AcMainThreadQueue.EnqueueOverlaySelect(objectId);
if (objectId == 0 || _setSelectedObject == null)
@ -433,7 +433,7 @@ internal static class ClientHelperHooks
// main thread (via the OnEndScene drain), not off the pump thread. Off-thread
// UseObject mutated AC's animation sequence (CSequence) and corrupted it ->
// the CSequence::update_internal AV captured after looting was enabled.
if (!MainThreadGuard.IsOnMainThread())
if (AcMainThreadQueue.MustQueue(teardown: false))
return AcMainThreadQueue.EnqueueUseObject(objectId);
if (_useObject == null || !IsValidObjectId(objectId))
@ -466,7 +466,7 @@ internal static class ClientHelperHooks
// Marshal onto AC's main thread (off-thread use-on-target mutates AC's
// object/animation graph and corrupts it — see UseObject). Drain re-invokes
// this on the main thread, where the gate is satisfied and it runs directly.
if (!MainThreadGuard.IsOnMainThread())
if (AcMainThreadQueue.MustQueue(teardown: false))
return AcMainThreadQueue.EnqueueUseObjectOn(sourceObjectId, targetObjectId);
if (_useWithTargetEvent == null || !IsValidObjectId(sourceObjectId) || !IsValidObjectId(targetObjectId))
@ -492,7 +492,7 @@ internal static class ClientHelperHooks
public static bool UseEquippedItem(uint sourceObjectId, uint targetObjectId)
{
if (!MainThreadGuard.IsOnMainThread())
if (AcMainThreadQueue.MustQueue(teardown: false))
return AcMainThreadQueue.EnqueueUseEquippedItem(sourceObjectId, targetObjectId);
if (_useEquippedItem == null || !IsValidObjectId(sourceObjectId) || !IsValidObjectId(targetObjectId))
@ -517,7 +517,7 @@ internal static class ClientHelperHooks
{
// Marshal onto AC's main thread — off-thread item moves race AC's per-tick
// object/container bookkeeping (the looting null-deref AV class).
if (!MainThreadGuard.IsOnMainThread())
if (AcMainThreadQueue.MustQueue(teardown: false))
return AcMainThreadQueue.EnqueueMoveItemExternal(objectId, targetContainerId, amount);
if (_moveItemExternal == null || !IsValidObjectId(objectId) || !IsValidContainerId(targetContainerId) || amount < 0)
@ -547,7 +547,7 @@ internal static class ClientHelperHooks
public static bool MoveItemInternal(uint objectId, uint targetContainerId, int slot, int amount)
{
if (!MainThreadGuard.IsOnMainThread())
if (AcMainThreadQueue.MustQueue(teardown: false))
return AcMainThreadQueue.EnqueueMoveItemInternal(objectId, targetContainerId, slot, amount);
if (_moveItemInternal == null) return false;
@ -604,7 +604,7 @@ internal static class ClientHelperHooks
/// </summary>
public static bool SplitStackInternal(uint objectId, uint targetContainerId, int slot, int amount)
{
if (!MainThreadGuard.IsOnMainThread())
if (AcMainThreadQueue.MustQueue(teardown: false))
return AcMainThreadQueue.EnqueueSplitStackInternal(objectId, targetContainerId, slot, amount);
if (_moveItemInternal == null) return false;
@ -656,7 +656,7 @@ internal static class ClientHelperHooks
/// </summary>
public static bool MergeStackInternal(uint sourceObjectId, uint targetObjectId)
{
if (!MainThreadGuard.IsOnMainThread())
if (AcMainThreadQueue.MustQueue(teardown: false))
return AcMainThreadQueue.EnqueueMergeStackInternal(sourceObjectId, targetObjectId);
if (_eventStackableMerge == null) return false;
@ -714,7 +714,7 @@ internal static class ClientHelperHooks
/// </summary>
public static bool PutItemInContainerAt(uint objectId, uint containerId, int slot)
{
if (!MainThreadGuard.IsOnMainThread())
if (AcMainThreadQueue.MustQueue(teardown: false))
return AcMainThreadQueue.EnqueuePutItemInContainer(objectId, containerId, slot);
if (_eventPutItemInContainer == null) return false;
@ -749,7 +749,7 @@ internal static class ClientHelperHooks
// Marshal onto AC's main thread — off-thread F7B1 inventory sends race AC's
// per-tick object/container bookkeeping (the looting null-deref AV class),
// exactly like MoveItemExternal / MergeStackInternal.
if (!MainThreadGuard.IsOnMainThread())
if (AcMainThreadQueue.MustQueue(teardown: false))
return AcMainThreadQueue.EnqueueGiveObjectTo(objectId, targetId, amount);
if (_eventGiveObjectRequest == null) return false;
@ -795,7 +795,7 @@ internal static class ClientHelperHooks
public static bool WieldItem(uint objectId, uint equipMask)
{
// Inventory sends run on AC's main thread, like MoveItemExternal / GiveObjectTo.
if (!MainThreadGuard.IsOnMainThread())
if (AcMainThreadQueue.MustQueue(teardown: false))
return _eventGetAndWieldItem != null && IsValidObjectId(objectId) && equipMask != 0
&& AcMainThreadQueue.EnqueueWieldItem(objectId, equipMask);
@ -825,7 +825,7 @@ internal static class ClientHelperHooks
public static bool DropItem(uint objectId)
{
// Inventory sends run on AC's main thread, like WieldItem / GiveObjectTo.
if (!MainThreadGuard.IsOnMainThread())
if (AcMainThreadQueue.MustQueue(teardown: false))
return _eventDropItem != null && IsValidObjectId(objectId)
&& AcMainThreadQueue.EnqueueDropItem(objectId);
@ -859,7 +859,7 @@ internal static class ClientHelperHooks
public static bool CloseContainer(uint containerId)
{
// An inventory game-action send, like DropItem / WieldItem: main thread only.
if (!MainThreadGuard.IsOnMainThread())
if (AcMainThreadQueue.MustQueue(teardown: true))
return _eventNoLongerViewingContents != null && IsValidObjectId(containerId)
&& AcMainThreadQueue.EnqueueCloseContainer(containerId);
@ -1151,7 +1151,7 @@ internal static class ClientHelperHooks
// same class as the SetSelectedObject 0x60D1D AV. The ring is FIFO with
// one consumer, so open -> add -> execute keep their order. Drain calls
// back into this method on the main thread, where the gate is satisfied.
if (!MainThreadGuard.IsOnMainThread())
if (AcMainThreadQueue.MustQueue(teardown: false))
return AcMainThreadQueue.EnqueueSalvageOpen(toolId);
try
@ -1193,7 +1193,7 @@ internal static class ClientHelperHooks
// queued entry carries only the item id: on the main thread this method
// runs again and re-reads the instance, since the panel may have closed
// or been rebuilt in between.
if (!MainThreadGuard.IsOnMainThread())
if (AcMainThreadQueue.MustQueue(teardown: false))
return AcMainThreadQueue.EnqueueSalvageAddItem(itemId);
try
@ -1228,7 +1228,7 @@ internal static class ClientHelperHooks
// Off-thread: same shape as SalvagePanelAddItem (instance re-read on the
// main thread when the entry drains).
if (!MainThreadGuard.IsOnMainThread())
if (AcMainThreadQueue.MustQueue(teardown: false))
return AcMainThreadQueue.EnqueueSalvageExecute();
try

View file

@ -332,7 +332,7 @@ internal static class CombatActionHooks
public static bool MeleeAttack(uint targetId, int attackHeight, float powerLevel)
{
if (!MainThreadGuard.IsOnMainThread())
if (AcMainThreadQueue.MustQueue(teardown: false))
return AcMainThreadQueue.EnqueueMeleeAttack(targetId, attackHeight, powerLevel);
if (_meleeAttack == null)
@ -350,7 +350,7 @@ internal static class CombatActionHooks
public static bool MissileAttack(uint targetId, int attackHeight, float accuracyLevel)
{
if (!MainThreadGuard.IsOnMainThread())
if (AcMainThreadQueue.MustQueue(teardown: false))
return AcMainThreadQueue.EnqueueMissileAttack(targetId, attackHeight, accuracyLevel);
if (_missileAttack == null)
@ -373,7 +373,7 @@ internal static class CombatActionHooks
// (CSequence) state on the thread that updates it — eliminating the
// off-thread-mutation corruption class (e.g. the CSequence::update_internal
// AV). On the main thread (incl. the drain) this executes directly.
if (!MainThreadGuard.IsOnMainThread())
if (AcMainThreadQueue.MustQueue(teardown: false))
return AcMainThreadQueue.EnqueueChangeCombatMode(combatMode);
// Prefer the CLIENT-level entry point. _changeCombatMode is bound by
@ -412,7 +412,7 @@ internal static class CombatActionHooks
// same gate. Queued in the action ring so it keeps FIFO order after an attack
// that is already queued (it used to run at once and could overtake it). The
// drain re-enters here on the main thread, where the gate passes.
if (!MainThreadGuard.IsOnMainThread())
if (AcMainThreadQueue.MustQueue(teardown: true))
return AcMainThreadQueue.EnqueueCancelAttack();
try
@ -435,7 +435,7 @@ internal static class CombatActionHooks
// so off-thread calls go to the non-gesture QueryHealth queue and the drain
// re-enters here on the main thread. Callers ignore the result and read the
// async 0x01C0 reply, so "queued" is enough.
if (!MainThreadGuard.IsOnMainThread())
if (AcMainThreadQueue.MustQueue(teardown: false))
return targetId != 0 && AcMainThreadQueue.EnqueueQueryHealth(targetId);
try
@ -461,7 +461,7 @@ internal static class CombatActionHooks
// here on the main thread, where this gate passes and the packet is sent.
// Fire-and-forget: the appraisal reply is async anyway, so "queued" keeps
// the bool's meaning ("requested").
if (!MainThreadGuard.IsOnMainThread())
if (AcMainThreadQueue.MustQueue(teardown: false))
return AcMainThreadQueue.EnqueueRequestId(objectId);
try
@ -504,7 +504,7 @@ internal static class CombatActionHooks
// which the drain-before order is intended to fix. On the main thread (the
// UseTime drain, or any main-thread caller) this falls through to the direct
// cast below.
if (!MainThreadGuard.IsOnMainThread())
if (AcMainThreadQueue.MustQueue(teardown: false))
return AcMainThreadQueue.EnqueueCast(targetId, (uint)spellId);
// From here on we are ON AC's main thread: the Client::UseTime cast drain

View file

@ -163,7 +163,7 @@ internal static class CommandInterpreterHooks
// motion graph the CSequence-AV corruption class kills. Off-thread
// callers marshal through the action ring (drained post-tick,
// gesture-gated) like every other mutator.
if (!MainThreadGuard.IsOnMainThread())
if (AcMainThreadQueue.MustQueue(teardown: !enabled))
return AcMainThreadQueue.EnqueueSetAutoRun(enabled);
int n = System.Threading.Interlocked.Increment(ref _setAutoRunCalls);
if (!TryBindDelegates())
@ -269,7 +269,7 @@ internal static class CommandInterpreterHooks
public static bool SetMotion(uint motion, bool enabled)
{
if (!MainThreadGuard.IsOnMainThread())
if (AcMainThreadQueue.MustQueue(teardown: !enabled))
return AcMainThreadQueue.EnqueueSetMotion(motion, enabled); // same off-thread class as SetAutoRun
if (!TryBindDelegates() || _setMotion == null)
return false;
@ -287,7 +287,7 @@ internal static class CommandInterpreterHooks
public static bool StopCompletely()
{
if (!MainThreadGuard.IsOnMainThread())
if (AcMainThreadQueue.MustQueue(teardown: true))
return AcMainThreadQueue.EnqueueStopCompletely(); // same off-thread class as SetAutoRun
if (!TryBindDelegates() || _stopCompletely == null)
return false;
@ -305,7 +305,7 @@ internal static class CommandInterpreterHooks
public static bool TurnToHeading(float headingDegrees)
{
if (!MainThreadGuard.IsOnMainThread())
if (AcMainThreadQueue.MustQueue(teardown: false))
return AcMainThreadQueue.EnqueueTurnToHeading(headingDegrees); // same off-thread class as SetAutoRun
int n = System.Threading.Interlocked.Increment(ref _turnToHeadingCalls);
if (!TryBindDelegates() || _turnToHeading == null)
@ -398,7 +398,7 @@ internal static class CommandInterpreterHooks
public static bool TapJump()
{
if (!MainThreadGuard.IsOnMainThread())
if (AcMainThreadQueue.MustQueue(teardown: false))
return AcMainThreadQueue.EnqueueTapJump();
if (!TryBindDelegates())
return false;
@ -419,7 +419,7 @@ internal static class CommandInterpreterHooks
public static bool CommenceJump()
{
if (!MainThreadGuard.IsOnMainThread())
if (AcMainThreadQueue.MustQueue(teardown: false))
return AcMainThreadQueue.EnqueueCommenceJump();
if (!TryBindDelegates())
return false;
@ -437,7 +437,7 @@ internal static class CommandInterpreterHooks
public static bool DoJump(bool autonomous)
{
if (!MainThreadGuard.IsOnMainThread())
if (AcMainThreadQueue.MustQueue(teardown: false))
return AcMainThreadQueue.EnqueueDoJumpAutonomous(autonomous);
if (!TryBindDelegates())
return false;

View file

@ -166,6 +166,14 @@ internal static class HeartbeatLogger
if (largest >= 0) vaField += $" valargest={largest}MB";
}
catch { }
// Crash logger module cache (native): rebuilt every 10 s here, so a fault
// never has to call the loader to name a module.
if (tick % 10 == 1)
{
try { SehTrampoline.RefreshCrashLoggerModules(); } catch { }
}
// Safety net for the main-thread message box count (MainThreadFreeze).
MessageBoxHooks.ReconcileStaleMainThreadCount();
// pump=paused = plugin ticks paused because AC's main thread is frozen
// (MainThreadFreeze); omitted while running.
try { if (MainThreadFreeze.Paused) vaField += $" pump=paused stall={MainThreadFreeze.MainThreadStallMs}ms"; }

View file

@ -117,10 +117,15 @@ internal static class MainThreadSnapshots
try { PlayerProgressHooks.Prefetch(); } catch { }
}
// Aelrynth skill mastery: the /mastery-data request after login, on panel open
// and after a raise (only on Aelrynth; a few compares when nothing is wanted).
try { MasteryFeed.MainThreadTick(playerLive); } catch { }
// Aelrynth account vault (the Inventory panel's Vault view): reads on request only.
try { VaultFeed.MainThreadTick(playerLive); } catch { }
// Both send server commands (a mastery raise, a vault withdraw), so like the
// Inventory panel they wait out a world transition; their requests stay pending.
if (!PlayerLifecycleLog.InWorldTransition)
{
// Aelrynth skill mastery: the /mastery-data request after login, on panel open
// and after a raise (only on Aelrynth; a few compares when nothing is wanted).
try { MasteryFeed.MainThreadTick(playerLive); } catch { }
// Aelrynth account vault (the Inventory panel's Vault view): reads on request only.
try { VaultFeed.MainThreadTick(playerLive); } catch { }
}
}
}

View file

@ -59,8 +59,6 @@ internal static class MessageBoxHooks
/// <summary>Message boxes open right now on AC's main thread. Any thread.</summary>
public static int MainThreadOpenCount => Volatile.Read(ref _mainThreadOpenCount);
/// <summary>The text AC's out-of-memory box carries ("OUT OF MEMORY: Failed to allocate N bytes.").</summary>
internal const string OutOfMemoryMarker = "OUT OF MEMORY";
public static void Initialize()
{
@ -123,47 +121,58 @@ internal static class MessageBoxHooks
{
MessageBoxDelegate? original = wide ? _originalW : _originalA;
string? description = null;
bool mainThread = false;
bool counted = false;
long opened = Environment.TickCount64;
int result = 0;
try
{
description = Opened(text, caption, type, wide, out mainThread, out bool outOfMemory);
// AC's OUT OF MEMORY box is modal: the process never crashes, so Windows never
// writes a dump, and the launcher later kills the client as wedged. Write ONE
// full-memory dump now, before the box shows (blocking this thread until it is
// written: the box would hold it anyway, and the user's OK must not let AC run on
// and exit mid-dump).
if (outOfMemory)
CrashDump.WriteOutOfMemoryDumpOnce(description);
}
catch { /* observation only: never block the dialog */ }
int result = original != null ? original(hWnd, text, caption, type) : 0;
try
{
long secs = (Environment.TickCount64 - opened) / 1000;
RynthLog.Info($"MessageBoxHooks: closed after {secs}s (result={result}): {description ?? "?"}");
if (mainThread && Interlocked.Decrement(ref _mainThreadOpenCount) < 0)
Interlocked.Exchange(ref _mainThreadOpenCount, 0);
if (Interlocked.Decrement(ref _openCount) <= 0)
try
{
Interlocked.Exchange(ref _openCount, 0);
_openDescription = null;
// Counted first: the freeze gate must see the box even if the rest throws.
bool mainThread = MainThreadGuard.IsOnMainThread();
if (mainThread)
{
Interlocked.Increment(ref _mainThreadOpenCount);
counted = true;
}
string body = Read(text, wide);
// AC's OUT OF MEMORY box is modal: the process never crashes, so Windows never
// writes a dump, and the launcher later kills the client as wedged. Decide and
// write ONE full-memory dump now, before anything here allocates more (the stack
// walk and the description below), and before the box shows (this thread waits:
// the box would hold it anyway, and the user's OK must not let AC run on and
// exit mid-dump).
if (OutOfMemoryBoxRule.IsOutOfMemoryBox(body, mainThread))
CrashDump.WriteOutOfMemoryDumpOnce(Flatten(body));
description = Opened(body, caption, type, wide, mainThread);
}
catch { /* observation only: never block the dialog */ }
result = original != null ? original(hWnd, text, caption, type) : 0;
}
finally
{
// First, and whatever happened above: a leaked count would pause plugin ticks for good.
if (counted && Interlocked.Decrement(ref _mainThreadOpenCount) < 0)
Interlocked.Exchange(ref _mainThreadOpenCount, 0);
try
{
long secs = (Environment.TickCount64 - opened) / 1000;
if (Interlocked.Decrement(ref _openCount) <= 0)
{
Interlocked.Exchange(ref _openCount, 0);
_openDescription = null;
}
RynthLog.Info($"MessageBoxHooks: closed after {secs}s (result={result}): {description ?? "?"}");
}
catch { }
}
catch { }
return result;
}
private static string Opened(IntPtr text, IntPtr caption, uint type, bool wide, out bool mainThread, out bool outOfMemory)
private static string Opened(string body, IntPtr caption, uint type, bool wide, bool mainThread)
{
string body = Read(text, wide);
string title = Read(caption, wide);
mainThread = MainThreadGuard.IsOnMainThread();
// Counted first: the freeze gate must see the box even if the rest of this throws.
if (mainThread) Interlocked.Increment(ref _mainThreadOpenCount);
outOfMemory = body.Contains(OutOfMemoryMarker, StringComparison.OrdinalIgnoreCase);
// The first frame outside user32 and this file: who asked for the dialog.
string caller = "?";
@ -187,6 +196,63 @@ internal static class MessageBoxHooks
return description;
}
// -- Stale main-thread count (safety net) ------------------------------------
// The count is decremented in Show's finally, so it should never leak; if it ever reads
// non-zero while AC's main thread owns no dialog window for 30 s, it is reset (and
// logged), so a leak can never pause plugin ticks for good. Heartbeat thread, 1 Hz.
private const long StaleCountResetMs = 30_000;
private static long _countWithoutBoxSinceMs;
private delegate bool EnumThreadWndProc(IntPtr hWnd, IntPtr lParam);
[DllImport("user32.dll")]
private static extern bool EnumThreadWindows(uint threadId, EnumThreadWndProc callback, IntPtr lParam);
[DllImport("user32.dll", CharSet = CharSet.Unicode)]
private static extern int GetClassNameW(IntPtr hWnd, System.Text.StringBuilder name, int max);
[DllImport("user32.dll")]
private static extern bool IsWindowVisible(IntPtr hWnd);
private static bool MainThreadOwnsDialog()
{
uint tid = MainThreadGuard.MainThreadId;
if (tid == 0) return false;
bool found = false;
var name = new System.Text.StringBuilder(64);
EnumThreadWindows(tid, (h, _) =>
{
name.Clear();
if (GetClassNameW(h, name, name.Capacity) > 0 && name.ToString() == "#32770" && IsWindowVisible(h))
{
found = true;
return false;
}
return true;
}, IntPtr.Zero);
return found;
}
/// <summary>Heartbeat thread, about once a second. Never throws.</summary>
public static void ReconcileStaleMainThreadCount()
{
try
{
long now = Environment.TickCount64;
// The OOM dump runs before the box window exists: counted, no dialog yet, legitimately.
if (MainThreadOpenCount <= 0 || CrashDump.FullDumpInProgress || MainThreadOwnsDialog())
{
_countWithoutBoxSinceMs = 0;
return;
}
if (_countWithoutBoxSinceMs == 0) { _countWithoutBoxSinceMs = now; return; }
if (now - _countWithoutBoxSinceMs < StaleCountResetMs) return;
int was = Interlocked.Exchange(ref _mainThreadOpenCount, 0);
_countWithoutBoxSinceMs = 0;
RynthLog.Warn($"MessageBoxHooks: main-thread box count was {was} with no dialog open on AC's main thread for {StaleCountResetMs / 1000}s - reset to 0.");
}
catch { }
}
private static string Read(IntPtr p, bool wide)
{
if (p == IntPtr.Zero) return "";

View file

@ -151,7 +151,7 @@ internal static class MovementActionHooks
public static bool DoMovement(uint motion, float speed = 1.0f, int holdKey = HoldKeyRun)
{
if (!MainThreadGuard.IsOnMainThread())
if (AcMainThreadQueue.MustQueue(teardown: false))
return AcMainThreadQueue.EnqueueDoMovement(motion, speed, holdKey);
int n = System.Threading.Interlocked.Increment(ref _doMovementCalls);
@ -179,7 +179,7 @@ internal static class MovementActionHooks
public static bool StopMovement(uint motion, int holdKey = HoldKeyRun)
{
if (!MainThreadGuard.IsOnMainThread())
if (AcMainThreadQueue.MustQueue(teardown: true))
return AcMainThreadQueue.EnqueueStopMovement(motion, holdKey);
int n = System.Threading.Interlocked.Increment(ref _stopMovementCalls);
@ -207,7 +207,7 @@ internal static class MovementActionHooks
public static bool JumpNonAutonomous(float extent)
{
if (!MainThreadGuard.IsOnMainThread())
if (AcMainThreadQueue.MustQueue(teardown: false))
return AcMainThreadQueue.EnqueueJump(extent);
if (_jumpNonAutonomous == null)
@ -231,7 +231,7 @@ internal static class MovementActionHooks
if (_autonomyLevel == null)
return false;
if (!MainThreadGuard.IsOnMainThread())
if (AcMainThreadQueue.MustQueue(teardown: false))
return AcMainThreadQueue.EnqueueSetAutonomyLevel(level);
try

View file

@ -0,0 +1,28 @@
// ============================================================================
// RynthCore.Engine - Compatibility/MutatorGate.cs
//
// The decision behind AcMainThreadQueue.MustQueue, the one line every AC-mutating helper
// opens with: call AC now, or queue the call?
// - off AC's main thread: queue (AC is single-threaded);
// - on it, called BY a queue drain: call now (the drain already applied the gate);
// - on it, a stop or cancel (teardown): call now, even in a world transition;
// - on it otherwise: queue while a world transition holds the drains (render-thread host
// actions used to run straight into a world AC was tearing down), else call now.
// holding is asked last and only when it matters (it is main-thread state).
//
// Pure. Compiled into tools\EngineRobustnessTests.
// ============================================================================
using System;
namespace RynthCore.Engine.Compatibility;
internal static class MutatorGate
{
public static bool MustQueue(bool onMainThread, bool teardown, bool draining, Func<bool> holding)
{
if (!onMainThread) return true;
if (draining || teardown) return false;
return holding();
}
}

View file

@ -65,14 +65,18 @@ internal sealed class PendingIdQueue
/// <summary>
/// Queue a request for <paramref name="id"/>, or merge it into a pending one for the
/// same object from the same <paramref name="epoch"/> that is at most
/// <paramref name="mergeMaxAgeMs"/> old at <paramref name="nowMs"/>.
/// <paramref name="mergeMaxAgeMs"/> old at <paramref name="nowMs"/> and was queued AFTER
/// <paramref name="mergeOnlyAfterMs"/> (the last moment a world transition held the
/// drains: an entry from before then is dropped when the drain reaches it, and a request
/// merged into it would be lost with it).
/// </summary>
public Result Enqueue(uint id, long nowMs, int epoch, long mergeMaxAgeMs)
public Result Enqueue(uint id, long nowMs, int epoch, long mergeMaxAgeMs, long mergeOnlyAfterMs = 0)
{
for (int i = 0; i < _count; i++)
{
ref readonly Item q = ref _ring[(_head + i) % _ring.Length];
if (q.Id == id && q.Epoch == epoch && nowMs - q.At <= mergeMaxAgeMs)
if (q.Id == id && q.Epoch == epoch && nowMs - q.At <= mergeMaxAgeMs
&& (mergeOnlyAfterMs <= 0 || q.At > mergeOnlyAfterMs)) // 0 = no transition: no floor
{
MergedTotal++;
return Result.Merged;

View file

@ -45,11 +45,28 @@ internal static class PlayerLifecycleLog
/// AC main thread only (the queue drains): true = hold everything queued now (see
/// WorldTransitionState for the rule).
/// </summary>
public static bool HoldQueuedWork(long nowMs) => _state.CheckHolding(nowMs);
public static bool HoldQueuedWork(long nowMs)
{
bool hold = _state.CheckHolding(nowMs);
if (hold) Interlocked.Exchange(ref _lastBlockedPublished, nowMs);
return hold;
}
/// <summary>AC main thread only: what a drain does with one queued item (WorldTransitionState.Decide).</summary>
public static WorldTransitionState.Verdict DecideQueued(long nowMs, long queuedAtMs, bool teardown) =>
_state.Decide(nowMs, queuedAtMs, teardown);
public static WorldTransitionState.Verdict DecideQueued(long nowMs, long queuedAtMs, bool teardown)
{
WorldTransitionState.Verdict v = _state.Decide(nowMs, queuedAtMs, teardown);
if (v == WorldTransitionState.Verdict.Hold) Interlocked.Exchange(ref _lastBlockedPublished, nowMs);
return v;
}
private static long _lastBlockedPublished;
/// <summary>
/// The last moment a drain was held by a world transition (0 = never), for other threads:
/// queued work from at or before it is dropped when the drains reach it.
/// </summary>
public static long LastBlockedMs => Interlocked.Read(ref _lastBlockedPublished);
/// <summary>AC main thread, once per game tick.</summary>
public static void SampleOnGameThread(bool portaling)
@ -94,6 +111,19 @@ internal static class PlayerLifecycleLog
RynthLog.Info($"[Lifecycle] landblock jump 0x{_state.PreviousLandblock:X4} -> 0x{landblock:X4}{(portaling ? " (in portal space)" : "")}; queued game actions held off for {WorldTransitionState.SettleMs / 1000} s.");
}
/// <summary>
/// AC main thread (SmartBoxHooks, after AC handled 0xF751 PlayerTeleport): a teleport starts
/// now. The settle window runs from here, published at once for the enqueue side.
/// </summary>
public static void OnTeleportMessage()
{
long now = Environment.TickCount64;
bool started = _state.OnTeleportMessage(now);
Interlocked.Exchange(ref _settleUntil, _state.SettleUntilMs);
if (started)
RynthLog.Info($"[Lifecycle] PlayerTeleport (0xF751) received in landblock 0x{_state.Landblock:X4}; queued game actions held off for {WorldTransitionState.SettleMs / 1000} s.");
}
private static string Ago(long since, long now) =>
since == 0 ? "?" : $"{(now - since) / 1000.0:0.0}s";
}

View file

@ -385,7 +385,7 @@ internal static class PlayerPhysicsHooks
// Park the heading in the coalesced slot instead; AcMainThreadQueue.Drain
// calls back in here on the main thread (and falls back to the
// CommandInterpreter turn there when there is no player, as before).
if (!MainThreadGuard.IsOnMainThread())
if (AcMainThreadQueue.MustQueue(teardown: false))
return AcMainThreadQueue.EnqueueDirectHeading(decalHeadingDeg);
int n = System.Threading.Interlocked.Increment(ref _setHeadingCalls);
@ -457,7 +457,7 @@ internal static class PlayerPhysicsHooks
// raw write racing AC's own motion-graph tick is a guaranteed torn
// write, not just an AV risk. Reachable off-thread via Jumper.cs's
// ReleaseJump on the Decal-coexistence pump thread.
if (!MainThreadGuard.IsOnMainThread())
if (AcMainThreadQueue.MustQueue(teardown: false))
return AcMainThreadQueue.EnqueueLaunchJumpWithMotion(shift, holdW, holdX, holdZ, holdC);
if (!TryGetCMotionInterp(out IntPtr cmi))

View file

@ -141,7 +141,7 @@ internal static unsafe class PlayerTrade
/// <summary>Ask <paramref name="targetId"/> to trade (0x01F6 OpenTradeNegotiations).</summary>
public static bool Open(uint targetId)
{
if (!MainThreadGuard.IsOnMainThread())
if (AcMainThreadQueue.MustQueue(teardown: false))
return _eventOpenTradeNegotiations != null && targetId != 0
&& AcMainThreadQueue.EnqueueTrade((uint)TradeOp.Open, targetId, 0);
if (_eventOpenTradeNegotiations == null || targetId == 0) return false;
@ -153,7 +153,7 @@ internal static unsafe class PlayerTrade
/// <summary>Put one of your items in the trade window (0x01F8 AddToTrade). slot 0 = next free.</summary>
public static bool Add(uint itemId, uint slot)
{
if (!MainThreadGuard.IsOnMainThread())
if (AcMainThreadQueue.MustQueue(teardown: false))
return _eventAddToTrade != null && itemId != 0
&& AcMainThreadQueue.EnqueueTrade((uint)TradeOp.Add, itemId, slot);
if (_eventAddToTrade == null || itemId == 0) return false;
@ -165,7 +165,7 @@ internal static unsafe class PlayerTrade
/// <summary>Empty both sides of the window (0x0204 ResetTrade).</summary>
public static bool Reset()
{
if (!MainThreadGuard.IsOnMainThread())
if (AcMainThreadQueue.MustQueue(teardown: false))
return _eventResetTrade != null && AcMainThreadQueue.EnqueueTrade((uint)TradeOp.Reset, 0, 0);
if (_eventResetTrade == null) return false;
byte rv = _eventResetTrade();
@ -176,7 +176,7 @@ internal static unsafe class PlayerTrade
/// <summary>Close the trade (0x01F7 CloseTradeNegotiations).</summary>
public static bool Close()
{
if (!MainThreadGuard.IsOnMainThread())
if (AcMainThreadQueue.MustQueue(teardown: false))
return _eventCloseTradeNegotiations != null && AcMainThreadQueue.EnqueueTrade((uint)TradeOp.Close, 0, 0);
if (_eventCloseTradeNegotiations == null) return false;
byte rv = _eventCloseTradeNegotiations();
@ -187,7 +187,7 @@ internal static unsafe class PlayerTrade
/// <summary>Accept the trade as it stands (the window's Accept button, 0x01FA AcceptTrade).</summary>
public static bool Accept()
{
if (!MainThreadGuard.IsOnMainThread())
if (AcMainThreadQueue.MustQueue(teardown: false))
return _tradeSystemAcceptTrade != null && AcMainThreadQueue.EnqueueTrade((uint)TradeOp.Accept, 0, 0);
if (_tradeSystemAcceptTrade == null) return false;
IntPtr system = TradeSystemWithTrade();
@ -200,7 +200,7 @@ internal static unsafe class PlayerTrade
/// <summary>Withdraw your acceptance (the window's Decline button, 0x01FB DeclineTrade).</summary>
public static bool Decline()
{
if (!MainThreadGuard.IsOnMainThread())
if (AcMainThreadQueue.MustQueue(teardown: false))
return _tradeSystemDeclineTrade != null && AcMainThreadQueue.EnqueueTrade((uint)TradeOp.Decline, 0, 0);
if (_tradeSystemDeclineTrade == null) return false;
IntPtr system = TradeSystemWithTrade();

View file

@ -121,7 +121,7 @@ internal static unsafe class PlayerTraining
RynthLog.Compat($"PlayerTraining: {kind} {stype} not sent - not in the world");
return false;
}
if (defer || !MainThreadGuard.IsOnMainThread())
if (defer || AcMainThreadQueue.MustQueue(teardown: false))
return AcMainThreadQueue.EnqueueTrain((uint)kind, stype, xp);
byte rv = kind switch

View file

@ -174,6 +174,14 @@ internal static class ProcessExitHooks
private static void ExitProcessDetour(uint exitCode)
{
// A crash exit goes straight to the original, before any managed work (IsCrashExit).
// The reverse-P/Invoke transition into this detour is the only managed step left; a
// native pass-through would remove that too; it is possible but not done here.
if (IsCrashExit(exitCode))
{
_exitOriginal!(exitCode);
return;
}
LogTermination("ExitProcess", IntPtr.Zero, exitCode);
// Run our orderly shutdown BEFORE AC's CRT atexit chain. Without this,
// hooks stay installed, our threads (TickPump, Avalonia STA) keep
@ -191,7 +199,7 @@ internal static class ProcessExitHooks
// MiniDumpWriteDump) can deadlock or fault again there and leave nothing at all. So a crash
// exit is passed straight to the original. The evidence comes from places that do not
// 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\Clr.c). This
// 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;
@ -211,6 +219,11 @@ internal static class ProcessExitHooks
private static void RtlExitUserProcessDetour(uint exitStatus)
{
if (IsCrashExit(exitStatus)) // see ExitProcessDetour
{
_rtlExitOriginal!(exitStatus);
return;
}
LogTermination("RtlExitUserProcess", IntPtr.Zero, exitStatus);
try { EngineLifecycle.Shutdown(); }
catch (Exception ex) { RynthLog.Info($"ProcessExit: EngineLifecycle.Shutdown threw {ex.GetType().Name}: {ex.Message}"); }

View file

@ -456,7 +456,9 @@ internal static class PropertyUpdateHooks
if (objectId != 0)
{
EvictObject(objectId);
AppraisalHooks.EvictObject(objectId);
// A client release keeps the identify data a while (a server delete,
// 0xF747, evicts it): see ReleasedObjectRetention.
AppraisalHooks.OnClientRelease(objectId, Environment.TickCount64);
}
}
}

View file

@ -0,0 +1,77 @@
// ============================================================================
// RynthCore.Engine - Compatibility/ReleasedObjectRetention.cs
//
// How long AppraisalHooks keeps an object's identify data after the CLIENT released it
// (AC's BeingDeleted, which fires for every object leaving the client's view).
//
// Before: the data was evicted on every client release, so when the
// object came back into view AutoId found nothing cached and appraised it again: the
// 10-minute re-appraisal window (AutoIdEligibility) almost never applied. Now the data is
// kept for RetainMs after a client release and dropped:
// - when RetainMs has passed (Expire, from AutoIdService's timer);
// - when the SERVER deleted the object (0xF747; AppraisalHooks.EvictObject);
// - at a session clear (logout), and under AppraisalHooks' object cap.
// A re-create (OnLive) makes the object current again.
//
// Pure bookkeeping (released ids and when); no locking (AppraisalHooks holds its lock).
// Compiled into tools\EngineRobustnessTests.
// ============================================================================
using System.Collections.Generic;
namespace RynthCore.Engine.Compatibility;
internal sealed class ReleasedObjectRetention
{
public const long DefaultRetainMs = 10L * 60 * 1000;
public const int DefaultMaxReleased = 4096;
private readonly Dictionary<uint, long> _releasedAt;
private readonly long _retainMs;
private readonly int _max;
public ReleasedObjectRetention(long retainMs = DefaultRetainMs, int maxReleased = DefaultMaxReleased)
{
_retainMs = retainMs;
_max = maxReleased;
_releasedAt = new Dictionary<uint, long>(maxReleased + 1);
}
public int Count => _releasedAt.Count;
public long RetainMs => _retainMs;
/// <summary>
/// The client released <paramref name="id"/> (which has cached data). Returns true when the
/// data is kept for now; false when it must be dropped at once (the bound is reached and
/// nothing has expired to make room).
/// </summary>
public bool OnRelease(uint id, long nowMs)
{
if (_releasedAt.ContainsKey(id)) { _releasedAt[id] = nowMs; return true; }
if (_releasedAt.Count >= _max) return false;
_releasedAt[id] = nowMs == 0 ? 1 : nowMs;
return true;
}
/// <summary>The object is current again (re-created), or its data was dropped for another reason.</summary>
public void Forget(uint id) => _releasedAt.Remove(id);
public bool IsReleased(uint id) => _releasedAt.ContainsKey(id);
/// <summary>Released ids whose data has outlived RetainMs: removed here and added to <paramref name="expired"/>.</summary>
public int Expire(long nowMs, List<uint> expired)
{
int n = 0;
foreach (KeyValuePair<uint, long> kv in _releasedAt)
{
if (nowMs - kv.Value < _retainMs) continue;
expired.Add(kv.Key);
n++;
}
for (int i = expired.Count - n; i < expired.Count; i++)
_releasedAt.Remove(expired[i]);
return n;
}
public void Clear() => _releasedAt.Clear();
}

View file

@ -28,6 +28,7 @@
using System;
using System.Runtime.InteropServices;
using System.Threading;
namespace RynthCore.Engine.Compatibility;
@ -52,6 +53,24 @@ internal static class SehTrampoline
catch (Exception ex) { RynthLog.Compat($"SehTrampoline: InstallCrashLogger failed - {ex.GetType().Name}: {ex.Message}"); }
}
private static int _moduleRefreshUnavailable;
/// <summary>
/// Rebuilds the crash logger's module cache (module names at exception time come from it,
/// so the handler never calls the loader). Heartbeat thread, every few seconds. A DLL
/// older than the export is tolerated: the first failure stops the calls.
/// </summary>
public static void RefreshCrashLoggerModules()
{
if (!_available || Volatile.Read(ref _moduleRefreshUnavailable) != 0) return;
try { _RefreshCrashLoggerModules(); }
catch (Exception ex)
{
Interlocked.Exchange(ref _moduleRefreshUnavailable, 1);
RynthLog.Compat($"SehTrampoline: crash-logger module refresh unavailable - {ex.GetType().Name}: {ex.Message}");
}
}
// ── Tag-parser guard (native detour) ───────────────────────────────────
/// <summary>Address of the native tag-parser null-guard detour (RC_TagParserGuard),
/// for the engine to pass to MinHook as the detour target.</summary>
@ -104,6 +123,10 @@ internal static class SehTrampoline
CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Unicode)]
private static extern void _InstallCrashLogger([MarshalAs(UnmanagedType.LPWStr)] string logPath);
[DllImport("RynthCore.SehTrampoline.dll", EntryPoint = "RC_RefreshCrashLoggerModules",
CallingConvention = CallingConvention.Cdecl)]
private static extern void _RefreshCrashLoggerModules();
[DllImport("RynthCore.SehTrampoline.dll", EntryPoint = "RC_GetTagParserGuardAddress",
CallingConvention = CallingConvention.Cdecl)]
private static extern IntPtr _GetTagParserGuardAddress();

View file

@ -16,6 +16,8 @@ internal static class SmartBoxHooks
private const uint PlayerPositionUpdateOpcode = 0x0000F74B;
private const uint VectorUpdateOpcode = 0x0000F74E;
private const uint UpdateObjectOpcode = 0x0000F7DB;
private const uint ServerObjectDeleteOpcode = 0x0000F747;
private const uint PlayerTeleportOpcode = 0x0000F751;
// ACSmartBox::DispatchSmartBoxEvent
// 83 EC 08 53 8B 5C 24 10 8B 53 30 83 FA 04 8B 43 2C 56 8B F1 89 44 24 14 89 54 24 08 72 ?? 8B 08
@ -136,6 +138,17 @@ internal static class SmartBoxHooks
TryQueueHealthUpdate(blob, info);
TryQueueDamageEvent(blob, info);
// Always on (no server-message capture needed), after AC handled the message:
// 0xF747 ObjectDelete [opcode][objectId]: the SERVER deleted it (AutoId re-arms it
// and its kept identify data goes), unlike the client's own view releases;
// 0xF751 PlayerTeleport: a teleport starts, so queued game actions hold for the
// settle window from this moment (WorldTransitionState), whatever the per-tick
// teleport_in_progress sample catches.
if (info.Opcode == ServerObjectDeleteOpcode && info.RawObjectId != 0)
AutoIdService.OnServerDelete(info.RawObjectId);
else if (info.Opcode == PlayerTeleportOpcode)
PlayerLifecycleLog.OnTeleportMessage();
if (info.RawObjectId != 0 &&
(info.Opcode == PositionUpdateOpcode ||
info.Opcode == PlayerPositionUpdateOpcode ||

View file

@ -93,6 +93,20 @@ internal sealed class WorldTransitionState
return edges;
}
/// <summary>
/// The server's PlayerTeleport message (0xF751) arrived: a teleport begins now, whether or not
/// a tick sample ever sees teleport_in_progress or a landblock jump (a recall into the next
/// landblock shows neither). Starts (or extends) the settle window. Returns false when the
/// window was already running past it.
/// </summary>
public bool OnTeleportMessage(long nowMs)
{
long until = nowMs + SettleMs;
if (until <= SettleUntilMs) return false;
SettleUntilMs = until;
return true;
}
/// <summary>Two landblocks more than one apart on either axis: a teleport, not a walk.</summary>
public static bool IsJump(uint from, uint to)
{

View file

@ -123,7 +123,7 @@ internal static class CrashDump
}
}
// ── OUT OF MEMORY full-memory dump ──────────────────────────────────────
// -- 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;
@ -157,34 +157,55 @@ internal static class CrashDump
if (Interlocked.Exchange(ref _oomDumpLatch, 1) != 0) return;
string why = "AC OUT OF MEMORY box: " + (reason ?? "?");
_fullDumpInProgress = true;
// The launcher reads this marker (DumpInProgressRule): MiniDumpWriteDump suspends every
// thread, so the log goes silent for the whole dump, which would otherwise read as a dead
// engine and get the client killed mid-dump.
try { RynthLog.Error($"{DumpMarkerStarted} pid={Environment.ProcessId} - AC OUT OF MEMORY box; writing one full-memory dump before it shows."); }
catch { }
Thread? writer = null;
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(() =>
{
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.");
// The flag stays up until the writer itself is done, even past a timed-out Join.
try { WriteOutOfMemoryDumpCore(why); }
finally { FinishFullDump(); }
}) { IsBackground = true, Name = "RynthCore.OomDump" };
writer.Start();
}
catch (Exception ex)
{
RynthLog.Error($"CrashDump: OOM dump failed {ex.GetType().Name}: {ex.Message}");
// No thread to be had (out of memory, after all): write it from this one.
try { RynthLog.Error($"CrashDump: dump thread failed to start ({ex.GetType().Name}) - writing on the calling thread."); } catch { }
writer = null;
}
finally
try
{
_fullDumpInProgress = false;
if (writer == null)
{
try { WriteOutOfMemoryDumpCore(why); }
finally { FinishFullDump(); }
}
else if (!writer.Join(FullDumpWaitMs))
{
RynthLog.Error($"CrashDump: full dump still writing after {FullDumpWaitMs / 1000}s - letting the box open (the writer keeps going).");
}
}
catch (Exception ex)
{
try { RynthLog.Error($"CrashDump: OOM dump failed {ex.GetType().Name}: {ex.Message}"); } catch { }
}
}
/// <summary>Log line written before the OUT OF MEMORY full dump starts (read by the launcher).</summary>
internal const string DumpMarkerStarted = RynthCore.Install.DumpInProgressRule.MarkerStarted;
/// <summary>Log line written once the writer has finished, whatever the outcome.</summary>
internal const string DumpMarkerEnded = RynthCore.Install.DumpInProgressRule.MarkerEnded;
private static void FinishFullDump()
{
_fullDumpInProgress = false;
try { RynthLog.Error($"{DumpMarkerEnded} pid={Environment.ProcessId}."); } catch { }
}
private static void WriteOutOfMemoryDumpCore(string reason)
@ -193,22 +214,20 @@ internal static class CrashDump
{
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}");
// Only after the new dump succeeded: a failed write never costs an older one.
PruneDumps(dir, OutOfMemoryDumpPrefix, OutOfMemoryDumpsKept);
}
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)
{
@ -216,7 +235,13 @@ internal static class CrashDump
}
}
/// <summary>Deletes all but the newest <paramref name="keep"/> <paramref name="prefix"/>*.dmp files in <paramref name="dir"/>. Never throws.</summary>
/// <summary>
/// Deletes all but the newest <paramref name="keep"/> <paramref name="prefix"/>*.dmp files in
/// <paramref name="dir"/>. The folder is shared by every client: a dump whose name carries
/// the pid of ANOTHER process that is still running is never deleted (it may still be
/// writing it, or about to report it), and is not counted against <paramref name="keep"/>.
/// Never throws.
/// </summary>
internal static int PruneDumps(string dir, string prefix, int keep)
{
int deleted = 0;
@ -224,13 +249,22 @@ internal static class CrashDump
{
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++)
int kept = 0;
int self = Environment.ProcessId;
foreach (FileInfo f in files)
{
int pid = DumpPid(f.Name, prefix);
if (pid > 0 && pid != self && IsProcessAlive(pid))
continue; // another live client's dump: not ours to delete
if (kept < Math.Max(0, keep)) { kept++; continue; }
string name = f.Name;
long length = 0;
try { length = f.Length; } catch { }
try
{
files[i].Delete();
f.Delete();
deleted++;
RynthLog.Info($"CrashDump: pruned old dump {files[i].Name} ({files[i].Length / (1024 * 1024)}MB).");
RynthLog.Info($"CrashDump: pruned old dump {name} ({length / (1024 * 1024)}MB).");
}
catch { /* in use by a debugger, or already gone */ }
}
@ -238,4 +272,25 @@ internal static class CrashDump
catch { }
return deleted;
}
}
/// <summary>The pid in "prefix&lt;pid&gt;_...dmp", or 0.</summary>
internal static int DumpPid(string fileName, string prefix)
{
if (!fileName.StartsWith(prefix, StringComparison.OrdinalIgnoreCase)) return 0;
int start = prefix.Length, end = start;
while (end < fileName.Length && char.IsDigit(fileName[end])) end++;
return end > start && int.TryParse(fileName.AsSpan(start, end - start), out int pid) ? pid : 0;
}
private static bool IsProcessAlive(int pid)
{
try
{
using var p = System.Diagnostics.Process.GetProcessById(pid);
return !p.HasExited;
}
catch
{
return false;
}
}}

View file

@ -33,6 +33,19 @@ internal static class MainThreadFreezeRule
}
}
/// <summary>
/// Is a message box AC's OUT OF MEMORY box (the one that gets a full-memory dump)? Only on
/// AC's main thread, and only AC's own text, matched exactly at the start (ordinal): a plugin
/// box or a chat line that merely mentions memory must never cost a multi-gigabyte dump.
/// </summary>
internal static class OutOfMemoryBoxRule
{
public const string Prefix = "OUT OF MEMORY: Failed to allocate";
public static bool IsOutOfMemoryBox(string? body, bool onMainThread) =>
onMainThread && body != null && body.StartsWith(Prefix, System.StringComparison.Ordinal);
}
/// <summary>Single-writer (the plugin pump). Not thread-safe; the engine glue publishes copies.</summary>
internal sealed class PumpPauseTracker
{

View file

@ -164,6 +164,7 @@
<ItemGroup>
<!-- Install-folder resolver (env, HKCU, HKLM, default C:\Games). Read only; same file in RynthSuite Plugins\Shared. -->
<Compile Include="..\Shared\RynthInstallPaths.cs" Link="Shared\RynthInstallPaths.cs" />
<Compile Include="..\Shared\DumpInProgressRule.cs" Link="Shared\DumpInProgressRule.cs" />
</ItemGroup>
</Project>