RynthCore/src/RynthCore.Engine/Compatibility/AutoIdService.cs
Daniel Wallace 8c7201dc25 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>
2026-10-12 17:17:59 -07:00

227 lines
9.6 KiB
C#

// ============================================================================
// RynthCore.Engine - Compatibility/AutoIdService.cs
//
// Automatically sends RequestId (appraisal) for newly-created world objects
// so that property caches (AppraisalHooks int/bool/string) are populated
// without requiring the player to manually select each object.
//
// Objects are queued from CreateObjectHooks and drained by a background timer
// with rate-limiting to avoid flooding the server.
//
// Which creates get an appraisal is AutoIdEligibility's rule: an object the client
// released and re-created is not appraised again within 10 minutes of the last one
// while its data is still cached, unless the server deleted it (see that file).
// ============================================================================
using System;
using System.Collections.Concurrent;
using System.Threading;
namespace RynthCore.Engine.Compatibility;
internal static class AutoIdService
{
// How often the drain timer fires (ms)
private const int DrainIntervalMs = 100;
// Max RequestId calls per drain tick
private const int MaxPerTick = 3;
// How long an appraisal stays good enough not to repeat: a client re-create inside
// this window, and the selected-target priority appraisal, skip an object whose
// appraisal is cached and this recent.
private const long ReappraiseWindowMs = AutoIdEligibility.DefaultWindowMs;
// Per-object appraisal bookkeeping. Written on AC's main thread (create, client
// release), the plugin pump (server delete) and the drain timer; every access holds
// _gate, for a few dictionary operations only.
private static readonly AutoIdEligibility _eligibility = new(ReappraiseWindowMs);
private static readonly object _gate = new();
// Pending queue
private static readonly ConcurrentQueue<uint> _queue = new();
private static Timer? _drainTimer;
private static bool _started;
private static long _skippedPriorityFresh;
/// <summary>Re-creates not appraised because a recent appraisal is still cached.</summary>
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);
public static void Start()
{
if (_started)
return;
_started = true;
_drainTimer = new Timer(DrainTick, null, DrainIntervalMs, DrainIntervalMs);
RynthLog.Verbose("Compat: AutoIdService started.");
}
/// <summary>
/// Dispose the drain timer at engine shutdown so it doesn't keep firing in
/// the old generation's (intentionally still-mapped) module across hot-reloads.
/// </summary>
public static void Stop()
{
if (!_started)
return;
_started = false;
_drainTimer?.Dispose();
_drainTimer = null;
RynthLog.Verbose("Compat: AutoIdService stopped.");
}
/// <summary>
/// Enqueue an object for automatic appraisal. Called from CreateObjectHooks detour
/// (AC's main thread) and the Decal bridge's create event.
/// </summary>
public static void Enqueue(uint objectId)
{
if (objectId == 0)
return;
// Skip the player character
uint playerId = ClientHelperHooks.GetPlayerId();
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)
decision = _eligibility.OnCreate(objectId, Environment.TickCount64, cached);
if (decision == AutoIdEligibility.CreateDecision.Appraise)
_queue.Enqueue(objectId);
}
/// <summary>
/// The CLIENT released an object (ACCObjectMaint::DeleteObject, or the Decal bridge's
/// delete event). A queued appraisal for it is skipped; its last appraisal time is kept,
/// so a re-create inside the window is not appraised again.
/// </summary>
public static void OnClientRelease(uint objectId)
{
if (objectId == 0) return;
lock (_gate)
_eligibility.OnClientRelease(objectId);
}
/// <summary>
/// The SERVER deleted an object (0xF747 ObjectDelete, from the server message stream on
/// the plugin pump). Whatever is created under that id next is appraised.
/// </summary>
public static void OnServerDelete(uint objectId)
{
if (objectId == 0) return;
lock (_gate)
_eligibility.OnServerDelete(objectId);
// It really went away: its kept identify data goes too.
AppraisalHooks.EvictObject(objectId);
}
/// <summary>
/// The 0xC8 for <paramref name="objectId"/> really went out (AcMainThreadQueue's drain, on
/// AC's main thread, for every RequestId caller). Starts its re-appraisal window.
/// </summary>
public static void OnSent(uint objectId, long nowMs)
{
if (objectId == 0) return;
lock (_gate)
_eligibility.OnSent(objectId, nowMs);
}
// Last target we issued a priority appraisal for (fires once per target change).
private static uint _lastPriorityTarget;
private static long _lastPruneMs;
private static void DrainTick(object? state)
{
try
{
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;
// Combat-target priority: when the selected target CHANGES, appraise it
// immediately — enqueued ahead of the create-order backlog so a fast kill
// still gets its max-HP appraisal out first instead of waiting behind the
// whole spawn. Fires once per change (guarded), so no per-tick re-appraisal.
// Skipped when the target's appraisal is already cached and fresh: selecting
// something identified a minute ago asked the server again for nothing.
uint target = SelectedTargetHooks.ReadCurrentSelectedId();
if (target != 0 && target != _lastPriorityTarget)
{
_lastPriorityTarget = target;
uint playerId = ClientHelperHooks.GetPlayerId();
if (target != playerId)
{
bool fresh = AutoIdEligibility.IsAppraisalFresh(
AppraisalHooks.HasAppraisalData(target), AppraisalHooks.GetLastIdTime(target),
DateTimeOffset.UtcNow.ToUnixTimeSeconds(), ReappraiseWindowMs);
if (fresh)
Interlocked.Increment(ref _skippedPriorityFresh);
else if (AcMainThreadQueue.EnqueueRequestId(target))
sent++;
}
}
while (sent < MaxPerTick && _queue.TryDequeue(out uint objectId))
{
// Object may have been destroyed between enqueue and drain
if (objectId == 0)
continue;
// Released since it was queued: skip it without spending one of the 3
// requests per tick. After a big landblock change (the 585 deletes of
// one jump) the queue otherwise kept asking the server to appraise gone
// objects at 30 a second for half a minute, and live ones waited. A
// release-then-recreate is decided again by Enqueue, so nothing live is lost.
bool live;
lock (_gate) live = _eligibility.IsLive(objectId);
if (!live)
continue;
// Marshal onto AC's main thread (EndScene drain) — the Timer thread must
// not call the native 0xC8 send directly (off-thread heap alloc + non-atomic
// UI-counter increment). EnqueueRequestId is the marshalled path. The
// appraisal counts as sent only when the main thread sends it (OnSent, from
// AcMainThreadQueue.DrainRequestIds): a queued request that is dropped there
// leaves the object due again.
AcMainThreadQueue.EnqueueRequestId(objectId);
sent++;
}
// Keep the bookkeeping bounded. Here, off AC's main thread: the create path
// never prunes.
if (now - _lastPruneMs >= 10_000)
{
_lastPruneMs = now;
int removed;
lock (_gate)
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 { }
}
}