AutoId review fixes: login pack sweep, refused sends kept, flight tag after send

- The login pack was never appraised: at login the PWD snapshot is cold, so ownership
  reads miss, the item classified Unknown and was skipped at 2 s. Unknown now waits
  (WaitSnapshot) until the snapshot has entries or 120 s pass, and a one-shot sweep runs
  at LoginCompleteAtMs + 30 s (and again after a hot reload's MarkAlreadyComplete, which
  restamps login): the player's owned items plus each owned side pack, uncached ones
  added as inventory work. The 5/s inventory cap still applies.
- The drain moved into AutoIdDrain.cs, a pure unit behind IAutoIdWorld, so it runs
  against a fake world in EngineRobustnessTests (cold snapshot for N seconds, then every
  pack item is sent, none before login + 30 s, at most 5 per second).
- A refused EnqueueRequestId keeps the entry, is not counted as sent, ends the tick's
  sending and does not take the inventory rate slot. The priority target is re-armed on
  refusal.
- The flight tag is registered only after _requestId returns true; the pending table is
  256 (MaxRequestIdQueue); IdentifyTagging covers 200 registrations and 200 matches.
- The 4096 pending cap applies only in Limited mode; _incoming is bounded at 16384 while
  DrainTick returns early, dropping the oldest and counting them.
- 0x0022 InventoryPutObjInContainer is read in SmartBoxHooks.ParseGameEvent so it works
  with ServerMessageStream off; ServerMessageStream is back to its base text.
- check_offthread_mutators.py: the stale DrainPending allow-list entry is replaced by
  LiveWorld's Enqueue.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Daniel Wallace 2026-10-12 16:29:54 -07:00
commit c9bbafbfb4
14 changed files with 670 additions and 218 deletions

View file

@ -6,9 +6,10 @@
// manually select each object.
//
// 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.
// items the server puts into a container (InventoryPutObjInContainer, SmartBoxHooks'
// game-event hook), from a rescan of a container the player opened, and from the
// one-shot login sweep of the pack. A background timer drains them (AutoIdDrain), at
// most AutoIdDrain.MaxPerTick sends per DrainIntervalMs.
//
// WHICH of them get an appraisal is two rules:
// - AutoIdEligibility (on create): an object the client released and re-created is
@ -18,15 +19,14 @@
// 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 (at most 5 a second); the last two wait for a
// minimum object age and a defer after login and after every world transition. All is the old behaviour; Off sends nothing.
// minimum object age and a defer after login and after every world transition.
// 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;
@ -38,18 +38,9 @@ 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;
// 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
@ -62,18 +53,7 @@ internal static class AutoIdService
private static readonly AutoIdEligibility _eligibility = new(ReappraiseWindowMs);
private static readonly object _gate = 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, 4 = rate
}
private static readonly List<Pending> _pending = new(256);
private static readonly HashSet<uint> _pendingIds = new();
private static int _pendingCount;
private static readonly AutoIdDrain _drain = new(new LiveWorld());
private static int _draining;
private static Timer? _drainTimer;
@ -87,8 +67,35 @@ internal static class AutoIdService
private static long _rescanDueMs;
private static long _skippedPriorityFresh;
private static long _skipMode, _skipAge, _skipDefer, _skipFresh, _skipRate, _overflow;
private static long _lastInventorySendMs; // drain timer only: the Inventory send cap
/// <summary>The engine behind AutoIdDrain: the PWD snapshot, the appraisal cache, eligibility, the main-thread queue.</summary>
private sealed class LiveWorld : IAutoIdWorld
{
public bool TryGetOwnership(uint id, out uint container, out uint wielder) =>
ClientObjectHooks.TryGetObjectOwnershipInfo(id, out container, out wielder, out _);
public bool SnapshotWarm => ClientObjectHooks.HasPwdSnapshot;
public int CollectOwned(uint container, Span<uint> dest) =>
ClientObjectHooks.CollectOwnedIdsFromSnapshot(container, dest);
public bool IsLive(uint id)
{
lock (_gate) return _eligibility.IsLive(id);
}
public bool HasAppraisal(uint id) => AppraisalHooks.HasAppraisalData(id);
public bool IsFresh(uint id) => AutoIdEligibility.IsAppraisalFresh(
AppraisalHooks.HasAppraisalData(id), AppraisalHooks.GetLastIdTime(id),
DateTimeOffset.UtcNow.ToUnixTimeSeconds(), ReappraiseWindowMs);
// 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 dropped there leaves it due again.
public bool Enqueue(uint id, IdRequester who) => AcMainThreadQueue.EnqueueRequestId(id, who);
}
/// <summary>Re-creates not appraised because a recent appraisal is still cached.</summary>
public static long SkippedRecentCount
@ -159,14 +166,15 @@ internal static class AutoIdService
decision = _eligibility.OnCreate(objectId, now, cached);
if (decision == AutoIdEligibility.CreateDecision.Appraise)
_incoming.Enqueue((objectId, now));
_drain.Offer(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.
/// (InventoryPutObjInContainer, game event 0x0022; SmartBoxHooks' game-event hook on AC's
/// main thread, or the Decal bridge on the 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)
{
@ -174,7 +182,7 @@ internal static class AutoIdService
return;
if (AppraisalHooks.HasAppraisalData(itemId))
return;
_incoming.Enqueue((itemId, Environment.TickCount64));
_drain.Offer(itemId, Environment.TickCount64);
}
/// <summary>
@ -233,7 +241,7 @@ 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.
// A slow tick must not overlap the next one: the drain's pending list is this timer's alone.
if (Interlocked.CompareExchange(ref _draining, 1, 0) != 0)
return;
try
@ -249,14 +257,13 @@ internal static class AutoIdService
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, 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.
// fresh. Exempt from the minimum age, the defers and the inventory cap. A
// refused enqueue forgets the change, so the next tick tries again.
uint target = SelectedTargetHooks.ReadCurrentSelectedId();
if (target != 0 && target != _lastPriorityTarget)
{
@ -265,27 +272,41 @@ internal static class AutoIdService
{
bool cached = AppraisalHooks.HasAppraisalData(target);
bool fresh = AutoIdEligibility.IsAppraisalFresh(
cached, AppraisalHooks.GetLastIdTime(target), nowUnixSec, ReappraiseWindowMs);
cached, AppraisalHooks.GetLastIdTime(target), DateTimeOffset.UtcNow.ToUnixTimeSeconds(), 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);
_drain.CountSkipFresh();
break;
case AutoIdPolicy.Verdict.Send:
if (AcMainThreadQueue.EnqueueRequestId(target, IdRequester.AutoIdTarget))
sent++;
else
_lastPriorityTarget = 0;
break;
default:
Interlocked.Increment(ref _skipMode);
_drain.CountSkipMode();
break;
}
}
}
TakeIncoming();
RescanOpenedContainer(now);
sent = DrainPending(now, mode, playerId, nowUnixSec, sent);
RescanOpenedContainer(now, mode);
uint open = ClientHelperHooks.GetGroundContainerId();
var ctx = new AutoIdDrain.Context
{
Now = now,
Mode = mode,
PlayerId = playerId,
OpenContainer = open,
OpenedAtMs = open != 0 && unchecked((uint)Volatile.Read(ref _openedContainerId)) == open
? Interlocked.Read(ref _openedAtMs) : 0,
SettleUntilMs = PlayerLifecycleLog.SettleUntilMs,
LoginCompleteAtMs = LoginLifecycleHooks.LoginCompleteAtMs,
};
_drain.Tick(ctx, sent);
// Keep the bookkeeping bounded. Here, off AC's main thread: the create path
// never prunes.
@ -310,156 +331,21 @@ internal static class AutoIdService
}
}
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)
private static void RescanOpenedContainer(long now, AutoIdMode mode)
{
long due = Interlocked.Read(ref _rescanDueMs);
if (due == 0 || now < due)
return;
Interlocked.CompareExchange(ref _rescanDueMs, 0, due);
if (Mode != AutoIdMode.Limited)
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);
}
_drain.AddContainerContents(container, Interlocked.Read(ref _openedAtMs), mode);
}
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;
long loginAt = LoginLifecycleHooks.LoginCompleteAtMs;
bool inDefer = AutoIdPolicy.InDefer(now, settleUntil, loginAt, inTransition: false);
bool openedAfterSettle = AutoIdPolicy.OpenedAfterSettle(openedAt, AutoIdPolicy.TransitionEndMs(settleUntil, loginAt));
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);
bool rateOk = AutoIdPolicy.InventoryRateAllows(now, _lastInventorySendMs);
AutoIdPolicy.Verdict v = AutoIdPolicy.Decide(mode, cls, now - p.AtMs, inDefer, openedAfterSettle, fresh, cached, rateOk);
if (v == AutoIdPolicy.Verdict.Send && cls == AutoIdPolicy.Class.Inventory && mode == AutoIdMode.Limited)
_lastInventorySendMs = now;
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.WaitRate:
if ((p.Counted & 4) == 0) { p.Counted |= 4; Interlocked.Increment(ref _skipRate); }
_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 =
@ -479,9 +365,8 @@ internal static class AutoIdService
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), sr = Interlocked.Read(ref _skipRate);
var sb = new System.Text.StringBuilder(160);
long sm = _drain.SkipMode, sa = _drain.SkipAge, sd = _drain.SkipDefer, sf = _drain.SkipFresh, sr = _drain.SkipRate;
var sb = new System.Text.StringBuilder(176);
sb.Append("autoid 60s: mode=").Append(AutoIdPolicy.Name(Mode)).Append(" sent");
long total = 0;
foreach (IdRequester who in Sources)
@ -506,8 +391,9 @@ internal static class AutoIdService
}
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).Append(" rate=").Append(sr - _lastSkipRate);
sb.Append(" pend=").Append(Volatile.Read(ref _pendingCount));
.Append(" defer=").Append(sd - _lastSkipDefer).Append(" fresh=").Append(sf - _lastSkipFresh)
.Append(" rate=").Append(sr - _lastSkipRate);
sb.Append(" pend=").Append(_drain.PendingCount);
_lastSkipMode = sm; _lastSkipAge = sa; _lastSkipDefer = sd; _lastSkipFresh = sf; _lastSkipRate = sr;
return sb.ToString();
}
@ -541,13 +427,16 @@ internal static class AutoIdService
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 login or a portal/death/teleport; inventory at most {1000 / AutoIdPolicy.InventoryMinIntervalMs}/s)",
};
string extra = "";
if (_drain.Overflow > 0) extra += $", overflow {_drain.Overflow}";
if (_drain.IncomingDropped > 0) extra += $", dropped while held {_drain.IncomingDropped}";
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)}, rate {Interlocked.Read(ref _skipRate)}; pending now {Volatile.Read(ref _pendingCount)}" +
(Interlocked.Read(ref _overflow) > 0 ? $", overflow {Interlocked.Read(ref _overflow)}" : "") + ".",
$"AutoId skipped: mode {_drain.SkipMode}, fresh {_drain.SkipFresh}, recent re-create {SkippedRecentCount}; " +
$"waited: age {_drain.SkipAge}, defer {_drain.SkipDefer}, rate {_drain.SkipRate}; refused {_drain.Refused} (kept); " +
$"login sweep {_drain.Swept}; pending now {_drain.PendingCount}{extra}.",
};
}
}