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

@ -0,0 +1,295 @@
// ============================================================================
// RynthCore.Engine - Compatibility/AutoIdDrain.cs
//
// AutoIdService's backlog: candidates in (any thread), decisions and sends out (the
// drain timer). Everything it needs from the engine comes through IAutoIdWorld, so it
// runs in tools\EngineRobustnessTests against a fake world and a fake clock.
//
// Per tick: take the new candidates, the one-shot login sweep, then look at the pending
// list in order (at most MaxEvaluatedPerTick, at most MaxPerTick sends) and decide each
// one with AutoIdPolicy. Waits stay; skips leave; a send leaves only when the main-thread
// queue took it (a refusal, in a transition or with the ring full, keeps the entry and
// ends this tick's sending).
//
// Login sweep: the pack is created before the 10 Hz object
// snapshot is warm (ClientObjectHooks.PrefetchPositions only starts after the post-login
// bootstrap), so a pack item created at login may still be unplaceable when its create
// candidate is decided. Once per login (and per hot reload, which marks a login), at
// login-complete + DeferMs and with the snapshot warm, every uncached item the player
// owns, and every item in a pack the player owns, becomes a candidate. The 5 a second
// Inventory cap still applies. An Unknown candidate also waits for the snapshot (up to
// AutoIdPolicy.UnknownMaxWaitMs) instead of being dropped at MinAgeMs.
//
// Bounds: _incoming is capped at MaxIncoming (oldest dropped, counted) because the drain
// returns early through a world transition (a long death); the pending list is capped at
// MaxPendingLimited in Limited mode only (All keeps the old unbounded backlog).
// ============================================================================
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Threading;
using RynthCore.Engine.Net;
namespace RynthCore.Engine.Compatibility;
/// <summary>What AutoIdDrain reads and does in the engine (a fake in the tests).</summary>
internal interface IAutoIdWorld
{
/// <summary>The object's container and wielder from the object snapshot; false when it is not in it.</summary>
bool TryGetOwnership(uint id, out uint container, out uint wielder);
/// <summary>The object snapshot has been filled at least once (it holds any object at all).</summary>
bool SnapshotWarm { get; }
/// <summary>Ids whose container or wielder is <paramref name="container"/>, from the snapshot.</summary>
int CollectOwned(uint container, Span<uint> dest);
/// <summary>Created and not released (AutoIdEligibility).</summary>
bool IsLive(uint id);
/// <summary>Its appraisal is cached.</summary>
bool HasAppraisal(uint id);
/// <summary>Its appraisal is cached and recent.</summary>
bool IsFresh(uint id);
/// <summary>Queue the 0xC8 for AC's main thread; false = refused (transition, ring full).</summary>
bool Enqueue(uint id, IdRequester who);
}
internal sealed class AutoIdDrain
{
public const int MaxPerTick = 3;
public const int MaxEvaluatedPerTick = 512;
public const int MaxPendingLimited = 4096;
public const int MaxIncoming = 16384;
public const int MaxSweepItems = 512;
/// <summary>One tick's view of the engine (read by AutoIdService each tick).</summary>
public struct Context
{
public long Now;
public AutoIdMode Mode;
public uint PlayerId;
public uint OpenContainer;
public long OpenedAtMs; // when OpenContainer was opened (0 = unknown)
public long SettleUntilMs; // PlayerLifecycleLog.SettleUntilMs
public long LoginCompleteAtMs; // LoginLifecycleHooks.LoginCompleteAtMs
}
private struct Pending
{
public uint Id;
public long AtMs; // created (or moved, or its container opened, or swept) at
public byte Counted; // waits already counted: 1 = age, 2 = defer, 4 = rate
}
private readonly IAutoIdWorld _w;
private readonly ConcurrentQueue<(uint Id, long AtMs)> _incoming = new();
private int _incomingCount;
private readonly List<Pending> _pending = new(256);
private readonly HashSet<uint> _pendingIds = new();
private int _pendingCount;
private long _lastInventorySendMs;
private long _sweptLoginAt;
private long _skipMode, _skipAge, _skipDefer, _skipFresh, _skipRate, _overflow, _incomingDropped, _refused, _swept;
public AutoIdDrain(IAutoIdWorld world) { _w = world; }
public long SkipMode => Interlocked.Read(ref _skipMode);
public long SkipAge => Interlocked.Read(ref _skipAge);
public long SkipDefer => Interlocked.Read(ref _skipDefer);
public long SkipFresh => Interlocked.Read(ref _skipFresh);
public long SkipRate => Interlocked.Read(ref _skipRate);
/// <summary>Candidates not taken because the Limited pending list was full.</summary>
public long Overflow => Interlocked.Read(ref _overflow);
/// <summary>Oldest new candidates dropped because _incoming was full (the drain was held).</summary>
public long IncomingDropped => Interlocked.Read(ref _incomingDropped);
/// <summary>Sends the main-thread queue refused (kept and tried again).</summary>
public long Refused => Interlocked.Read(ref _refused);
/// <summary>Items the login sweeps made candidates.</summary>
public long Swept => Interlocked.Read(ref _swept);
public int PendingCount => Volatile.Read(ref _pendingCount);
/// <summary>The selected-target path counts its fresh / mode skips here too.</summary>
public void CountSkipFresh() => Interlocked.Increment(ref _skipFresh);
public void CountSkipMode() => Interlocked.Increment(ref _skipMode);
/// <summary>A new candidate (any thread). Past MaxIncoming the oldest waiting one is dropped.</summary>
public void Offer(uint id, long atMs)
{
if (id == 0) return;
_incoming.Enqueue((id, atMs));
if (Interlocked.Increment(ref _incomingCount) > MaxIncoming && _incoming.TryDequeue(out _))
{
Interlocked.Decrement(ref _incomingCount);
Interlocked.Increment(ref _incomingDropped);
}
}
/// <summary>Drain thread: the items in <paramref name="container"/> with nothing cached become candidates.</summary>
public void AddContainerContents(uint container, long atMs, AutoIdMode mode)
{
if (container == 0) return;
Span<uint> ids = stackalloc uint[256];
int n = _w.CollectOwned(container, ids);
for (int i = 0; i < n; i++)
if (_w.IsLive(ids[i]) && !_w.HasAppraisal(ids[i]))
AddPending(ids[i], atMs, mode);
}
/// <summary>Drain thread, once per timer tick. Returns the sends so far (starting at <paramref name="sent"/>).</summary>
public int Tick(in Context c, int sent)
{
TakeIncoming(c.Mode);
LoginSweep(c);
return DrainPending(c, sent);
}
private void TakeIncoming(AutoIdMode mode)
{
while (_incoming.TryDequeue(out (uint Id, long AtMs) x))
{
Interlocked.Decrement(ref _incomingCount);
AddPending(x.Id, x.AtMs, mode);
}
}
private void AddPending(uint id, long atMs, AutoIdMode mode)
{
if (id == 0 || _pendingIds.Contains(id))
return;
if (mode != AutoIdMode.All && _pending.Count >= MaxPendingLimited)
{
Interlocked.Increment(ref _overflow);
return;
}
_pendingIds.Add(id);
_pending.Add(new Pending { Id = id, AtMs = atMs });
}
/// <summary>Once per login-complete stamp, at login + DeferMs with the snapshot warm: the uncached pack.</summary>
private void LoginSweep(in Context c)
{
if (c.Mode != AutoIdMode.Limited || c.LoginCompleteAtMs <= 0 || c.LoginCompleteAtMs == _sweptLoginAt)
return;
if (c.Now < c.LoginCompleteAtMs + AutoIdPolicy.DeferMs || c.PlayerId == 0 || !_w.SnapshotWarm)
return;
_sweptLoginAt = c.LoginCompleteAtMs;
Span<uint> top = stackalloc uint[MaxSweepItems];
Span<uint> inner = stackalloc uint[MaxSweepItems];
int n = _w.CollectOwned(c.PlayerId, top);
int before = _pending.Count;
for (int i = 0; i < n; i++)
{
uint id = top[i];
if (_w.IsLive(id) && !_w.HasAppraisal(id))
AddPending(id, c.LoginCompleteAtMs, c.Mode);
// A side pack (or anything else holding items): its contents are the pack too.
int m = _w.CollectOwned(id, inner);
for (int k = 0; k < m; k++)
if (_w.IsLive(inner[k]) && !_w.HasAppraisal(inner[k]))
AddPending(inner[k], c.LoginCompleteAtMs, c.Mode);
}
Interlocked.Add(ref _swept, _pending.Count - before);
}
private int DrainPending(in Context c, int sent)
{
if (_pending.Count == 0)
{
Volatile.Write(ref _pendingCount, 0);
return sent;
}
long transitionEnd = AutoIdPolicy.TransitionEndMs(c.SettleUntilMs, c.LoginCompleteAtMs);
bool inDefer = AutoIdPolicy.InDefer(c.Now, c.SettleUntilMs, c.LoginCompleteAtMs, inTransition: false);
bool openedAfterSettle = AutoIdPolicy.OpenedAfterSettle(c.OpenedAtMs, transitionEnd);
bool snapshotWarm = _w.SnapshotWarm;
bool sending = true;
int keep = 0, evaluated = 0;
for (int i = 0; i < _pending.Count; i++)
{
Pending p = _pending[i];
if (!sending || sent >= MaxPerTick || evaluated >= MaxEvaluatedPerTick)
{
_pending[keep++] = p;
continue;
}
evaluated++;
// Released since it was queued: gone, without spending a send.
if (!_w.IsLive(p.Id))
{
_pendingIds.Remove(p.Id);
continue;
}
AutoIdPolicy.Class cls = Classify(p.Id, c.PlayerId, c.OpenContainer);
bool cached = _w.HasAppraisal(p.Id);
bool fresh = cached && _w.IsFresh(p.Id);
bool rateOk = AutoIdPolicy.InventoryRateAllows(c.Now, _lastInventorySendMs);
AutoIdPolicy.Verdict v = AutoIdPolicy.Decide(c.Mode, cls, c.Now - p.AtMs, inDefer, openedAfterSettle,
fresh, cached, rateOk, snapshotWarm);
switch (v)
{
case AutoIdPolicy.Verdict.Send:
if (!_w.Enqueue(p.Id, RequesterFor(cls)))
{
// Refused (a transition began, or the ring is full): keep it, and
// stop sending this tick.
Interlocked.Increment(ref _refused);
_pending[keep++] = p;
sending = false;
break;
}
sent++;
if (cls == AutoIdPolicy.Class.Inventory && c.Mode == AutoIdMode.Limited)
_lastInventorySendMs = c.Now;
_pendingIds.Remove(p.Id);
break;
case AutoIdPolicy.Verdict.WaitAge:
case AutoIdPolicy.Verdict.WaitSnapshot:
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 snapshot.</summary>
private AutoIdPolicy.Class Classify(uint id, uint playerId, uint open)
{
if (!_w.TryGetOwnership(id, out uint container, out uint wielder))
return AutoIdPolicy.Classify(false, playerId, open, 0, 0, 0);
uint parent = 0;
if (container != 0 && container != playerId && container != open
&& _w.TryGetOwnership(container, out uint cc, out _))
parent = cc;
return AutoIdPolicy.Classify(true, playerId, open, container, wielder, parent);
}
public 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,
};
}

View file

@ -60,6 +60,13 @@ internal static class AutoIdPolicy
/// </summary>
public const long InventoryMinIntervalMs = 200;
/// <summary>
/// An object whose place is unknown because the object snapshot has not been filled yet
/// (at login the pack is created before ClientObjectHooks.PrefetchPositions starts) waits
/// for it this long at most before it is dropped.
/// </summary>
public const long UnknownMaxWaitMs = 120_000;
public enum Class
{
/// <summary>The selected target (the priority path).</summary>
@ -88,6 +95,8 @@ internal static class AutoIdPolicy
SkipFresh,
/// <summary>Inventory over its send rate (InventoryMinIntervalMs): keep it and ask again later.</summary>
WaitRate,
/// <summary>Place unknown and the object snapshot still empty: keep it (up to UnknownMaxWaitMs).</summary>
WaitSnapshot,
}
/// <summary>
@ -99,9 +108,11 @@ internal static class AutoIdPolicy
/// <paramref name="fresh"/>: its appraisal is cached and recent (Target, Container).
/// <paramref name="cached"/>: its appraisal is cached at all (Inventory).
/// <paramref name="inventoryRateOk"/>: Inventory only, the send rate allows one now (<see cref="InventoryRateAllows"/>).
/// <paramref name="snapshotWarm"/>: Unknown only, the object snapshot has been filled (an
/// object missing from a warm snapshot is not coming; one missing from a cold one may be).
/// </summary>
public static Verdict Decide(AutoIdMode mode, Class cls, long ageMs, bool inDefer, bool openedAfterSettle,
bool fresh, bool cached, bool inventoryRateOk = true)
bool fresh, bool cached, bool inventoryRateOk = true, bool snapshotWarm = true)
{
switch (mode)
{
@ -133,7 +144,10 @@ internal static class AutoIdPolicy
case Class.Unknown:
// Its place shows up in the snapshot within a tick or two; until it is
// MinAgeMs old it may still turn out to be in the open container or the pack.
return ageMs < MinAgeMs ? Verdict.WaitAge : Verdict.SkipMode;
// While the snapshot has never been filled (login), it waits for it.
if (ageMs < MinAgeMs) return Verdict.WaitAge;
if (!snapshotWarm && ageMs < UnknownMaxWaitMs) return Verdict.WaitSnapshot;
return Verdict.SkipMode;
default: // World
return Verdict.SkipMode;
}

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}.",
};
}
}

View file

@ -3835,6 +3835,11 @@ internal static class ClientObjectHooks
/// container or wielder is <paramref name="containerId"/> from the main-thread
/// snapshot, under one lock, with no AC access. Returns the count written.
/// </summary>
internal static bool HasPwdSnapshot
{
get { lock (_weeniePtrSwapLock) return _pwdFront.Count > 0; }
}
internal static int CollectOwnedIdsFromSnapshot(uint containerId, Span<uint> dest)
{
int found = 0;

View file

@ -470,11 +470,15 @@ internal static class CombatActionHooks
try
{
if (who != Net.IdRequester.None)
Net.FlightRecorder.EngineSend((byte)who, objectId);
bool sent = _requestId(objectId);
if (sent)
{
// Registered only once the call succeeded, so a failed call leaves nothing to
// mis-tag a later 0xC8 for the same object.
if (who != Net.IdRequester.None)
Net.FlightRecorder.EngineSend((byte)who, objectId);
Net.IdSendStats.CountSent(who);
}
return sent;
}
catch

View file

@ -392,6 +392,15 @@ internal static class SmartBoxHooks
RecordWeenieError(eventType, unchecked((uint)Marshal.ReadInt32(IntPtr.Add(data, 4))), 0);
break;
case 0x0022: // InventoryPutObjInContainer: [item u32][container u32][placement][type].
// AutoId (Limited): an item that landed in the player's inventory with
// nothing cached is a candidate. Here, not on the server message stream,
// so it works with that stream off (engine.json / /rc netmsg off).
if (size >= 12)
AutoIdService.OnPutInContainer(
unchecked((uint)Marshal.ReadInt32(IntPtr.Add(data, 4))),
unchecked((uint)Marshal.ReadInt32(IntPtr.Add(data, 8))));
break;
case 0x00A0: // InventoryServerSaveFailed: [objectId u32][errorType u32] —
// the server refused an inventory change (wield, move, ...).
// Layout from UIQueueManager::ProcessNetBlobData's inline case

View file

@ -598,9 +598,10 @@ internal sealed unsafe class FlightCapture
// -- engine IdentifyObject (0xC8) sends --
// Kept apart from _pending: AutoId alone can send 30 a second, which would push every
// other engine call out of that 16-entry table. No marker line per send: the tag on the
// 0xC8 itself ([eng:<who>]) says who asked.
// 0xC8 itself ([eng:<who>]) says who asked. 256 entries = AcMainThreadQueue's
// MaxRequestIdQueue: one drain can send a whole full queue before any of it reaches sendto.
private struct IdPending { public uint Id; public byte Who; public long Stamp; public bool Used; }
private readonly IdPending[] _idPending = new IdPending[64];
private readonly IdPending[] _idPending = new IdPending[256];
private int _idPendingNext;
private long _identifyForeign;

View file

@ -226,14 +226,6 @@ internal static unsafe class ServerMessageStream
try { Compatibility.AutoIdService.OnServerDelete(AcPacketWire.ReadU32(message + 4)); }
catch (Exception ex) { RynthLog.Compat($"ServerMessageStream: server delete failed - {ex.GetType().Name}: {ex.Message}"); }
}
// InventoryPutObjInContainer (game event 0x0022: item, container, ...): an item
// landed in a container. AutoId's Limited mode appraises one that landed in the
// player's own inventory with nothing cached (AutoIdPolicy).
else if (eventType == InventoryOrder.EventPutObjInContainer && length >= 24)
{
try { Compatibility.AutoIdService.OnPutInContainer(AcPacketWire.ReadU32(message + 16), AcPacketWire.ReadU32(message + 20)); }
catch (Exception ex) { RynthLog.Compat($"ServerMessageStream: put-in-container failed - {ex.GetType().Name}: {ex.Message}"); }
}
}
if (_pluginsWant)
_dispatchedToPlugins += PluginManager.DispatchServerMessage(opcode, eventType, message + 4, length - 4);

View file

@ -0,0 +1,232 @@
using RynthCore.Engine.Compatibility;
using RynthCore.Engine.Net;
namespace EngineRobustnessTests;
/// <summary>
/// AutoIdDrain against a fake world and a fake clock: the pack
/// created before the object snapshot is warm still gets appraised, a refused enqueue
/// is kept, and the bounds.
/// </summary>
internal static partial class Program
{
private sealed class FakeWorld : IAutoIdWorld
{
public bool Warm;
public readonly Dictionary<uint, (uint Container, uint Wielder)> Snapshot = new();
public readonly HashSet<uint> Cached = new();
public readonly HashSet<uint> Released = new();
public bool Refuse;
public readonly List<(uint Id, IdRequester Who, long At)> Sent = new();
public long Now;
public bool TryGetOwnership(uint id, out uint container, out uint wielder)
{
container = wielder = 0;
if (!Warm || !Snapshot.TryGetValue(id, out var e)) return false;
container = e.Container; wielder = e.Wielder;
return true;
}
public bool SnapshotWarm => Warm;
public int CollectOwned(uint container, Span<uint> dest)
{
if (!Warm) return 0;
int n = 0;
foreach (var kv in Snapshot)
{
if (n >= dest.Length) break;
if (kv.Key != container && (kv.Value.Container == container || kv.Value.Wielder == container)) dest[n++] = kv.Key;
}
return n;
}
public bool IsLive(uint id) => !Released.Contains(id);
public bool HasAppraisal(uint id) => Cached.Contains(id);
public bool IsFresh(uint id) => Cached.Contains(id);
public bool Enqueue(uint id, IdRequester who)
{
if (Refuse) return false;
Sent.Add((id, who, Now));
Cached.Add(id); // the reply lands
return true;
}
}
private const uint Me = 0x50000001, SidePack = 0x80000900;
private static AutoIdDrain.Context Ctx(FakeWorld w, long loginAt, AutoIdMode mode = AutoIdMode.Limited, long settle = 0) => new()
{
Now = w.Now, Mode = mode, PlayerId = Me, OpenContainer = 0, OpenedAtMs = 0, SettleUntilMs = settle, LoginCompleteAtMs = loginAt,
};
/// <summary>Runs the 100 ms drain from w.Now to <paramref name="until"/>.</summary>
private static void RunUntil(AutoIdDrain d, FakeWorld w, long until, long loginAt, AutoIdMode mode = AutoIdMode.Limited, Action? each = null)
{
for (; w.Now <= until; w.Now += 100)
{
each?.Invoke();
d.Tick(Ctx(w, loginAt, mode), 0);
}
}
private static void RunAutoIdDrainTests()
{
DrainLoginPackWithColdSnapshot();
DrainLoginSweep();
DrainUnknownWaitsForSnapshotThenGivesUp();
DrainRefusedEnqueueIsKept();
DrainBounds();
}
// The pack is created at login, before the snapshot is warm; it must still go out.
private static void DrainLoginPackWithColdSnapshot()
{
_case = "drain login pack, cold snapshot";
var w = new FakeWorld { Now = 10_000 };
var d = new AutoIdDrain(w);
// The login create burst: 20 pack items and a side pack with 5 more, created at 10 s.
var pack = new List<uint>();
for (uint i = 1; i <= 20; i++) { pack.Add(0x80001000 + i); w.Snapshot[0x80001000 + i] = (Me, 0); }
w.Snapshot[SidePack] = (Me, 0);
pack.Add(SidePack);
for (uint i = 1; i <= 5; i++) { pack.Add(0x80002000 + i); w.Snapshot[0x80002000 + i] = (SidePack, 0); }
foreach (uint id in pack) d.Offer(id, w.Now);
const long LoginAt = 12_000;
const long WarmAt = 40_000; // the snapshot starts 28 s after login-complete (cold for N seconds)
// Before login completes, and while the snapshot is cold: nothing is sent, nothing dropped.
RunUntil(d, w, LoginAt - 100, loginAt: 0);
Check(w.Sent.Count == 0, $"nothing before login-complete, sent {w.Sent.Count}");
RunUntil(d, w, WarmAt - 100, LoginAt);
Check(w.Sent.Count == 0, $"nothing while the snapshot is cold, sent {w.Sent.Count}");
Check(d.PendingCount == pack.Count, $"all {pack.Count} kept while the snapshot is cold, pending {d.PendingCount}");
w.Warm = true;
RunUntil(d, w, 120_000, LoginAt);
var sentIds = w.Sent.Select(s => s.Id).ToHashSet();
Check(pack.All(sentIds.Contains), $"every pack item eventually sent ({sentIds.Count}/{pack.Count})");
Check(w.Sent.All(s => s.Who == IdRequester.AutoIdInventory), "all as autoid-inventory");
Check(w.Sent.Min(s => s.At) >= LoginAt + AutoIdPolicy.DeferMs, "none before login + DeferMs");
int worst = w.Sent.Max(s => w.Sent.Count(t => t.At >= s.At && t.At < s.At + 1_000));
Check(worst <= 5, $"at most 5 a second, got {worst}");
}
// The one-shot sweep at login + DeferMs, also after a hot reload (a new login stamp).
private static void DrainLoginSweep()
{
_case = "drain login sweep";
var w = new FakeWorld { Now = 100_000, Warm = true };
var d = new AutoIdDrain(w);
for (uint i = 1; i <= 8; i++) w.Snapshot[0x80003000 + i] = (Me, 0); // main pack, never offered
w.Snapshot[SidePack] = (Me, 0);
for (uint i = 1; i <= 4; i++) w.Snapshot[0x80004000 + i] = (SidePack, 0); // side pack contents
w.Snapshot[0x80005000] = (0, Me); // worn
w.Cached.Add(0x80003001); // already appraised
w.Snapshot[0x80006000] = (0, 0); // a ground item: not ours
long loginAt = 100_000;
RunUntil(d, w, loginAt + AutoIdPolicy.DeferMs - 100, loginAt);
Check(w.Sent.Count == 0, $"no sweep before login + DeferMs, sent {w.Sent.Count}");
RunUntil(d, w, loginAt + AutoIdPolicy.DeferMs + 10_000, loginAt);
var ids = w.Sent.Select(s => s.Id).ToHashSet();
Check(Enumerable.Range(2, 7).All(i => ids.Contains(0x80003000 + (uint)i)), "the uncached main-pack items are swept");
Check(!ids.Contains(0x80003001), "a cached one is not");
Check(Enumerable.Range(1, 4).All(i => ids.Contains(0x80004000 + (uint)i)), "the side pack's contents are swept");
Check(ids.Contains(SidePack) && ids.Contains(0x80005000), "the side pack itself and worn gear are swept");
Check(!ids.Contains(0x80006000), "a ground item is not");
Check(d.Swept == 13, $"13 swept (7 main pack, the side pack, its 4, 1 worn), got {d.Swept}");
int count = w.Sent.Count;
// The same login: no second sweep, even with new uncached items.
w.Snapshot[0x80007000] = (Me, 0);
RunUntil(d, w, w.Now + 5_000, loginAt);
Check(w.Sent.Count == count, "one sweep per login");
// A hot reload (MarkAlreadyComplete) stamps a new login: swept again after its defer.
long reloadAt = w.Now;
RunUntil(d, w, reloadAt + AutoIdPolicy.DeferMs + 2_000, reloadAt);
Check(w.Sent.Any(s => s.Id == 0x80007000), "a new login stamp sweeps again");
// All mode never sweeps (it appraises every create anyway).
var w2 = new FakeWorld { Now = 100_000, Warm = true };
w2.Snapshot[0x80008000] = (Me, 0);
var d2 = new AutoIdDrain(w2);
RunUntil(d2, w2, 100_000 + AutoIdPolicy.DeferMs + 5_000, 100_000, AutoIdMode.All);
Check(w2.Sent.Count == 0, "All mode: no sweep");
}
private static void DrainUnknownWaitsForSnapshotThenGivesUp()
{
_case = "drain unknown";
// Warm snapshot, object not in it: dropped at MinAgeMs (a creature gone, or never placed).
var w = new FakeWorld { Now = 1_000_000, Warm = true };
var d = new AutoIdDrain(w);
d.Offer(0x80009001, w.Now);
RunUntil(d, w, w.Now + AutoIdPolicy.MinAgeMs + 200, loginAt: 1);
Check(d.PendingCount == 0 && d.SkipMode == 1, $"warm snapshot: dropped after MinAgeMs (pending {d.PendingCount}, skipMode {d.SkipMode})");
// Cold snapshot that never warms: kept until UnknownMaxWaitMs, then dropped.
var c = new FakeWorld { Now = 1_000_000 };
var e = new AutoIdDrain(c);
e.Offer(0x80009002, c.Now);
long t0 = c.Now;
RunUntil(e, c, t0 + AutoIdPolicy.UnknownMaxWaitMs - 200, loginAt: 1);
Check(e.PendingCount == 1, "cold snapshot: still kept just before UnknownMaxWaitMs");
RunUntil(e, c, t0 + AutoIdPolicy.UnknownMaxWaitMs + 200, loginAt: 1);
Check(e.PendingCount == 0 && e.SkipMode == 1, "cold snapshot: dropped at UnknownMaxWaitMs");
}
// A refused enqueue (transition, full ring) is kept, not counted, and sent later.
private static void DrainRefusedEnqueueIsKept()
{
_case = "drain refused enqueue";
var w = new FakeWorld { Now = 1_000_000, Warm = true, Refuse = true };
var d = new AutoIdDrain(w);
for (uint i = 1; i <= 3; i++) { w.Snapshot[0x8000A000 + i] = (0, 0); d.Offer(0x8000A000 + i, w.Now); }
int sent = d.Tick(Ctx(w, 1, AutoIdMode.All), 0);
Check(sent == 0, $"a refused send is not counted as sent, got {sent}");
Check(d.PendingCount == 3, $"all three kept, pending {d.PendingCount}");
Check(d.Refused == 1, $"the first refusal ends the tick's sending (1 refused), got {d.Refused}");
w.Now += 100;
w.Refuse = false;
sent = d.Tick(Ctx(w, 1, AutoIdMode.All), 0);
Check(sent == 3 && w.Sent.Count == 3 && d.PendingCount == 0, $"sent once accepted (sent {sent}, pending {d.PendingCount})");
// The inventory cap counts only a send that was taken.
var v = new FakeWorld { Now = 1_000_000, Warm = true, Refuse = true };
var e = new AutoIdDrain(v);
v.Snapshot[0x8000B001] = (Me, 0); v.Snapshot[0x8000B002] = (Me, 0);
e.Offer(0x8000B001, 0); e.Offer(0x8000B002, 0);
e.Tick(Ctx(v, 1), 0);
v.Refuse = false; v.Now += 100;
e.Tick(Ctx(v, 1), 0);
Check(v.Sent.Count == 1, $"a refused inventory send did not use up the rate slot (sent {v.Sent.Count})");
}
// All mode keeps the old unbounded backlog; Limited is capped; _incoming is bounded.
private static void DrainBounds()
{
_case = "drain bounds";
var w = new FakeWorld { Now = 1_000, Warm = true };
var d = new AutoIdDrain(w);
int n = AutoIdDrain.MaxPendingLimited + 500;
for (uint i = 0; i < n; i++) { w.Snapshot[0x81000000 + i] = (0, 0); d.Offer(0x81000000 + i, w.Now); }
d.Tick(Ctx(w, 0, AutoIdMode.All), AutoIdDrain.MaxPerTick); // no sends: just take them in
Check(d.PendingCount == n && d.Overflow == 0, $"All: all {n} pending (got {d.PendingCount}, overflow {d.Overflow})");
var l = new FakeWorld { Now = 1_000, Warm = true };
var e = new AutoIdDrain(l);
for (uint i = 0; i < n; i++) e.Offer(0x82000000 + i, l.Now);
e.Tick(Ctx(l, 0, AutoIdMode.Limited), AutoIdDrain.MaxPerTick);
Check(e.PendingCount == AutoIdDrain.MaxPendingLimited && e.Overflow == 500,
$"Limited: capped at {AutoIdDrain.MaxPendingLimited}, 500 counted (got {e.PendingCount}, {e.Overflow})");
// While the drain is held (a long death), _incoming keeps the newest MaxIncoming.
var h = new FakeWorld { Now = 1_000, Warm = true };
var f = new AutoIdDrain(h);
int over = 37;
for (uint i = 0; i < AutoIdDrain.MaxIncoming + over; i++) f.Offer(0x83000000 + i, h.Now);
Check(f.IncomingDropped == over, $"{over} oldest dropped and counted, got {f.IncomingDropped}");
f.Tick(Ctx(h, 0, AutoIdMode.All), AutoIdDrain.MaxPerTick);
Check(f.PendingCount == AutoIdDrain.MaxIncoming, $"the newest {AutoIdDrain.MaxIncoming} kept, got {f.PendingCount}");
}
}

View file

@ -27,10 +27,10 @@ internal static partial class Program
// ---- the decision table ---------------------------------------------------------
private static readonly long[] Ages = { 0, AutoIdPolicy.MinAgeMs - 1, AutoIdPolicy.MinAgeMs, 60_000 };
private static readonly long[] Ages = { 0, AutoIdPolicy.MinAgeMs - 1, AutoIdPolicy.MinAgeMs, 60_000, AutoIdPolicy.UnknownMaxWaitMs - 1, AutoIdPolicy.UnknownMaxWaitMs };
/// <summary>The rule as the spec states it, written out independently of AutoIdPolicy.Decide.</summary>
private static V Expected(AutoIdMode mode, C cls, long age, bool defer, bool openedAfter, bool fresh, bool cached, bool rateOk)
private static V Expected(AutoIdMode mode, C cls, long age, bool defer, bool openedAfter, bool fresh, bool cached, bool rateOk, bool warm)
{
if (mode == AutoIdMode.Off) return V.SkipMode;
if (mode == AutoIdMode.All) return cls == C.Target && fresh ? V.SkipFresh : V.Send;
@ -40,7 +40,7 @@ internal static partial class Program
C.Target => fresh ? V.SkipFresh : V.Send,
C.Container => fresh ? V.SkipFresh : young ? V.WaitAge : defer && !openedAfter ? V.WaitDefer : V.Send,
C.Inventory => cached ? V.SkipFresh : young ? V.WaitAge : defer ? V.WaitDefer : !rateOk ? V.WaitRate : V.Send,
C.Unknown => young ? V.WaitAge : V.SkipMode,
C.Unknown => young ? V.WaitAge : !warm && age < AutoIdPolicy.UnknownMaxWaitMs ? V.WaitSnapshot : V.SkipMode,
_ => V.SkipMode,
};
}
@ -57,16 +57,17 @@ internal static partial class Program
foreach (bool cached in new[] { false, true })
foreach (bool fresh in new[] { false, true })
foreach (bool rateOk in new[] { false, true })
foreach (bool warm in new[] { false, true })
{
if (fresh && !cached) continue; // fresh implies cached
rows++;
V got = AutoIdPolicy.Decide(mode, cls, age, defer, opened, fresh, cached, rateOk);
V want = Expected(mode, cls, age, defer, opened, fresh, cached, rateOk);
V got = AutoIdPolicy.Decide(mode, cls, age, defer, opened, fresh, cached, rateOk, warm);
V want = Expected(mode, cls, age, defer, opened, fresh, cached, rateOk, warm);
if (got != want && wrong++ < 10)
Check(false, $"{mode} {cls} age={age} defer={defer} opened={opened} cached={cached} fresh={fresh} rateOk={rateOk}: want {want}, got {got}");
Check(false, $"{mode} {cls} age={age} defer={defer} opened={opened} cached={cached} fresh={fresh} rateOk={rateOk} warm={warm}: want {want}, got {got}");
}
Check(wrong == 0, $"{wrong} of {rows} rows wrong");
Check(rows == 3 * 5 * 4 * 2 * 2 * 3 * 2, $"row count {rows}");
Check(rows == 3 * 5 * 6 * 2 * 2 * 3 * 2 * 2, $"row count {rows}");
}
/// <summary>The same rules as named cases, so a mutation is easy to read off a failure.</summary>

View file

@ -17,6 +17,8 @@
CastSlot.cs the cast slot refuses during a world transition
CrashExitRule.cs which exit codes are crash exits (not ExitProcess(-1))
AutoIdPolicy.cs AutoIdMode All/Limited/Off: class, minimum age, post-transition defer
AutoIdDrain.cs the AutoId backlog against a fake world: login sweep, cold snapshot,
refused sends kept, bounds
IdRequester.cs the engine-send marker that tags every engine 0xC8
Run: dotnet run -c Release (exit 0 = pass, 1 = fail)
-->
@ -43,6 +45,7 @@
<Compile Include="..\..\src\RynthCore.Engine\Compatibility\CastSlot.cs" Link="Engine\CastSlot.cs" />
<Compile Include="..\..\src\RynthCore.Engine\Compatibility\CrashExitRule.cs" Link="Engine\CrashExitRule.cs" />
<Compile Include="..\..\src\RynthCore.Engine\Compatibility\AutoIdPolicy.cs" Link="Engine\AutoIdPolicy.cs" />
<Compile Include="..\..\src\RynthCore.Engine\Compatibility\AutoIdDrain.cs" Link="Engine\AutoIdDrain.cs" />
<Compile Include="..\..\src\RynthCore.Engine\Net\IdRequester.cs" Link="Engine\IdRequester.cs" />
</ItemGroup>

View file

@ -43,6 +43,7 @@ internal static partial class Program
RunRingAndGateTests();
RunAutoIdLimitTests();
RunAutoIdDrainTests();
Console.WriteLine($"{_checks} check(s), {_failed} failed.");
return _failed == 0 ? 0 : 1;

View file

@ -420,15 +420,21 @@ internal static unsafe class Program
Out(c, Identify(Corpse));
Has(Last(c), "[cli]", "a send without a requester is not registered");
// 64 sends in a burst do not push out other engine calls (their own table).
// 200 sends in a burst (a full RequestId queue drained at once) do not push out other
// engine calls (their own table), and every one of them is matched.
c.EngineCall("UseObject", Corpse, 0);
for (uint i = 0; i < 64; i++) c.EngineSend((byte)IdRequester.AutoIdWorld, 0x80100000 + i);
for (uint i = 0; i < 200; i++) c.EngineSend((byte)IdRequester.AutoIdWorld, 0x80100000 + i);
Out(c, Use(Corpse));
Has(Last(c), "[eng] Use", "an identify burst leaves the pending use intact");
Out(c, Identify(0x80100000 + 63));
Has(Last(c), "[eng:autoid-world]", "the newest send of the burst still matches");
Out(c, Identify(0x80100000));
Has(Last(c), "[eng:autoid-world]", "and so does the oldest: 64 sends inside the match window all keep their slot");
long foreignBefore = c.IdentifyForeignTotal;
int matched = 0;
for (uint i = 0; i < 200; i++)
{
Out(c, Identify(0x80100000 + i));
if (Last(c).Contains("[eng:autoid-world] IdentifyObject", StringComparison.Ordinal)) matched++;
}
Eq(matched, 200, "200 registrations, 200 tagged identifies (oldest to newest)");
Eq(c.IdentifyForeignTotal, foreignBefore, "none of the burst counted as foreign");
foreach (IdRequester who in Enum.GetValues<IdRequester>())
{

View file

@ -98,7 +98,7 @@ ENQUEUE = "AcMainThreadQueue.Enqueue"
# (file, method) pairs, each verified to do no off-thread AC mutation.
ENQUEUE_PRODUCER_ALLOW = {
("AutoIdService.cs", "DrainTick"), # appraisal: enqueues 0xC8, sent on main thread in DrainRequestIds
("AutoIdService.cs", "DrainPending"), # DrainTick's backlog half: only EnqueueRequestId; reads the PWD snapshot
("AutoIdService.cs", "Enqueue"), # LiveWorld.Enqueue, called from AutoIdDrain on the drain timer: only EnqueueRequestId
("RynthCoreChatCommands.cs", "Reply"), # /rc and /rv plates replies: only EnqueueWriteToChat
("AcMouseOver.cs", "Say"), # /rc acmouse watch lines: only EnqueueWriteToChat (and the log)
}