From aaaa0a94b49bc700c4d66685b9b042188ff81508 Mon Sep 17 00:00:00 2001 From: Daniel Wallace Date: Sat, 10 Oct 2026 23:09:15 -0700 Subject: [PATCH] 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) --- .../Compatibility/AcMainThreadQueue.cs | 13 +- .../Compatibility/AutoIdPolicy.cs | 176 ++++++++ .../Compatibility/AutoIdService.cs | 415 +++++++++++++++--- .../Compatibility/ClientHelperHooks.cs | 1 + .../Compatibility/CombatActionHooks.cs | 13 +- .../Compatibility/HeartbeatLogger.cs | 7 + .../Compatibility/InventoryModel.cs | 3 +- .../Compatibility/PendingIdQueue.cs | 9 +- .../Compatibility/PlayerLifecycleLog.cs | 7 + .../Compatibility/RynthCoreChatCommands.cs | 15 + src/RynthCore.Engine/Net/FlightCapture.cs | 61 ++- src/RynthCore.Engine/Net/FlightFormat.cs | 6 +- src/RynthCore.Engine/Net/FlightRecorder.cs | 19 + src/RynthCore.Engine/Net/FlightRing.cs | 7 +- src/RynthCore.Engine/Net/IdRequester.cs | 116 +++++ .../Net/ServerMessageStream.cs | 8 + .../Plugins/EngineSettings.cs | 29 +- src/RynthCore.Engine/Plugins/PluginManager.cs | 7 +- .../EngineRobustnessTests/AutoIdLimitTests.cs | 254 +++++++++++ .../EngineRobustnessTests.csproj | 4 + tools/EngineRobustnessTests/Program.cs | 2 + .../EngineSettingsTests.csproj | 1 + tools/EngineSettingsTests/Program.cs | 33 ++ .../FlightRecorderTests.csproj | 1 + tools/FlightRecorderTests/Program.cs | 59 +++ tools/check_offthread_mutators.py | 1 + 26 files changed, 1198 insertions(+), 69 deletions(-) create mode 100644 src/RynthCore.Engine/Compatibility/AutoIdPolicy.cs create mode 100644 src/RynthCore.Engine/Net/IdRequester.cs create mode 100644 tools/EngineRobustnessTests/AutoIdLimitTests.cs diff --git a/src/RynthCore.Engine/Compatibility/AcMainThreadQueue.cs b/src/RynthCore.Engine/Compatibility/AcMainThreadQueue.cs index 814ae0b..c106c57 100644 --- a/src/RynthCore.Engine/Compatibility/AcMainThreadQueue.cs +++ b/src/RynthCore.Engine/Compatibility/AcMainThreadQueue.cs @@ -850,7 +850,9 @@ internal static class AcMainThreadQueue // Pump/Timer-thread enqueue. Drops (returns false) if the queue is full. A request for an // object already waiting returns true without queueing a second send. - public static bool EnqueueRequestId(uint objectId) + // rides with the entry so the drain can mark the real send as the + // engine's (Net/IdRequester.cs); a merge keeps the first requester. + public static bool EnqueueRequestId(uint objectId, Net.IdRequester who = Net.IdRequester.None) { if (objectId == 0) return false; // Dead / portaling / settling: an appraisal queued now is dropped when the window @@ -862,7 +864,7 @@ internal static class AcMainThreadQueue lock (_requestIdLock) { PendingIdQueue.Result r = _requestIdQueue.Enqueue(objectId, NowMs, Volatile.Read(ref _loginEpoch), - RequestIdMergeMaxAgeMs, mergeOnlyAfter); + RequestIdMergeMaxAgeMs, mergeOnlyAfter, (byte)who); if (r == PendingIdQueue.Result.Full) { Interlocked.Increment(ref _dropped); @@ -903,7 +905,12 @@ internal static class AcMainThreadQueue continue; } bool sent = false; - try { sent = CombatActionHooks.RequestId(item.Id); } catch { } + try + { + using (Net.EngineSendMarker.Enter((Net.IdRequester)item.Source)) + sent = CombatActionHooks.RequestId(item.Id); + } + catch { } // AutoId's re-appraisal window starts at the real send, not at the queueing: // a request dropped here (stale, transition) leaves the object due again. if (sent) diff --git a/src/RynthCore.Engine/Compatibility/AutoIdPolicy.cs b/src/RynthCore.Engine/Compatibility/AutoIdPolicy.cs new file mode 100644 index 0000000..3b7b3f7 --- /dev/null +++ b/src/RynthCore.Engine/Compatibility/AutoIdPolicy.cs @@ -0,0 +1,176 @@ +// ============================================================================ +// RynthCore.Engine - Compatibility/AutoIdPolicy.cs +// +// Which background appraisals AutoIdService sends (the decision only; AutoIdService +// does the queueing, the lookups and the sends). +// +// Why: in one 26-minute session (1585 s) the client sent 3211 IdentifyObject (0xC8), +// about three quarters of everything it sent, for 2479 objects against 28 +// kills. AutoId appraised every object the client created. The bot (RynthAi) already +// appraises what it needs at the point of use (corpse items its loot rules need, the +// selected creature, equipment, meta conditions), so most of that was traffic for +// nothing; it is now limited (engine.json "AutoIdMode", /rc autoid). +// +// Modes: +// All the old behaviour: every created object except the player, the selected +// target with its fresh-cache skip. +// Limited (default) only +// Target the selected target (fresh-cache skip, no age, no defer); +// Container items in the container the player has open now (a corpse, +// a chest, a pack opened through ViewContents); +// Inventory items in the player's own inventory (worn, in the main pack +// or in a side pack) that have no cached appraisal. +// Container and Inventory wait until the object is MinAgeMs old, and until +// DeferMs after a world transition's settle window ends (death, portal, +// teleport, landblock jump; walking into the next landblock is not one). +// A container the player opened after that settle window ended is not +// deferred. Creatures, ground items, other players: never. +// Off nothing, the selected target included. +// Plugins calling the host RequestId are not limited by any of this. +// +// Pure: no engine state, no locking. Compiled into tools\EngineRobustnessTests and +// tools\EngineSettingsTests. +// ============================================================================ + +using System; + +namespace RynthCore.Engine.Compatibility; + +/// engine.json "AutoIdMode" (see ). +internal enum AutoIdMode { All = 0, Limited = 1, Off = 2 } + +internal static class AutoIdPolicy +{ + public const AutoIdMode DefaultMode = AutoIdMode.Limited; + + /// Container and Inventory appraisals wait until the object is this old. + public const long MinAgeMs = 2_000; + + /// Container and Inventory appraisals wait this long after a transition's settle window ends. + public const long DeferMs = 30_000; + + public enum Class + { + /// The selected target (the priority path). + Target, + /// In the container the player has open now. + Container, + /// In the player's own inventory (worn, main pack, side pack). + Inventory, + /// Anything else the client knows where it is: a creature, a ground item, another player. + World, + /// Not in the engine's object snapshot yet (created moments ago), so its place is unknown. + Unknown, + } + + public enum Verdict + { + /// Appraise it now. + Send, + /// The mode does not appraise this: drop it. + SkipMode, + /// Too young: keep it and ask again later. + WaitAge, + /// Inside the post-transition defer: keep it and ask again later. + WaitDefer, + /// Its appraisal is cached (fresh): drop it. + SkipFresh, + } + + /// + /// The decision for one candidate. + /// : how long the object has existed (or since it moved, for a move). + /// : inside the post-transition defer window (). + /// : Container only, the player opened it after the last + /// settle window ended (), which exempts it from the defer. + /// : its appraisal is cached and recent (Target, Container). + /// : its appraisal is cached at all (Inventory). + /// + public static Verdict Decide(AutoIdMode mode, Class cls, long ageMs, bool inDefer, bool openedAfterSettle, + bool fresh, bool cached) + { + switch (mode) + { + case AutoIdMode.Off: + return Verdict.SkipMode; + + case AutoIdMode.All: + // The old behaviour: the create-time eligibility already decided; only the + // selected target has the fresh-cache skip. + if (cls == Class.Target && fresh) return Verdict.SkipFresh; + return Verdict.Send; + + default: // Limited + switch (cls) + { + case Class.Target: + return fresh ? Verdict.SkipFresh : Verdict.Send; + case Class.Container: + if (fresh) return Verdict.SkipFresh; + if (ageMs < MinAgeMs) return Verdict.WaitAge; + if (inDefer && !openedAfterSettle) return Verdict.WaitDefer; + return Verdict.Send; + case Class.Inventory: + if (cached) return Verdict.SkipFresh; + if (ageMs < MinAgeMs) return Verdict.WaitAge; + if (inDefer) return Verdict.WaitDefer; + return Verdict.Send; + 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; + default: // World + return Verdict.SkipMode; + } + } + } + + /// + /// Inside the post-transition defer: in a transition now, or less than + /// after the last settle window ended. is + /// WorldTransitionState.SettleUntilMs (0 = no transition yet); it only moves on a death, + /// a portal, a teleport or a landblock jump, never on a walk into the next landblock. + /// + public static bool InDefer(long nowMs, long settleUntilMs, bool inTransition) => + inTransition || (settleUntilMs > 0 && nowMs < settleUntilMs + DeferMs); + + /// The player opened the container (at ) after the last settle window ended. + public static bool OpenedAfterSettle(long openedAtMs, long settleUntilMs) => + openedAtMs > 0 && openedAtMs >= settleUntilMs; + + /// + /// Where an object is, from its PublicWeenieDesc ownership fields ( = + /// the snapshot had it). is the container's own container + /// (a side pack's owner), 0 when unknown or none. is the + /// container the player has open now (0 = none). + /// + public static Class Classify(bool known, uint playerId, uint openContainer, + uint container, uint wielder, uint containerParent) + { + if (!known) return Class.Unknown; + if (playerId != 0 && (container == playerId || wielder == playerId || (container != 0 && containerParent == playerId))) + return Class.Inventory; + // openContainer != 0 also keeps a ground item (container 0) out of here. + if (openContainer != 0 && (container == openContainer || containerParent == openContainer)) + return Class.Container; + return Class.World; + } + + public static bool TryParseMode(string? text, out AutoIdMode mode) + { + switch ((text ?? "").Trim().ToLowerInvariant()) + { + case "all": mode = AutoIdMode.All; return true; + case "limited": case "limit": mode = AutoIdMode.Limited; return true; + case "off": case "none": mode = AutoIdMode.Off; return true; + default: mode = DefaultMode; return false; + } + } + + public static string Name(AutoIdMode mode) => mode switch + { + AutoIdMode.All => "all", + AutoIdMode.Off => "off", + _ => "limited", + }; +} diff --git a/src/RynthCore.Engine/Compatibility/AutoIdService.cs b/src/RynthCore.Engine/Compatibility/AutoIdService.cs index 5770cb4..2bc24b5 100644 --- a/src/RynthCore.Engine/Compatibility/AutoIdService.cs +++ b/src/RynthCore.Engine/Compatibility/AutoIdService.cs @@ -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 _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 = new(256); + private static readonly HashSet _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; /// Re-creates not appraised because a recent appraisal is still cached. public static long SkippedRecentCount @@ -55,13 +98,26 @@ internal static class AutoIdService /// Selected-target priority appraisals skipped because the target's data is cached and fresh. public static long SkippedPriorityFreshCount => Interlocked.Read(ref _skippedPriorityFresh); + /// The live mode (engine.json "AutoIdMode", /rc autoid). + public static AutoIdMode Mode => (AutoIdMode)_mode; + + /// Switch the mode now; also saves it to engine.json. + 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)})."); } /// @@ -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)); + } + + /// + /// The server put into + /// (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. + /// + 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)); + } + + /// + /// The client opened '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. + /// + 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); } /// @@ -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 }); + } + + /// Limited mode: the items already in a container the player opened become candidates. + 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 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; + } + + /// Where the object is now, from the engine's object snapshot (no AC access off its main thread). + 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; + + /// + /// 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 #". + /// + 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(); + } + + /// /rc autoid [all|limited|off|status] + 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)}" : "") + ".", + }; } } diff --git a/src/RynthCore.Engine/Compatibility/ClientHelperHooks.cs b/src/RynthCore.Engine/Compatibility/ClientHelperHooks.cs index 2d5bc81..e57b4a2 100644 --- a/src/RynthCore.Engine/Compatibility/ClientHelperHooks.cs +++ b/src/RynthCore.Engine/Compatibility/ClientHelperHooks.cs @@ -964,6 +964,7 @@ internal static class ClientHelperHooks return; Interlocked.Exchange(ref _currentGroundContainerId, unchecked((int)objectId)); + AutoIdService.OnContainerOpened(objectId); } public static void NotifyStopViewingObjectContents(uint objectId) diff --git a/src/RynthCore.Engine/Compatibility/CombatActionHooks.cs b/src/RynthCore.Engine/Compatibility/CombatActionHooks.cs index 4ec9061..37d1dc1 100644 --- a/src/RynthCore.Engine/Compatibility/CombatActionHooks.cs +++ b/src/RynthCore.Engine/Compatibility/CombatActionHooks.cs @@ -461,12 +461,21 @@ internal static class CombatActionHooks // here on the main thread, where this gate passes and the packet is sent. // Fire-and-forget: the appraisal reply is async anyway, so "queued" keeps // the bool's meaning ("requested"). + // The caller's EngineSendMarker (Net/IdRequester.cs) says who asked: it rides with a + // queued request, and a send made under it is registered with the flight recorder so + // the 0xC8 shows as [eng:]. Without a marker the send stays [cli]. + Net.IdRequester who = Net.EngineSendMarker.Current; if (AcMainThreadQueue.MustQueue(teardown: false)) - return AcMainThreadQueue.EnqueueRequestId(objectId); + return AcMainThreadQueue.EnqueueRequestId(objectId, who); try { - return _requestId(objectId); + if (who != Net.IdRequester.None) + Net.FlightRecorder.EngineSend((byte)who, objectId); + bool sent = _requestId(objectId); + if (sent) + Net.IdSendStats.CountSent(who); + return sent; } catch { diff --git a/src/RynthCore.Engine/Compatibility/HeartbeatLogger.cs b/src/RynthCore.Engine/Compatibility/HeartbeatLogger.cs index eaf9660..4a5abca 100644 --- a/src/RynthCore.Engine/Compatibility/HeartbeatLogger.cs +++ b/src/RynthCore.Engine/Compatibility/HeartbeatLogger.cs @@ -201,6 +201,13 @@ internal static class HeartbeatLogger if (tick % 60 == 0) LogGcStats(); + // Every 60 s: IdentifyObject (0xC8) sends by who asked, and AutoId's skips + // (AutoIdService.TakeMinuteLine). Its own line, never part of "hb #". + if (tick % 60 == 0) + { + try { RynthLog.Info(AutoIdService.TakeMinuteLine()); } catch { } + } + // Every 5 s: hide and destroy any panel window no live panel owns // (the "double UI" orphans). if (tick % 5 == 0) diff --git a/src/RynthCore.Engine/Compatibility/InventoryModel.cs b/src/RynthCore.Engine/Compatibility/InventoryModel.cs index 0fcf53a..cf24e58 100644 --- a/src/RynthCore.Engine/Compatibility/InventoryModel.cs +++ b/src/RynthCore.Engine/Compatibility/InventoryModel.cs @@ -1118,7 +1118,8 @@ internal static class InventoryModel _identified[id] = now; _lastIdentify = now; sentRecently = true; - ClientActionHooks.RequestId(id); // main thread: the 0xC8 is sent now + using (Net.EngineSendMarker.Enter(Net.IdRequester.Ui)) + ClientActionHooks.RequestId(id); // main thread: the 0xC8 is sent now tip = null; // rebuild below with "identifying" } diff --git a/src/RynthCore.Engine/Compatibility/PendingIdQueue.cs b/src/RynthCore.Engine/Compatibility/PendingIdQueue.cs index 63727b6..1aa0ed8 100644 --- a/src/RynthCore.Engine/Compatibility/PendingIdQueue.cs +++ b/src/RynthCore.Engine/Compatibility/PendingIdQueue.cs @@ -37,12 +37,15 @@ internal sealed class PendingIdQueue public readonly uint Id; public readonly long At; public readonly int Epoch; + /// Who asked (Net.IdRequester as a byte): the first request's, a merge keeps it. + public readonly byte Source; - public Item(uint id, long at, int epoch) + public Item(uint id, long at, int epoch, byte source = 0) { Id = id; At = at; Epoch = epoch; + Source = source; } } @@ -70,7 +73,7 @@ internal sealed class PendingIdQueue /// drains: an entry from before then is dropped when the drain reaches it, and a request /// merged into it would be lost with it). /// - public Result Enqueue(uint id, long nowMs, int epoch, long mergeMaxAgeMs, long mergeOnlyAfterMs = 0) + public Result Enqueue(uint id, long nowMs, int epoch, long mergeMaxAgeMs, long mergeOnlyAfterMs = 0, byte source = 0) { for (int i = 0; i < _count; i++) { @@ -84,7 +87,7 @@ internal sealed class PendingIdQueue } if (_count >= _ring.Length) return Result.Full; - _ring[(_head + _count) % _ring.Length] = new Item(id, nowMs, epoch); + _ring[(_head + _count) % _ring.Length] = new Item(id, nowMs, epoch, source); _count++; return Result.Queued; } diff --git a/src/RynthCore.Engine/Compatibility/PlayerLifecycleLog.cs b/src/RynthCore.Engine/Compatibility/PlayerLifecycleLog.cs index f997a5b..0c3d843 100644 --- a/src/RynthCore.Engine/Compatibility/PlayerLifecycleLog.cs +++ b/src/RynthCore.Engine/Compatibility/PlayerLifecycleLog.cs @@ -41,6 +41,13 @@ internal static class PlayerLifecycleLog public static bool InWorldTransition => _dead || _portaling || Environment.TickCount64 < Interlocked.Read(ref _settleUntil); + /// + /// When the last settle window ends (TickCount64; 0 = no transition yet), as of the last + /// game tick; any thread. Moves only on a death, a portal, a teleport or a landblock jump, + /// never on a walk into the next landblock (AutoIdPolicy's post-transition defer). + /// + public static long SettleUntilMs => Interlocked.Read(ref _settleUntil); + /// /// AC main thread only (the queue drains): true = hold everything queued now (see /// WorldTransitionState for the rule). diff --git a/src/RynthCore.Engine/Compatibility/RynthCoreChatCommands.cs b/src/RynthCore.Engine/Compatibility/RynthCoreChatCommands.cs index 7e517d4..4d50734 100644 --- a/src/RynthCore.Engine/Compatibility/RynthCoreChatCommands.cs +++ b/src/RynthCore.Engine/Compatibility/RynthCoreChatCommands.cs @@ -81,6 +81,9 @@ namespace RynthCore.Engine.Compatibility; /// /rc report [text] - "Report a problem" (): alone it /// opens the panel; with text it sends that report now, with the recent log attached /// (the panel is where the log can be left out). One report a minute. +/// /rc autoid [all|limited|off] - which background appraisals the engine's AutoId +/// sends (, ; saved in engine.json); +/// alone it reports the mode and the identify counts by who asked. /// /// internal static class RynthCoreChatCommands @@ -288,6 +291,18 @@ internal static class RynthCoreChatCommands return true; } + // /rc autoid [all|limited|off] : which background appraisals AutoId sends (alone: status) + if (IsVerb(sub, "autoid", out string autoIdArgs)) + { + try + { + foreach (string l in AutoIdService.HandleCommand(autoIdArgs)) + Reply(l); + } + catch (Exception ex) { RynthLog.Compat($"RynthCoreChatCommands: /rc autoid failed - {ex.GetType().Name}: {ex.Message}"); } + return true; + } + // /rc netmsg [status|on|off|log on|off|capture on|off] : the v78 server message stream if (IsVerb(sub, "netmsg", out string netArgs)) { diff --git a/src/RynthCore.Engine/Net/FlightCapture.cs b/src/RynthCore.Engine/Net/FlightCapture.cs index c633947..7a566e8 100644 --- a/src/RynthCore.Engine/Net/FlightCapture.cs +++ b/src/RynthCore.Engine/Net/FlightCapture.cs @@ -348,8 +348,14 @@ internal sealed unsafe class FlightCapture NoteTarget(arg1, now); } - f |= MatchEngineCall(action, arg0, arg1, now) ? FlightFlags.Engine : FlightFlags.Client; - Keep(_out, now, FlightDir.Out, f, msg, len, fullLen, seq, 0); + // An IdentifyObject is the engine's when an engine send for that object was + // registered just before (EngineSend, with who asked); otherwise AC or Decal sent it. + byte idWho = action == FlightOp.AcIdentifyObject ? MatchEngineSend(arg0, now) : (byte)0; + bool engine = idWho != 0 || MatchEngineCall(action, arg0, arg1, now); + if (action == FlightOp.AcIdentifyObject && !engine) + Interlocked.Increment(ref _identifyForeign); + f |= engine ? FlightFlags.Engine : FlightFlags.Client; + Keep(_out, now, FlightDir.Out, f, msg, len, fullLen, seq, 0, idWho); if (action == FlightOp.AcUse || action == FlightOp.AcUseWithTarget) DetectUseSent(action == FlightOp.AcUse ? arg0 : arg1, counted: action == FlightOp.AcUse, now); @@ -431,10 +437,10 @@ internal sealed unsafe class FlightCapture } } - private void Keep(Side side, long now, FlightDir dir, FlightFlags f, byte* msg, int len, int fullLen, uint seq, uint suppressed) + private void Keep(Side side, long now, FlightDir dir, FlightFlags f, byte* msg, int len, int fullLen, uint seq, uint suppressed, uint requester = 0) { side.Kept++; - Ring.WriteMessage(now, dir, f, msg, len, fullLen, seq, suppressed); + Ring.WriteMessage(now, dir, f, msg, len, fullLen, seq, suppressed, requester); } // ── positions ────────────────────────────────────────────────────────── @@ -589,6 +595,53 @@ 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:]) says who asked. + private struct IdPending { public uint Id; public byte Who; public long Stamp; public bool Used; } + private readonly IdPending[] _idPending = new IdPending[64]; + private int _idPendingNext; + private long _identifyForeign; + + /// IdentifyObject (0xC8) messages sent with no engine send to match: AC itself or Decal. + public long IdentifyForeignTotal => Interlocked.Read(ref _identifyForeign); + + /// + /// The engine is about to send an IdentifyObject for on behalf of + /// (an IdRequester, non-zero). The next 0xC8 for that id within + /// EngineMatchMs is tagged [eng:<who>]. + /// + public void EngineSend(byte who, uint id) + { + if (who == 0) return; + long now = _clock(); + lock (_engineLock) + { + ref IdPending p = ref _idPending[_idPendingNext]; + _idPendingNext = (_idPendingNext + 1) & (_idPending.Length - 1); + p.Id = id; p.Who = who; p.Stamp = now; p.Used = false; + } + } + + /// The requester of the oldest unmatched engine send for , or 0. + private byte MatchEngineSend(uint id, long now) + { + lock (_engineLock) + { + int best = -1; + for (int i = 0; i < _idPending.Length; i++) + { + ref IdPending p = ref _idPending[i]; + if (p.Who == 0 || p.Used || p.Id != id || now < p.Stamp || Ms(now - p.Stamp) > EngineMatchMs) continue; + if (best < 0 || p.Stamp < _idPending[best].Stamp) best = i; + } + if (best < 0) return 0; + _idPending[best].Used = true; + return _idPending[best].Who; + } + } + /// Engine calls that send something to the server. private static bool Expects(string name) => name switch { diff --git a/src/RynthCore.Engine/Net/FlightFormat.cs b/src/RynthCore.Engine/Net/FlightFormat.cs index 0968e2f..29751cc 100644 --- a/src/RynthCore.Engine/Net/FlightFormat.cs +++ b/src/RynthCore.Engine/Net/FlightFormat.cs @@ -344,7 +344,9 @@ internal static class FlightFormat uint seq = rd.U32(); uint action = rd.U32(); - string tag = (e.Flags & FlightFlags.Engine) != 0 ? "[eng] " : (e.Flags & FlightFlags.Client) != 0 ? "[cli] " : ""; + string who = IdRequesters.Label(e.C); + string tag = (e.Flags & FlightFlags.Engine) != 0 ? (who.Length > 0 ? $"[eng:{who}] " : "[eng] ") + : (e.Flags & FlightFlags.Client) != 0 ? "[cli] " : ""; string body = action switch { FlightOp.AcUse => $"{Id(rd.U32())}", @@ -794,6 +796,8 @@ internal static class FlightFormat " -> client to server (what this client sent). [eng] = matches an engine direct-action call just before", " (the 'engine ...' marker above it); [cli] = no engine call to match: the client's own path", " (keyboard/mouse, or a plugin calling AC some other way). Movement matches are by time only.", + " IdentifyObject: [eng:autoid-target|autoid-container|autoid-inventory|autoid-world|plugin|self|ui]", + " = an engine appraisal and who asked for it; [cli] = AC itself or Decal.", " <- server to client: game events (UseDone, ViewContents, errors, magic, combat), the player's own", " motion/position/teleport, system text, and messages about objects the character just used.", " ** engine markers: engine calls, m_cBusy changes and resets, action-gate clears, a per-second link", diff --git a/src/RynthCore.Engine/Net/FlightRecorder.cs b/src/RynthCore.Engine/Net/FlightRecorder.cs index 6fa5963..c2cb398 100644 --- a/src/RynthCore.Engine/Net/FlightRecorder.cs +++ b/src/RynthCore.Engine/Net/FlightRecorder.cs @@ -125,6 +125,25 @@ internal static unsafe class FlightRecorder try { c.EngineCall(name, a, b); } catch { } } + /// An engine IdentifyObject send for , asked for by + /// (IdRequester): the 0xC8 it produces is tagged [eng:<who>]. + public static void EngineSend(byte who, uint id) + { + FlightCapture? c = _cap; + if (c == null || _paused) return; + try { c.EngineSend(who, id); } catch { } + } + + /// IdentifyObject messages sent with no engine send to match (AC or Decal); -1 while the recorder is off. + public static long ForeignIdentifyTotal + { + get + { + FlightCapture? c = _cap; + return c == null ? -1 : c.IdentifyForeignTotal; + } + } + public static void Mark(FlightMark kind, uint a = 0, uint b = 0, uint c = 0, string? text = null) { FlightCapture? cap = _cap; diff --git a/src/RynthCore.Engine/Net/FlightRing.cs b/src/RynthCore.Engine/Net/FlightRing.cs index e607f59..79300a7 100644 --- a/src/RynthCore.Engine/Net/FlightRing.cs +++ b/src/RynthCore.Engine/Net/FlightRing.cs @@ -93,7 +93,7 @@ internal unsafe struct FlightEntry public uint A; /// Messages: rate-limited copies dropped before this one. Markers: second number. public uint B; - /// Messages: unused. Markers: third number. + /// Messages: an engine 0xC8's requester (IdRequester), else 0. Markers: third number. public uint C; public fixed byte Data[DataCap]; } @@ -153,7 +153,8 @@ internal sealed unsafe class FlightRing } /// A message: its first DataCap bytes. - public void WriteMessage(long stamp, FlightDir dir, FlightFlags flags, byte* msg, int len, int fullLen, uint fragSeq, uint suppressed) + /// Messages' C: for an engine 0xC8, who asked (IdRequester); else 0. + public void WriteMessage(long stamp, FlightDir dir, FlightFlags flags, byte* msg, int len, int fullLen, uint fragSeq, uint suppressed, uint requester = 0) { if (!Own(out int i, out int serial)) return; ref FlightEntry e = ref _slots[i]; @@ -167,7 +168,7 @@ internal sealed unsafe class FlightRing e.FullLen = (ushort)Math.Clamp(fullLen, 0, ushort.MaxValue); e.A = fragSeq; e.B = suppressed; - e.C = 0; + e.C = requester; fixed (byte* d = e.Data) { if (keep > 0) Buffer.MemoryCopy(msg, d, FlightEntry.DataCap, keep); diff --git a/src/RynthCore.Engine/Net/IdRequester.cs b/src/RynthCore.Engine/Net/IdRequester.cs new file mode 100644 index 0000000..2474a10 --- /dev/null +++ b/src/RynthCore.Engine/Net/IdRequester.cs @@ -0,0 +1,116 @@ +// ============================================================================ +// RynthCore.Engine - Net/IdRequester.cs +// +// Who asked for an IdentifyObject (0xC8) the engine sends, so the flight recorder and +// the per-minute counters can tell the engine's appraisals apart from AC's and Decal's. +// +// Before: the recorder tagged every 0xC8 [cli] (FlightCapture had no case for it), so +// 3211 identifies in one session's dump could not be split between AutoId, the plugins +// and the client itself. +// +// The marker is call-scoped and thread-local: whoever calls CombatActionHooks.RequestId +// wraps the call in EngineSendMarker.Enter(who). When the call is queued for AC's main +// thread, the requester rides with the queued entry (PendingIdQueue) and the drain +// re-enters the marker around the real send. Only a send made under a marker is +// registered with the recorder (FlightCapture.EngineSend), so a 0xC8 nobody marked stays +// [cli]: AC itself or Decal. +// +// Pure: no engine state. Compiled into tools\EngineRobustnessTests and +// tools\FlightRecorderTests. +// ============================================================================ + +using System; +using System.Threading; + +namespace RynthCore.Engine.Net; + +/// Who asked for an engine 0xC8. The byte value is what the flight ring stores. +internal enum IdRequester : byte +{ + /// No marker: not an engine send (AC itself, Decal), or an unmarked engine path. + None = 0, + AutoIdTarget = 1, + AutoIdContainer = 2, + AutoIdInventory = 3, + /// AutoIdMode All only: an object that is not the target, in an open container or in the pack. + AutoIdWorld = 4, + /// A plugin through the host RequestId (plugin API). + Plugin = 5, + /// The engine's delayed login self-identify (max vitals). + Self = 6, + /// The engine's Inventory panel identifying the item under the cursor. + Ui = 7, +} + +internal static class IdRequesters +{ + public const int Count = 8; + + /// The flight-recorder label after "eng:" ("" for None or an unknown code). + public static string Label(uint code) => code switch + { + 1 => "autoid-target", + 2 => "autoid-container", + 3 => "autoid-inventory", + 4 => "autoid-world", + 5 => "plugin", + 6 => "self", + 7 => "ui", + _ => "", + }; + + /// Short heartbeat field names (none contains fps=, plug=, login= or qd=). + public static string Short(IdRequester who) => who switch + { + IdRequester.AutoIdTarget => "tgt", + IdRequester.AutoIdContainer => "ctr", + IdRequester.AutoIdInventory => "inv", + IdRequester.AutoIdWorld => "wld", + IdRequester.Plugin => "plg", + IdRequester.Self => "slf", + IdRequester.Ui => "ui", + _ => "unm", + }; +} + +/// The thread-local "this 0xC8 is the engine's" marker around a RequestId call. +internal static class EngineSendMarker +{ + [ThreadStatic] private static IdRequester t_current; + + /// The requester marked on this thread (None outside any scope). + public static IdRequester Current => t_current; + + /// Marks this thread until the returned scope is disposed (scopes nest). + public static Scope Enter(IdRequester who) + { + IdRequester previous = t_current; + t_current = who; + return new Scope(previous); + } + + public readonly struct Scope : IDisposable + { + private readonly IdRequester _previous; + internal Scope(IdRequester previous) { _previous = previous; } + public void Dispose() => t_current = _previous; + } +} + +/// Engine 0xC8 sends that really went out, per requester (running totals; any thread). +internal static class IdSendStats +{ + private static readonly long[] _sent = new long[IdRequesters.Count]; + + public static void CountSent(IdRequester who) + { + int i = (int)who; + if ((uint)i < (uint)_sent.Length) Interlocked.Increment(ref _sent[i]); + } + + public static long Sent(IdRequester who) + { + int i = (int)who; + return (uint)i < (uint)_sent.Length ? Interlocked.Read(ref _sent[i]) : 0; + } +} diff --git a/src/RynthCore.Engine/Net/ServerMessageStream.cs b/src/RynthCore.Engine/Net/ServerMessageStream.cs index a40bc4c..d02e335 100644 --- a/src/RynthCore.Engine/Net/ServerMessageStream.cs +++ b/src/RynthCore.Engine/Net/ServerMessageStream.cs @@ -226,6 +226,14 @@ 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); diff --git a/src/RynthCore.Engine/Plugins/EngineSettings.cs b/src/RynthCore.Engine/Plugins/EngineSettings.cs index 992d743..7ec8369 100644 --- a/src/RynthCore.Engine/Plugins/EngineSettings.cs +++ b/src/RynthCore.Engine/Plugins/EngineSettings.cs @@ -48,6 +48,7 @@ internal static class EngineSettings // "ReportEndpoint": where "Report a problem" posts (Report/ProblemReport.cs); null = the built-in URL. // For testing only (https, or http to this PC); read only, like MaxHotReloads. private static string? _reportEndpoint; + private static Compatibility.AutoIdMode _autoIdMode = Compatibility.AutoIdPolicy.DefaultMode; private static bool _loaded; public static IReadOnlyList PluginPaths @@ -418,6 +419,25 @@ internal static class EngineSettings } } + /// "AutoIdMode" in engine.json: "All", "Limited" (default) or "Off". + /// Which background appraisals the engine's AutoId sends (Compatibility/AutoIdPolicy.cs); + /// plugins' own RequestId calls are never limited by it. Set live with /rc autoid. + public static Compatibility.AutoIdMode AutoIdMode + { + get + { + EnsureLoaded(); + return _autoIdMode; + } + set + { + EnsureLoaded(); // populate _pluginPaths before Save() rewrites the file + if (_autoIdMode == value) return; + _autoIdMode = value; + Save(); + } + } + public static void AddPluginPath(string path) { EnsureLoaded(); @@ -568,6 +588,11 @@ internal static class EngineSettings repEl.GetString() is { Length: > 0 } rep) _reportEndpoint = rep.Trim(); + if (doc.RootElement.TryGetProperty("AutoIdMode", out var aimEl) && + aimEl.ValueKind == JsonValueKind.String && + Compatibility.AutoIdPolicy.TryParseMode(aimEl.GetString(), out Compatibility.AutoIdMode aim)) + _autoIdMode = aim; + if (doc.RootElement.TryGetProperty("PreventIdleLogoff", out var pilEl) && (pilEl.ValueKind == JsonValueKind.True || pilEl.ValueKind == JsonValueKind.False)) { @@ -627,7 +652,7 @@ internal static class EngineSettings "EnableImGuiBackend", "EnableHangMinidump", "PreventIdleLogoff", "DecalBridge", "DecalInGameImGui", "DecalStandDown", "DisabledUiHooks", "ServerMessageStream", "FlightRecorder", "InsertReleasesUi", "IltServerNames", "IltHosts", "EnableLargeAddressAlignmentFix", - "MaxHotReloads", "ReportEndpoint", "CloseOnServerDisconnect", + "MaxHotReloads", "ReportEndpoint", "CloseOnServerDisconnect", "AutoIdMode", }; private static void Save() @@ -684,6 +709,8 @@ internal static class EngineSettings w.WriteString("ReportEndpoint", _reportEndpoint); WriteStringList(w, "IltServerNames", _iltServerNames); // null (not in the file): left out WriteStringList(w, "IltHosts", _iltHosts); + if (_autoIdMode != Compatibility.AutoIdPolicy.DefaultMode) // default: leave the file as it was + w.WriteString("AutoIdMode", _autoIdMode.ToString()); w.WriteEndObject(); } diff --git a/src/RynthCore.Engine/Plugins/PluginManager.cs b/src/RynthCore.Engine/Plugins/PluginManager.cs index 625650b..76b056d 100644 --- a/src/RynthCore.Engine/Plugins/PluginManager.cs +++ b/src/RynthCore.Engine/Plugins/PluginManager.cs @@ -1050,7 +1050,8 @@ internal static partial class PluginManager uint pid = ClientHelperHooks.GetPlayerId(); if (pid != 0 && CombatActionHooks.HasRequestId) { - CombatActionHooks.RequestId(pid); + using (Net.EngineSendMarker.Enter(Net.IdRequester.Self)) + CombatActionHooks.RequestId(pid); RynthLog.Plugin($"PluginManager: sent (delayed) self-identify for player 0x{pid:X8} to seed max vitals."); } } @@ -3081,7 +3082,9 @@ internal static partial class PluginManager private static int RequestIdAction(uint objectId) { - return ToAbiBool(ClientActionHooks.RequestId(objectId)); + // A plugin's identify: never limited by AutoIdMode; its 0xC8 is tagged [eng:plugin]. + using (Net.EngineSendMarker.Enter(Net.IdRequester.Plugin)) + return ToAbiBool(ClientActionHooks.RequestId(objectId)); } private static int CastSpellAction(uint targetId, int spellId) diff --git a/tools/EngineRobustnessTests/AutoIdLimitTests.cs b/tools/EngineRobustnessTests/AutoIdLimitTests.cs new file mode 100644 index 0000000..871ff04 --- /dev/null +++ b/tools/EngineRobustnessTests/AutoIdLimitTests.cs @@ -0,0 +1,254 @@ +using RynthCore.Engine.Compatibility; +using RynthCore.Engine.Net; +using V = RynthCore.Engine.Compatibility.AutoIdPolicy.Verdict; +using C = RynthCore.Engine.Compatibility.AutoIdPolicy.Class; + +namespace EngineRobustnessTests; + +/// +/// AutoId limiting: the mode decision table, the post-transition defer, where an +/// object is, and the engine-send marker that tags every engine 0xC8. +/// +internal static partial class Program +{ + private static void RunAutoIdLimitTests() + { + AutoIdDecisionTable(); + AutoIdDecisionSpotCases(); + AutoIdDeferWindow(); + AutoIdClassify(); + AutoIdModeParse(); + IdMarkerScopes(); + IdMarkerRidesTheQueue(); + IdHeartbeatNames(); + } + + // ---- the decision table --------------------------------------------------------- + + private static readonly long[] Ages = { 0, AutoIdPolicy.MinAgeMs - 1, AutoIdPolicy.MinAgeMs, 60_000 }; + + /// The rule as the spec states it, written out independently of AutoIdPolicy.Decide. + private static V Expected(AutoIdMode mode, C cls, long age, bool defer, bool openedAfter, bool fresh, bool cached) + { + if (mode == AutoIdMode.Off) return V.SkipMode; + if (mode == AutoIdMode.All) return cls == C.Target && fresh ? V.SkipFresh : V.Send; + bool young = age < AutoIdPolicy.MinAgeMs; + return cls switch + { + 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 : V.Send, + C.Unknown => young ? V.WaitAge : V.SkipMode, + _ => V.SkipMode, + }; + } + + private static void AutoIdDecisionTable() + { + _case = "autoid decision table"; + int rows = 0, wrong = 0; + foreach (AutoIdMode mode in Enum.GetValues()) + foreach (C cls in Enum.GetValues()) + foreach (long age in Ages) + foreach (bool defer in new[] { false, true }) + foreach (bool opened in new[] { false, true }) + foreach (bool cached in new[] { false, true }) + foreach (bool fresh in new[] { false, true }) + { + if (fresh && !cached) continue; // fresh implies cached + rows++; + V got = AutoIdPolicy.Decide(mode, cls, age, defer, opened, fresh, cached); + V want = Expected(mode, cls, age, defer, opened, fresh, cached); + if (got != want && wrong++ < 10) + Check(false, $"{mode} {cls} age={age} defer={defer} opened={opened} cached={cached} fresh={fresh}: want {want}, got {got}"); + } + Check(wrong == 0, $"{wrong} of {rows} rows wrong"); + Check(rows == 3 * 5 * 4 * 2 * 2 * 3, $"row count {rows}"); + } + + /// The same rules as named cases, so a mutation is easy to read off a failure. + private static void AutoIdDecisionSpotCases() + { + _case = "autoid spot cases"; + const long Old = 10_000; + // Off: nothing at all, the selected target included. + Check(AutoIdPolicy.Decide(AutoIdMode.Off, C.Target, 0, false, false, false, false) == V.SkipMode, "off skips the target"); + Check(AutoIdPolicy.Decide(AutoIdMode.Off, C.Container, Old, false, true, false, false) == V.SkipMode, "off skips an open container"); + // All: the old behaviour. + Check(AutoIdPolicy.Decide(AutoIdMode.All, C.World, 0, true, false, false, false) == V.Send, "all sends a fresh-born world object, deferred or not"); + Check(AutoIdPolicy.Decide(AutoIdMode.All, C.Target, 0, false, false, true, true) == V.SkipFresh, "all keeps the target fresh skip"); + Check(AutoIdPolicy.Decide(AutoIdMode.All, C.Inventory, 0, false, false, false, true) == V.Send, "all sends a cached pack item (old behaviour)"); + // Limited: target. + Check(AutoIdPolicy.Decide(AutoIdMode.Limited, C.Target, 0, true, false, false, false) == V.Send, "target exempt from age and defer"); + Check(AutoIdPolicy.Decide(AutoIdMode.Limited, C.Target, 0, false, false, true, true) == V.SkipFresh, "target fresh skip"); + Check(AutoIdPolicy.Decide(AutoIdMode.Limited, C.Target, 0, false, false, false, true) == V.Send, "target cached but stale is sent"); + // Limited: world never. + Check(AutoIdPolicy.Decide(AutoIdMode.Limited, C.World, Old, false, false, false, false) == V.SkipMode, "creature / ground item skipped"); + // Limited: container. + Check(AutoIdPolicy.Decide(AutoIdMode.Limited, C.Container, AutoIdPolicy.MinAgeMs - 1, false, true, false, false) == V.WaitAge, "container item waits for the minimum age"); + Check(AutoIdPolicy.Decide(AutoIdMode.Limited, C.Container, AutoIdPolicy.MinAgeMs, false, false, false, false) == V.Send, "container item at the minimum age is sent"); + Check(AutoIdPolicy.Decide(AutoIdMode.Limited, C.Container, Old, true, false, false, false) == V.WaitDefer, "container opened before the settle ended waits out the defer"); + Check(AutoIdPolicy.Decide(AutoIdMode.Limited, C.Container, Old, true, true, false, false) == V.Send, "container opened after the settle is not deferred"); + Check(AutoIdPolicy.Decide(AutoIdMode.Limited, C.Container, Old, false, false, true, true) == V.SkipFresh, "fresh container item skipped"); + Check(AutoIdPolicy.Decide(AutoIdMode.Limited, C.Container, Old, false, false, false, true) == V.Send, "stale cached container item re-appraised"); + // Limited: inventory. + Check(AutoIdPolicy.Decide(AutoIdMode.Limited, C.Inventory, Old, false, false, false, true) == V.SkipFresh, "pack item with any cached appraisal skipped"); + Check(AutoIdPolicy.Decide(AutoIdMode.Limited, C.Inventory, AutoIdPolicy.MinAgeMs - 1, false, false, false, false) == V.WaitAge, "pack item waits for the minimum age"); + Check(AutoIdPolicy.Decide(AutoIdMode.Limited, C.Inventory, Old, true, true, false, false) == V.WaitDefer, "pack item deferred (the opened-container exemption does not apply)"); + Check(AutoIdPolicy.Decide(AutoIdMode.Limited, C.Inventory, Old, false, false, false, false) == V.Send, "uncached pack item sent"); + // Limited: unknown place. + Check(AutoIdPolicy.Decide(AutoIdMode.Limited, C.Unknown, 100, false, false, false, false) == V.WaitAge, "unknown place waits while young"); + Check(AutoIdPolicy.Decide(AutoIdMode.Limited, C.Unknown, Old, false, false, false, false) == V.SkipMode, "still unknown when old: skipped"); + Check(AutoIdPolicy.DefaultMode == AutoIdMode.Limited, "default mode is Limited"); + } + + // ---- the post-transition defer ----------------------------------------------------- + + private static void AutoIdDeferWindow() + { + _case = "autoid defer window"; + const long D = AutoIdPolicy.DeferMs; + const long S = WorldTransitionState.SettleMs; + + // No transition yet: nothing is deferred. + var w = new WorldTransitionState(); + w.Sample(1000, dead: false, portaling: false, landblock: 0xA9B4); + Check(!AutoIdPolicy.InDefer(1000, w.SettleUntilMs, w.InTransition(1000)), "no transition, no defer"); + + // Walking into the next landblock never defers. + w.Sample(2000, false, false, 0xAAB4); + w.Sample(3000, false, false, 0xAAB5); + Check(w.SettleUntilMs == 0, "an adjacent walk sets no settle window"); + Check(!AutoIdPolicy.InDefer(3000, w.SettleUntilMs, w.InTransition(3000)), "adjacent walk: no defer"); + + // A portal: deferred through portal space, the settle window, and DeferMs after it. + w.Sample(10_000, false, true, 0xAAB5); + Check(AutoIdPolicy.InDefer(10_000, w.SettleUntilMs, w.InTransition(10_000)), "in portal space: deferred"); + w.Sample(12_000, false, false, 0x0007); + long settleEnd = w.SettleUntilMs; + Check(settleEnd == 12_000 + S, $"settle ends {S} ms after the portal exit, got {settleEnd}"); + Check(AutoIdPolicy.InDefer(settleEnd + D - 1, settleEnd, w.InTransition(settleEnd + D - 1)), "deferred until DeferMs after the settle"); + Check(!AutoIdPolicy.InDefer(settleEnd + D, settleEnd, w.InTransition(settleEnd + D)), "not deferred at DeferMs after the settle"); + + // A container opened after the settle ended is exempt; one opened before is not. + Check(AutoIdPolicy.OpenedAfterSettle(settleEnd + 1, settleEnd), "opened after the settle: exempt"); + Check(!AutoIdPolicy.OpenedAfterSettle(settleEnd - 1, settleEnd), "opened during the settle: not exempt"); + Check(!AutoIdPolicy.OpenedAfterSettle(0, settleEnd), "never opened: not exempt"); + + // Death defers too. + var d = new WorldTransitionState(); + d.Sample(1000, false, false, 0x1234); + d.Sample(2000, true, false, 0x1234); + d.Sample(3000, false, false, 0x1234); + Check(AutoIdPolicy.InDefer(3000 + S + D - 1, d.SettleUntilMs, false), "death: deferred"); + Check(!AutoIdPolicy.InDefer(3000 + S + D, d.SettleUntilMs, false), "death: defer ends"); + + // A landblock jump without portal space defers. + var j = new WorldTransitionState(); + j.Sample(1000, false, false, 0x00AE); + j.Sample(1100, false, false, 0xA9B4); + Check(AutoIdPolicy.InDefer(1100 + S + D - 1, j.SettleUntilMs, false), "landblock jump: deferred"); + + // A PlayerTeleport message (a recall into the next landblock) defers. + var t = new WorldTransitionState(); + t.Sample(1000, false, false, 0x1234); + t.OnTeleportMessage(5000); + Check(AutoIdPolicy.InDefer(5000 + S + D - 1, t.SettleUntilMs, false), "teleport message: deferred"); + Check(!AutoIdPolicy.InDefer(5000 + S + D, t.SettleUntilMs, false), "teleport message: defer ends"); + + // In a transition right now: deferred whatever the settle time says. + Check(AutoIdPolicy.InDefer(1, 0, inTransition: true), "in a transition: deferred"); + } + + // ---- where an object is ------------------------------------------------------------ + + private static void AutoIdClassify() + { + _case = "autoid classify"; + const uint Me = 0x50000001, Corpse = 0x80000100, Pack = 0x80000200, Monster = 0x80000300, Chest = 0x80000400; + Check(AutoIdPolicy.Classify(false, Me, Corpse, Corpse, 0, 0) == C.Unknown, "not in the snapshot: unknown"); + Check(AutoIdPolicy.Classify(true, Me, 0, Me, 0, 0) == C.Inventory, "in the main pack"); + Check(AutoIdPolicy.Classify(true, Me, 0, 0, Me, 0) == C.Inventory, "worn"); + Check(AutoIdPolicy.Classify(true, Me, 0, Pack, 0, Me) == C.Inventory, "in a side pack"); + Check(AutoIdPolicy.Classify(true, Me, Pack, Pack, 0, Me) == C.Inventory, "in an opened own side pack: inventory"); + Check(AutoIdPolicy.Classify(true, Me, Corpse, Corpse, 0, 0) == C.Container, "in the open corpse"); + Check(AutoIdPolicy.Classify(true, Me, Chest, Pack, 0, Chest) == C.Container, "in a pack inside the open chest"); + Check(AutoIdPolicy.Classify(true, Me, Chest, Corpse, 0, 0) == C.World, "in a corpse that is not open"); + Check(AutoIdPolicy.Classify(true, Me, 0, 0, 0, 0) == C.World, "on the ground, nothing open"); + Check(AutoIdPolicy.Classify(true, Me, Corpse, 0, 0, 0) == C.World, "on the ground while a corpse is open (container 0 is not the open one)"); + Check(AutoIdPolicy.Classify(true, Me, Corpse, 0, Monster, 0) == C.World, "wielded by a monster"); + Check(AutoIdPolicy.Classify(true, 0, 0, 0, 0, 0) == C.World, "player unknown: nothing is inventory"); + } + + private static void AutoIdModeParse() + { + _case = "autoid mode parse"; + Check(AutoIdPolicy.TryParseMode("ALL", out AutoIdMode m) && m == AutoIdMode.All, "all"); + Check(AutoIdPolicy.TryParseMode(" limited ", out m) && m == AutoIdMode.Limited, "limited"); + Check(AutoIdPolicy.TryParseMode("off", out m) && m == AutoIdMode.Off, "off"); + Check(!AutoIdPolicy.TryParseMode("sometimes", out m) && m == AutoIdPolicy.DefaultMode, "unknown: false, default"); + foreach (AutoIdMode mode in Enum.GetValues()) + Check(AutoIdPolicy.TryParseMode(AutoIdPolicy.Name(mode), out m) && m == mode, $"{mode} round-trips by name"); + foreach (AutoIdMode mode in Enum.GetValues()) + Check(AutoIdPolicy.TryParseMode(mode.ToString(), out m) && m == mode, $"{mode} round-trips as engine.json writes it"); + } + + // ---- the engine-send marker -------------------------------------------------------- + + private static void IdMarkerScopes() + { + _case = "id marker"; + Check(EngineSendMarker.Current == IdRequester.None, "no marker outside a scope"); + using (EngineSendMarker.Enter(IdRequester.Plugin)) + { + Check(EngineSendMarker.Current == IdRequester.Plugin, "marked inside"); + using (EngineSendMarker.Enter(IdRequester.AutoIdContainer)) + Check(EngineSendMarker.Current == IdRequester.AutoIdContainer, "nested scope"); + Check(EngineSendMarker.Current == IdRequester.Plugin, "outer marker restored"); + + IdRequester seenElsewhere = IdRequester.Self; + var th = new Thread(() => seenElsewhere = EngineSendMarker.Current); + th.Start(); + th.Join(); + Check(seenElsewhere == IdRequester.None, "another thread is not marked (thread-local)"); + } + Check(EngineSendMarker.Current == IdRequester.None, "cleared after the scope"); + try + { + using (EngineSendMarker.Enter(IdRequester.Ui)) + throw new InvalidOperationException(); + } + catch (InvalidOperationException) { } + Check(EngineSendMarker.Current == IdRequester.None, "cleared after an exception"); + } + + private static void IdMarkerRidesTheQueue() + { + _case = "id marker queue"; + var q = new PendingIdQueue(8); + q.Enqueue(1, 1000, 1, MergeMax, 0, (byte)IdRequester.AutoIdContainer); + q.Enqueue(2, 1000, 1, MergeMax, 0, (byte)IdRequester.Plugin); + Check(q.Enqueue(1, 1100, 1, MergeMax, 0, (byte)IdRequester.Plugin) == PendingIdQueue.Result.Merged, "merged"); + Check(q.TryDequeue(out var a) && a.Source == (byte)IdRequester.AutoIdContainer, "the requester rides with the entry; a merge keeps the first"); + Check(q.TryDequeue(out var b) && b.Source == (byte)IdRequester.Plugin, "second entry's requester"); + q.Enqueue(3, 1200, 1, MergeMax); + Check(q.TryDequeue(out var c) && c.Source == 0, "unmarked stays None"); + } + + private static void IdHeartbeatNames() + { + _case = "id heartbeat names"; + foreach (IdRequester who in Enum.GetValues()) + { + string s = IdRequesters.Short(who) + "="; + foreach (string bad in new[] { "fps=", "plug=", "login=", "qd=" }) + Check(!s.Contains(bad) && !bad.Contains(s), $"{who}: \"{s}\" vs {bad}"); + if (who != IdRequester.None) + Check(IdRequesters.Label((uint)who).Length > 0, $"{who} has a flight label"); + } + Check(IdRequesters.Label(0) == "" && IdRequesters.Label(99) == "", "no label for none or an unknown code"); + var regex = new System.Text.RegularExpressions.Regex(@"hb #\d+ .*?fps=(\d+) .*?plug=(\d+)/s .*?login=(\d)(?:.*?qd=(\d+))?"); + string sample = "autoid 60s: mode=limited sent tgt=1 ctr=2 inv=0 wld=0 plg=5 slf=0 ui=0 cli=3 tot=11 skip mode=900 age=4 defer=0 fresh=1 pend=2"; + Check(!regex.IsMatch(sample), "the minute line does not match the launcher's heartbeat regex"); + } +} diff --git a/tools/EngineRobustnessTests/EngineRobustnessTests.csproj b/tools/EngineRobustnessTests/EngineRobustnessTests.csproj index 341bff5..fad8f64 100644 --- a/tools/EngineRobustnessTests/EngineRobustnessTests.csproj +++ b/tools/EngineRobustnessTests/EngineRobustnessTests.csproj @@ -16,6 +16,8 @@ DumpInProgressRule.cs the launcher holds its wedge kill while an OOM dump is written (capped) 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 + IdRequester.cs the engine-send marker that tags every engine 0xC8 Run: dotnet run -c Release (exit 0 = pass, 1 = fail) --> @@ -40,6 +42,8 @@ + + diff --git a/tools/EngineRobustnessTests/Program.cs b/tools/EngineRobustnessTests/Program.cs index 2bead51..6ad3ec6 100644 --- a/tools/EngineRobustnessTests/Program.cs +++ b/tools/EngineRobustnessTests/Program.cs @@ -42,6 +42,8 @@ internal static partial class Program RunRingAndGateTests(); + RunAutoIdLimitTests(); + Console.WriteLine($"{_checks} check(s), {_failed} failed."); return _failed == 0 ? 0 : 1; } diff --git a/tools/EngineSettingsTests/EngineSettingsTests.csproj b/tools/EngineSettingsTests/EngineSettingsTests.csproj index 0999f32..4201d3e 100644 --- a/tools/EngineSettingsTests/EngineSettingsTests.csproj +++ b/tools/EngineSettingsTests/EngineSettingsTests.csproj @@ -23,6 +23,7 @@ + diff --git a/tools/EngineSettingsTests/Program.cs b/tools/EngineSettingsTests/Program.cs index 2b8e8f7..8c506f3 100644 --- a/tools/EngineSettingsTests/Program.cs +++ b/tools/EngineSettingsTests/Program.cs @@ -47,6 +47,7 @@ namespace EngineSettingsTests Run(nameof(OwnedKeysMatchEngineSettings), OwnedKeysMatchEngineSettings); Run(nameof(SaveKeepsLauncherKeys), SaveKeepsLauncherKeys); Run(nameof(SaveRoundTripsOwnedKeys), SaveRoundTripsOwnedKeys); + Run(nameof(AutoIdModeRoundTrips), AutoIdModeRoundTrips); Run(nameof(SaveWithoutFileWritesOwnedKeys), SaveWithoutFileWritesOwnedKeys); Run(nameof(SaveLeavesMalformedFileAlone), SaveLeavesMalformedFileAlone); Run(nameof(MaxHotReloadsReadAndKept), MaxHotReloadsReadAndKept); @@ -83,7 +84,12 @@ namespace EngineSettingsTests case "imgui-off": EngineSettings.EnableImGuiBackend = false; break; case "dcclose-off": EngineSettings.CloseOnServerDisconnect = false; break; case "dcclose-on": EngineSettings.CloseOnServerDisconnect = true; break; + case "autoid": + if (!RynthCore.Engine.Compatibility.AutoIdPolicy.TryParseMode(args[1], out var aim)) throw new ArgumentException(args[1]); + EngineSettings.AutoIdMode = aim; + break; case "dump": + Console.WriteLine("AutoIdMode=" + EngineSettings.AutoIdMode); Console.WriteLine("PluginPaths=" + string.Join("|", EngineSettings.PluginPaths)); Console.WriteLine("StartTooltip=" + EngineSettings.IsUiHookEnabled("StartTooltip")); Console.WriteLine("DecalBridge=" + EngineSettings.DecalBridgeMode); @@ -216,6 +222,33 @@ namespace EngineSettingsTests Check(ReadJson(path).TryGetProperty("EnableDcompOverlay", out _), "launcher key still there"); } + private static void AutoIdModeRoundTrips() + { + string dir = NewDir("autoid"); + string path = Path.Combine(dir, "engine.json"); + File.WriteAllText(path, LauncherFile); + var (exit, output) = RunChild(path, "dump"); + Eq(exit, 0, "dump"); + Check(output.Contains("AutoIdMode=Limited"), "default is Limited: " + output); + + Eq(RunChild(path, "autoid", "off").Exit, 0, "set off"); + Eq(ReadJson(path).GetProperty("AutoIdMode").GetString(), "Off", "saved as \"Off\""); + (exit, output) = RunChild(path, "dump"); + Check(output.Contains("AutoIdMode=Off"), "Off read back: " + output); + + Eq(RunChild(path, "autoid", "all").Exit, 0, "set all"); + (exit, output) = RunChild(path, "dump"); + Check(output.Contains("AutoIdMode=All"), "All read back: " + output); + + Eq(RunChild(path, "autoid", "limited").Exit, 0, "back to limited"); + Check(!ReadJson(path).TryGetProperty("AutoIdMode", out _), "the default leaves the key out"); + Check(ReadJson(path).TryGetProperty("EnableDcompOverlay", out _), "launcher key still there"); + + File.WriteAllText(path, LauncherFile.Replace("\"LoggingLevel\"", "\"AutoIdMode\": \"bogus\", \"LoggingLevel\"")); + (exit, output) = RunChild(path, "dump"); + Check(output.Contains("AutoIdMode=Limited"), "an unknown value reads as the default: " + output); + } + private static void SaveWithoutFileWritesOwnedKeys() { string dir = NewDir("nofile"); diff --git a/tools/FlightRecorderTests/FlightRecorderTests.csproj b/tools/FlightRecorderTests/FlightRecorderTests.csproj index 3fae4aa..57d39be 100644 --- a/tools/FlightRecorderTests/FlightRecorderTests.csproj +++ b/tools/FlightRecorderTests/FlightRecorderTests.csproj @@ -34,6 +34,7 @@ + diff --git a/tools/FlightRecorderTests/Program.cs b/tools/FlightRecorderTests/Program.cs index 245f357..c8018a0 100644 --- a/tools/FlightRecorderTests/Program.cs +++ b/tools/FlightRecorderTests/Program.cs @@ -30,6 +30,7 @@ internal static unsafe class Program RetransmitDedupe(); ResendRequestMarker(); EngineTagging(); + IdentifyTagging(); EngineRepeatFolding(); DetectUseRefusal(); @@ -378,6 +379,64 @@ internal static unsafe class Program Has(engineLines, "engine UseObject(0x80068ACE, 0)", "engine call markers written"); } + private static byte[] Identify(uint obj) => Action(0x00C8, new Body().U32(obj)); + + private static void IdentifyTagging() + { + Case("capture: an IdentifyObject is [eng:] after an engine send for that id, otherwise [cli]"); + var c = NewCapture(); + LoginAs(c); + int marks = Count(c, FlightDir.Mark); + c.EngineSend((byte)IdRequester.AutoIdContainer, Corpse); + Eq(Count(c, FlightDir.Mark), marks, "an engine send writes no marker line"); + _t += 30; + Out(c, Identify(Corpse)); + Has(Last(c), "[eng:autoid-container] IdentifyObject 0x80068ACE", "autoid container send"); + Eq(c.IdentifyForeignTotal, 0L, "not counted as foreign"); + + Out(c, Identify(Corpse)); + Has(Last(c), "[cli] IdentifyObject", "a second 0xC8 with no engine send is AC's or Decal's"); + Eq(c.IdentifyForeignTotal, 1L, "counted as foreign"); + + c.EngineSend((byte)IdRequester.Plugin, Other); + Out(c, Identify(Corpse)); + Has(Last(c), "[cli]", "an engine send for another id does not tag this one"); + Out(c, Identify(Other)); + Has(Last(c), "[eng:plugin] IdentifyObject 0x80012345", "plugin send matched by id"); + + c.EngineSend((byte)IdRequester.AutoIdTarget, Other); + _t += FlightCapture.EngineMatchMs + 1; + Out(c, Identify(Other)); + Has(Last(c), "[cli]", "too late to match"); + + c.EngineSend((byte)IdRequester.AutoIdTarget, Other); + c.EngineSend((byte)IdRequester.AutoIdInventory, Other); + Out(c, Identify(Other)); + Has(Last(c), "[eng:autoid-target]", "two sends for one id: the older first"); + Out(c, Identify(Other)); + Has(Last(c), "[eng:autoid-inventory]", "then the newer"); + + c.EngineSend(0, Corpse); + 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). + c.EngineCall("UseObject", Corpse, 0); + for (uint i = 0; i < 64; 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"); + + foreach (IdRequester who in Enum.GetValues()) + { + if (who == IdRequester.None) continue; + Check(IdRequesters.Label((byte)who).Length > 0, $"{who} has a label"); + } + } + private static void EngineRepeatFolding() { Case("capture: identical engine calls within 1 s fold into one line plus a 'repeated' line"); diff --git a/tools/check_offthread_mutators.py b/tools/check_offthread_mutators.py index 7ab4827..5e8dbd0 100644 --- a/tools/check_offthread_mutators.py +++ b/tools/check_offthread_mutators.py @@ -98,6 +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 ("RynthCoreChatCommands.cs", "Reply"), # /rc and /rv plates replies: only EnqueueWriteToChat ("AcMouseOver.cs", "Say"), # /rc acmouse watch lines: only EnqueueWriteToChat (and the log) }