AutoId limit: AutoIdMode All/Limited/Off (default Limited), requester-tagged 0xC8s

A flight capture from one 26-minute session showed the client sending 3211 IdentifyObject
(0xC8) messages, most of everything it sent, because AutoId appraised every object the
client created. Bots already appraise at the point of use, so the background appraisals
are now limited.

AutoIdMode (engine.json "AutoIdMode", default Limited; /rc autoid all|limited|off, live
and saved; /rc autoid alone reports it):
  All      the old behaviour.
  Limited  only the selected target (fresh-cache skip), items in the container the
           player has open now, and items in the player's own inventory with nothing
           cached. The last two wait until the object is 2 s old and until 30 s after a
           world transition's settle window ends (death, portal, teleport, landblock jump;
           walking into the next landblock never defers). A container opened after the
           settle ended is not deferred. Creatures, ground items, other players: never.
  Off      nothing, the selected target included.
Plugins' own RequestId calls are not limited; they still merge in the RequestId slot.

The decision is AutoIdPolicy (pure). AutoIdService now keeps a pending list on its drain
timer (waits for age/defer stay, skips leave), classifies each candidate from the PWD
snapshot (container / wielder / side pack owner, and the ground container from
ViewObjectContents), takes InventoryPutObjInContainer (0x0022) moves from the server
message stream, and rescans an opened container 2.5 s after the open.

Requester tagging: a thread-local EngineSendMarker around every engine RequestId call
(AutoId by class, plugin host API, the login self-identify, the Inventory panel hover).
A queued request carries its requester in PendingIdQueue and the main-thread drain
re-enters the marker around the real send. Only a marked send registers with the
flight recorder (FlightCapture.EngineSend, its own 64-entry table so bursts never evict
other engine calls), so its 0xC8 shows as [eng:autoid-target|autoid-container|
autoid-inventory|autoid-world|plugin|self|ui]; an unmarked 0xC8 stays [cli] and counts
as AC's or Decal's.

Per-minute log line "autoid 60s: ..." (its own line, not part of "hb #"): sends by
requester, cli, total, AutoId skips by reason (mode, age, defer, fresh), pending.

EngineSettings keeps upstream's MaxHotReloads, IltServerNames/IltHosts, ReportEndpoint
and CloseOnServerDisconnect next to AutoIdMode (owned keys, load and save).

Tests: EngineRobustnessTests (decision table against an independent expected function,
spot cases, defer window from WorldTransitionState inputs, classification, marker scopes
and thread-locality, requester through PendingIdQueue, heartbeat field names against the
launcher regex), FlightRecorderTests (identify tagging, foreign count, match window, burst),
EngineSettingsTests (AutoIdMode round trip, default left out). check_offthread_mutators.py:
DrainPending allow-listed like DrainTick (it only enqueues).

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Daniel Wallace 2026-10-10 23:09:15 -07:00
commit aaaa0a94b4
26 changed files with 1198 additions and 69 deletions

View file

@ -1,21 +1,35 @@
// ============================================================================
// 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.
// Automatically sends RequestId (appraisal) for 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.
// Candidates come from CreateObjectHooks (and the Decal bridge's create event), from
// items the server puts into a container (InventoryPutObjInContainer, through the
// server message stream), and from a rescan of a container the player opened. A
// background timer drains them, at most MaxPerTick sends per DrainIntervalMs.
//
// 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).
// WHICH of them get an appraisal is two rules:
// - AutoIdEligibility (on create): 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;
// - AutoIdPolicy (on drain): the AutoIdMode (engine.json "AutoIdMode", /rc autoid).
// Limited (the default) appraises only the selected target, the
// items in the container the player has open, and items in the player's own
// inventory with nothing cached; the last two wait for a minimum object age and a
// post-transition defer. All is the old behaviour; Off sends nothing.
//
// Every send is queued with who asked (Net/IdRequester.cs), so the flight recorder tags
// it [eng:autoid-target|autoid-container|autoid-inventory|autoid-world].
// ============================================================================
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Threading;
using RynthCore.Engine.Net;
using RynthCore.Engine.Plugins;
namespace RynthCore.Engine.Compatibility;
@ -27,6 +41,16 @@ internal static class AutoIdService
// Max RequestId calls per drain tick
private const int MaxPerTick = 3;
// Candidates waiting for a decision (most leave on their first look; only the ones
// waiting out the minimum age or the post-transition defer stay).
private const int MaxPending = 4096;
private const int MaxEvaluatedPerTick = 512;
// A container the player opened is rescanned this long after the open, so items the
// client already knew (created before the open, or by an earlier open) are candidates too.
private const long ContainerRescanDelayMs = AutoIdPolicy.MinAgeMs + 500;
private const int MaxRescanItems = 256;
// 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.
@ -38,13 +62,32 @@ internal static class AutoIdService
private static readonly AutoIdEligibility _eligibility = new(ReappraiseWindowMs);
private static readonly object _gate = new();
// Pending queue
private static readonly ConcurrentQueue<uint> _queue = new();
// New candidates (any thread) -> the drain's pending list (drain timer only).
private static readonly ConcurrentQueue<(uint Id, long AtMs)> _incoming = new();
private struct Pending
{
public uint Id;
public long AtMs; // created (or moved, or its container opened) at
public byte Counted; // waits already counted: 1 = age, 2 = defer
}
private static readonly List<Pending> _pending = new(256);
private static readonly HashSet<uint> _pendingIds = new();
private static int _pendingCount;
private static int _draining;
private static Timer? _drainTimer;
private static bool _started;
private static volatile int _mode = (int)AutoIdPolicy.DefaultMode;
// The container the player opened last (ViewObjectContents), and when.
private static int _openedContainerId;
private static long _openedAtMs;
private static long _rescanDueMs;
private static long _skippedPriorityFresh;
private static long _skipMode, _skipAge, _skipDefer, _skipFresh, _overflow;
/// <summary>Re-creates not appraised because a recent appraisal is still cached.</summary>
public static long SkippedRecentCount
@ -55,13 +98,26 @@ internal static class AutoIdService
/// <summary>Selected-target priority appraisals skipped because the target's data is cached and fresh.</summary>
public static long SkippedPriorityFreshCount => Interlocked.Read(ref _skippedPriorityFresh);
/// <summary>The live mode (engine.json "AutoIdMode", /rc autoid).</summary>
public static AutoIdMode Mode => (AutoIdMode)_mode;
/// <summary>Switch the mode now; <paramref name="persist"/> also saves it to engine.json.</summary>
public static void SetMode(AutoIdMode mode, bool persist)
{
_mode = (int)mode;
if (persist)
EngineSettings.AutoIdMode = mode;
RynthLog.Compat($"Compat: AutoId mode {AutoIdPolicy.Name(mode)}.");
}
public static void Start()
{
if (_started)
return;
_started = true;
try { _mode = (int)EngineSettings.AutoIdMode; } catch { }
_drainTimer = new Timer(DrainTick, null, DrainIntervalMs, DrainIntervalMs);
RynthLog.Verbose("Compat: AutoIdService started.");
RynthLog.Verbose($"Compat: AutoIdService started (mode {AutoIdPolicy.Name(Mode)}).");
}
/// <summary>
@ -96,12 +152,42 @@ internal static class AutoIdService
// if the release was inside ReleasedObjectRetention's time).
AppraisalHooks.MarkLive(objectId);
bool cached = AppraisalHooks.HasAppraisalData(objectId);
long now = Environment.TickCount64;
AutoIdEligibility.CreateDecision decision;
lock (_gate)
decision = _eligibility.OnCreate(objectId, Environment.TickCount64, cached);
decision = _eligibility.OnCreate(objectId, now, cached);
if (decision == AutoIdEligibility.CreateDecision.Appraise)
_queue.Enqueue(objectId);
_incoming.Enqueue((objectId, now));
}
/// <summary>
/// The server put <paramref name="itemId"/> into <paramref name="containerId"/>
/// (InventoryPutObjInContainer, game event 0x0022; server message stream, plugin pump).
/// In Limited mode an item that landed in the player's inventory with nothing cached is
/// a candidate; where it landed is decided at the drain, from the object snapshot.
/// </summary>
public static void OnPutInContainer(uint itemId, uint containerId)
{
if (itemId == 0 || containerId == 0 || Mode != AutoIdMode.Limited)
return;
if (AppraisalHooks.HasAppraisalData(itemId))
return;
_incoming.Enqueue((itemId, Environment.TickCount64));
}
/// <summary>
/// The client opened <paramref name="containerId"/>'s contents (ViewObjectContents, AC's
/// main thread). Its time decides the defer exemption, and a rescan after the minimum
/// age makes the items already known in it candidates.
/// </summary>
public static void OnContainerOpened(uint containerId)
{
if (containerId == 0) return;
long now = Environment.TickCount64;
Interlocked.Exchange(ref _openedAtMs, now);
Interlocked.Exchange(ref _openedContainerId, unchecked((int)containerId));
Interlocked.Exchange(ref _rescanDueMs, now + ContainerRescanDelayMs);
}
/// <summary>
@ -146,6 +232,9 @@ internal static class AutoIdService
private static void DrainTick(object? state)
{
// A slow tick must not overlap the next one: the pending list is this timer's alone.
if (Interlocked.CompareExchange(ref _draining, 1, 0) != 0)
return;
try
{
if (!CombatActionHooks.HasRequestId)
@ -156,55 +245,46 @@ internal static class AutoIdService
return;
long now = Environment.TickCount64;
AutoIdMode mode = Mode;
int sent = 0;
uint playerId = ClientHelperHooks.GetPlayerId();
long nowUnixSec = DateTimeOffset.UtcNow.ToUnixTimeSeconds();
// 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.
// immediately, ahead of the backlog, so a fast kill still gets its max-HP
// appraisal out first. 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. Exempt from the minimum age and the post-transition defer.
uint target = SelectedTargetHooks.ReadCurrentSelectedId();
if (target != 0 && target != _lastPriorityTarget)
{
_lastPriorityTarget = target;
uint playerId = ClientHelperHooks.GetPlayerId();
if (target != playerId)
{
bool cached = AppraisalHooks.HasAppraisalData(target);
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++;
cached, AppraisalHooks.GetLastIdTime(target), nowUnixSec, ReappraiseWindowMs);
switch (AutoIdPolicy.Decide(mode, AutoIdPolicy.Class.Target, 0, false, false, fresh, cached))
{
case AutoIdPolicy.Verdict.SkipFresh:
Interlocked.Increment(ref _skippedPriorityFresh);
Interlocked.Increment(ref _skipFresh);
break;
case AutoIdPolicy.Verdict.Send:
if (AcMainThreadQueue.EnqueueRequestId(target, IdRequester.AutoIdTarget))
sent++;
break;
default:
Interlocked.Increment(ref _skipMode);
break;
}
}
}
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++;
}
TakeIncoming();
RescanOpenedContainer(now);
sent = DrainPending(now, mode, playerId, nowUnixSec, sent);
// Keep the bookkeeping bounded. Here, off AC's main thread: the create path
// never prunes.
@ -223,5 +303,242 @@ internal static class AutoIdService
}
}
catch { }
finally
{
Volatile.Write(ref _draining, 0);
}
}
private static void TakeIncoming()
{
while (_incoming.TryDequeue(out (uint Id, long AtMs) c))
AddPending(c.Id, c.AtMs);
}
private static void AddPending(uint id, long atMs)
{
if (id == 0 || _pendingIds.Contains(id))
return;
if (_pending.Count >= MaxPending)
{
Interlocked.Increment(ref _overflow);
return;
}
_pendingIds.Add(id);
_pending.Add(new Pending { Id = id, AtMs = atMs });
}
/// <summary>Limited mode: the items already in a container the player opened become candidates.</summary>
private static void RescanOpenedContainer(long now)
{
long due = Interlocked.Read(ref _rescanDueMs);
if (due == 0 || now < due)
return;
Interlocked.CompareExchange(ref _rescanDueMs, 0, due);
if (Mode != AutoIdMode.Limited)
return;
uint container = unchecked((uint)Volatile.Read(ref _openedContainerId));
if (container == 0 || ClientHelperHooks.GetGroundContainerId() != container)
return; // closed again (or another one opened: its own rescan follows)
long openedAt = Interlocked.Read(ref _openedAtMs);
Span<uint> ids = stackalloc uint[MaxRescanItems];
int n = ClientObjectHooks.CollectOwnedIdsFromSnapshot(container, ids);
for (int i = 0; i < n; i++)
{
bool live;
lock (_gate) live = _eligibility.IsLive(ids[i]);
if (live && !AppraisalHooks.HasAppraisalData(ids[i]))
AddPending(ids[i], openedAt);
}
}
private static int DrainPending(long now, AutoIdMode mode, uint playerId, long nowUnixSec, int sent)
{
if (_pending.Count == 0)
{
Volatile.Write(ref _pendingCount, 0);
return sent;
}
uint open = ClientHelperHooks.GetGroundContainerId();
long openedAt = open != 0 && unchecked((uint)Volatile.Read(ref _openedContainerId)) == open
? Interlocked.Read(ref _openedAtMs) : 0;
long settleUntil = PlayerLifecycleLog.SettleUntilMs;
bool inDefer = AutoIdPolicy.InDefer(now, settleUntil, inTransition: false);
bool openedAfterSettle = AutoIdPolicy.OpenedAfterSettle(openedAt, settleUntil);
int keep = 0, evaluated = 0;
for (int i = 0; i < _pending.Count; i++)
{
Pending p = _pending[i];
if (sent >= MaxPerTick || evaluated >= MaxEvaluatedPerTick)
{
_pending[keep++] = p;
continue;
}
evaluated++;
// 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(p.Id);
if (!live)
{
_pendingIds.Remove(p.Id);
continue;
}
AutoIdPolicy.Class cls = ClassifyNow(p.Id, playerId, open);
bool cached = AppraisalHooks.HasAppraisalData(p.Id);
bool fresh = cached && AutoIdEligibility.IsAppraisalFresh(
cached, AppraisalHooks.GetLastIdTime(p.Id), nowUnixSec, ReappraiseWindowMs);
AutoIdPolicy.Verdict v = AutoIdPolicy.Decide(mode, cls, now - p.AtMs, inDefer, openedAfterSettle, fresh, cached);
switch (v)
{
case AutoIdPolicy.Verdict.Send:
// 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). 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(p.Id, RequesterFor(cls));
sent++;
_pendingIds.Remove(p.Id);
break;
case AutoIdPolicy.Verdict.WaitAge:
if ((p.Counted & 1) == 0) { p.Counted |= 1; Interlocked.Increment(ref _skipAge); }
_pending[keep++] = p;
break;
case AutoIdPolicy.Verdict.WaitDefer:
if ((p.Counted & 2) == 0) { p.Counted |= 2; Interlocked.Increment(ref _skipDefer); }
_pending[keep++] = p;
break;
case AutoIdPolicy.Verdict.SkipFresh:
Interlocked.Increment(ref _skipFresh);
_pendingIds.Remove(p.Id);
break;
default:
Interlocked.Increment(ref _skipMode);
_pendingIds.Remove(p.Id);
break;
}
}
_pending.RemoveRange(keep, _pending.Count - keep);
Volatile.Write(ref _pendingCount, _pending.Count);
return sent;
}
/// <summary>Where the object is now, from the engine's object snapshot (no AC access off its main thread).</summary>
private static AutoIdPolicy.Class ClassifyNow(uint id, uint playerId, uint open)
{
if (!ClientObjectHooks.TryGetObjectOwnershipInfo(id, out uint container, out uint wielder, out _))
return AutoIdPolicy.Classify(false, playerId, open, 0, 0, 0);
uint parent = 0;
if (container != 0 && container != playerId && container != open
&& ClientObjectHooks.TryGetObjectOwnershipInfo(container, out uint cc, out _, out _))
parent = cc;
return AutoIdPolicy.Classify(true, playerId, open, container, wielder, parent);
}
private static IdRequester RequesterFor(AutoIdPolicy.Class cls) => cls switch
{
AutoIdPolicy.Class.Target => IdRequester.AutoIdTarget,
AutoIdPolicy.Class.Container => IdRequester.AutoIdContainer,
AutoIdPolicy.Class.Inventory => IdRequester.AutoIdInventory,
_ => IdRequester.AutoIdWorld,
};
// -- counters: /rc autoid and the per-minute log line --
private static readonly IdRequester[] Sources =
{
IdRequester.AutoIdTarget, IdRequester.AutoIdContainer, IdRequester.AutoIdInventory, IdRequester.AutoIdWorld,
IdRequester.Plugin, IdRequester.Self, IdRequester.Ui, IdRequester.None,
};
private static readonly long[] _lastSent = new long[IdRequesters.Count];
private static long _lastForeign, _lastSkipMode, _lastSkipAge, _lastSkipDefer, _lastSkipFresh;
/// <summary>
/// The last minute's IdentifyObject counts (heartbeat thread, once a minute): sent per
/// requester, cli = sent by AC or Decal (from the flight recorder; ? while it is off),
/// and AutoId's skips by reason. None of its fields contains fps=, plug=, login= or qd=
/// (the launcher's heartbeat regex), and the line does not start with "hb #".
/// </summary>
public static string TakeMinuteLine()
{
long foreign = FlightRecorder.ForeignIdentifyTotal;
long sm = Interlocked.Read(ref _skipMode), sa = Interlocked.Read(ref _skipAge);
long sd = Interlocked.Read(ref _skipDefer), sf = Interlocked.Read(ref _skipFresh);
var sb = new System.Text.StringBuilder(160);
sb.Append("autoid 60s: mode=").Append(AutoIdPolicy.Name(Mode)).Append(" sent");
long total = 0;
foreach (IdRequester who in Sources)
{
long now = IdSendStats.Sent(who);
long d = now - _lastSent[(int)who];
_lastSent[(int)who] = now;
total += d;
if (who == IdRequester.None && d == 0) continue; // unmarked engine sends: shown only when there are any
sb.Append(' ').Append(IdRequesters.Short(who)).Append('=').Append(d);
}
if (foreign >= 0)
{
long d = foreign - _lastForeign;
_lastForeign = foreign;
total += d;
sb.Append(" cli=").Append(d);
}
else
{
sb.Append(" cli=?");
}
sb.Append(" tot=").Append(total);
sb.Append(" skip mode=").Append(sm - _lastSkipMode).Append(" age=").Append(sa - _lastSkipAge)
.Append(" defer=").Append(sd - _lastSkipDefer).Append(" fresh=").Append(sf - _lastSkipFresh);
sb.Append(" pend=").Append(Volatile.Read(ref _pendingCount));
_lastSkipMode = sm; _lastSkipAge = sa; _lastSkipDefer = sd; _lastSkipFresh = sf;
return sb.ToString();
}
/// <summary>/rc autoid [all|limited|off|status]</summary>
public static string[] HandleCommand(string args)
{
string verb = (args ?? "").Trim();
if (verb.Length > 0 && !verb.Equals("status", StringComparison.OrdinalIgnoreCase))
{
if (!AutoIdPolicy.TryParseMode(verb, out AutoIdMode mode))
return new[] { "Usage: /rc autoid [all|limited|off] (alone: status)" };
SetMode(mode, persist: true);
}
return StatusLines();
}
public static string[] StatusLines()
{
var sent = new System.Text.StringBuilder();
foreach (IdRequester who in Sources)
{
long n = IdSendStats.Sent(who);
if (who == IdRequester.None && n == 0) continue;
sent.Append(sent.Length > 0 ? ", " : "").Append(IdRequesters.Short(who)).Append(' ').Append(n);
}
long foreign = FlightRecorder.ForeignIdentifyTotal;
string modeText = Mode switch
{
AutoIdMode.All => "all (every created object, the old behaviour)",
AutoIdMode.Off => "off (no background appraisals, not even the selected target)",
_ => $"limited (selected target; open container and own inventory after {AutoIdPolicy.MinAgeMs / 1000} s, {AutoIdPolicy.DeferMs / 1000} s after a portal/death/teleport)",
};
return new[]
{
$"AutoId: {modeText}. Saved in engine.json; /rc autoid all|limited|off switches it now. Plugins' own identifies are never limited.",
$"Identifies sent since start: {sent}; by AC or Decal: {(foreign >= 0 ? foreign.ToString() : "? (flight recorder off)")}.",
$"AutoId skipped: mode {Interlocked.Read(ref _skipMode)}, fresh {Interlocked.Read(ref _skipFresh)}, recent re-create {SkippedRecentCount}; " +
$"waited: age {Interlocked.Read(ref _skipAge)}, defer {Interlocked.Read(ref _skipDefer)}; pending now {Volatile.Read(ref _pendingCount)}" +
(Interlocked.Read(ref _overflow) > 0 ? $", overflow {Interlocked.Read(ref _overflow)}" : "") + ".",
};
}
}