diff --git a/src/RynthCore.Engine/Compatibility/AutoIdDrain.cs b/src/RynthCore.Engine/Compatibility/AutoIdDrain.cs index 4f84895..313b201 100644 --- a/src/RynthCore.Engine/Compatibility/AutoIdDrain.cs +++ b/src/RynthCore.Engine/Compatibility/AutoIdDrain.cs @@ -18,7 +18,13 @@ // 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. +// AutoIdPolicy.UnknownMaxWaitMs) instead of being dropped at MinAgeMs. Only containers are +// looked into, and a sweep that overflowed the pending list counts as not done: it runs +// again once there is room. +// +// Combat: Inventory sends wait while a target is selected or a cast or attack +// is in flight (Context.CombatBusy). Each 0xC8 raises AC's busy count, and plugins gate +// their casts on it. The selected target and an open container are not held. // // 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 @@ -49,7 +55,9 @@ internal interface IAutoIdWorld /// Its appraisal is cached and recent. bool IsFresh(uint id); /// Queue the 0xC8 for AC's main thread; false = refused (transition, ring full). - bool Enqueue(uint id, IdRequester who); + bool QueueIdentify(uint id, IdRequester who); + /// It holds items (a pack, a chest): only these are looked into by the login sweep. + bool IsContainer(uint id); } internal sealed class AutoIdDrain @@ -70,13 +78,14 @@ internal sealed class AutoIdDrain public long OpenedAtMs; // when OpenContainer was opened (0 = unknown) public long SettleUntilMs; // PlayerLifecycleLog.SettleUntilMs public long LoginCompleteAtMs; // LoginLifecycleHooks.LoginCompleteAtMs + public bool CombatBusy; // a target selected, or a cast or attack in flight (Inventory waits) } 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 + public byte Counted; // waits already counted: 1 = age, 2 = defer, 4 = rate, 8 = combat } private readonly IAutoIdWorld _w; @@ -88,7 +97,7 @@ internal sealed class AutoIdDrain private long _lastInventorySendMs; private long _sweptLoginAt; - private long _skipMode, _skipAge, _skipDefer, _skipFresh, _skipRate, _overflow, _incomingDropped, _refused, _swept; + private long _skipMode, _skipAge, _skipDefer, _skipFresh, _skipRate, _skipCombat, _overflow, _incomingDropped, _refused, _swept; public AutoIdDrain(IAutoIdWorld world) { _w = world; } @@ -97,6 +106,8 @@ internal sealed class AutoIdDrain public long SkipDefer => Interlocked.Read(ref _skipDefer); public long SkipFresh => Interlocked.Read(ref _skipFresh); public long SkipRate => Interlocked.Read(ref _skipRate); + /// Inventory candidates that waited for combat to end (counted once each). + public long SkipCombat => Interlocked.Read(ref _skipCombat); /// Candidates not taken because the Limited pending list was full. public long Overflow => Interlocked.Read(ref _overflow); /// Oldest new candidates dropped because _incoming was full (the drain was held). @@ -171,23 +182,32 @@ internal sealed class AutoIdDrain return; if (c.Now < c.LoginCompleteAtMs + AutoIdPolicy.DeferMs || c.PlayerId == 0 || !_w.SnapshotWarm) return; - _sweptLoginAt = c.LoginCompleteAtMs; + // A full pending list: try again on a later tick (no walk, no overflow counted). + if (_pending.Count >= MaxPendingLimited) + return; Span top = stackalloc uint[MaxSweepItems]; Span inner = stackalloc uint[MaxSweepItems]; int n = _w.CollectOwned(c.PlayerId, top); int before = _pending.Count; + long overflowBefore = Interlocked.Read(ref _overflow); 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. + // A side pack: its contents are the pack too. Only a container is looked into. + if (!_w.IsContainer(id)) + continue; 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); + // Done only when everything fit; an overflowed sweep runs again once there is room + // (what it already added is not added twice: AddPending skips ids already pending). + if (Interlocked.Read(ref _overflow) == overflowBefore) + _sweptLoginAt = c.LoginCompleteAtMs; } private int DrainPending(in Context c, int sent) @@ -227,11 +247,11 @@ internal sealed class AutoIdDrain 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); + fresh, cached, rateOk, snapshotWarm, c.CombatBusy); switch (v) { case AutoIdPolicy.Verdict.Send: - if (!_w.Enqueue(p.Id, RequesterFor(cls))) + if (!_w.QueueIdentify(p.Id, RequesterFor(cls))) { // Refused (a transition began, or the ring is full): keep it, and // stop sending this tick. @@ -258,6 +278,10 @@ internal sealed class AutoIdDrain if ((p.Counted & 4) == 0) { p.Counted |= 4; Interlocked.Increment(ref _skipRate); } _pending[keep++] = p; break; + case AutoIdPolicy.Verdict.WaitCombat: + if ((p.Counted & 8) == 0) { p.Counted |= 8; Interlocked.Increment(ref _skipCombat); } + _pending[keep++] = p; + break; case AutoIdPolicy.Verdict.SkipFresh: Interlocked.Increment(ref _skipFresh); _pendingIds.Remove(p.Id); diff --git a/src/RynthCore.Engine/Compatibility/AutoIdPolicy.cs b/src/RynthCore.Engine/Compatibility/AutoIdPolicy.cs index 04cda53..a07e0b1 100644 --- a/src/RynthCore.Engine/Compatibility/AutoIdPolicy.cs +++ b/src/RynthCore.Engine/Compatibility/AutoIdPolicy.cs @@ -27,7 +27,8 @@ // a client crashed in AC's CreateObject handling during the // login create burst). A container the player opened after the last // transition ended is not deferred. Inventory sends are capped at 5 a -// second. Creatures, ground items, other players: never. +// second and wait while a target is selected or a cast or attack is in +// flight. Creatures, ground items, other players: never. // Off nothing, the selected target included. // Plugins calling the host RequestId are not limited by any of this. // @@ -97,6 +98,8 @@ internal static class AutoIdPolicy WaitRate, /// Place unknown and the object snapshot still empty: keep it (up to UnknownMaxWaitMs). WaitSnapshot, + /// Inventory while in combat (a target selected, a cast or an attack in flight): keep it. + WaitCombat, } /// @@ -110,9 +113,12 @@ internal static class AutoIdPolicy /// : Inventory only, the send rate allows one now (). /// : 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). + /// : Inventory only, a target is selected or a cast or attack is in + /// flight. Each 0xC8 raises AC's busy count, which plugins gate casts on, so the pack waits. /// public static Verdict Decide(AutoIdMode mode, Class cls, long ageMs, bool inDefer, bool openedAfterSettle, - bool fresh, bool cached, bool inventoryRateOk = true, bool snapshotWarm = true) + bool fresh, bool cached, bool inventoryRateOk = true, bool snapshotWarm = true, + bool combatBusy = false) { switch (mode) { @@ -139,6 +145,7 @@ internal static class AutoIdPolicy if (cached) return Verdict.SkipFresh; if (ageMs < MinAgeMs) return Verdict.WaitAge; if (inDefer) return Verdict.WaitDefer; + if (combatBusy) return Verdict.WaitCombat; if (!inventoryRateOk) return Verdict.WaitRate; return Verdict.Send; case Class.Unknown: diff --git a/src/RynthCore.Engine/Compatibility/AutoIdService.cs b/src/RynthCore.Engine/Compatibility/AutoIdService.cs index abd69d8..9fc9a98 100644 --- a/src/RynthCore.Engine/Compatibility/AutoIdService.cs +++ b/src/RynthCore.Engine/Compatibility/AutoIdService.cs @@ -94,7 +94,14 @@ internal static class AutoIdService // 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); + // Block-bodied, and named apart from the create-path Enqueue, so + // tools/check_offthread_mutators.py scans it and its allow-list entry covers only this. + public bool QueueIdentify(uint id, IdRequester who) + { + return AcMainThreadQueue.EnqueueRequestId(id, who); + } + + public bool IsContainer(uint id) => ClientObjectHooks.IsContainerInSnapshot(id); } /// Re-creates not appraised because a recent appraisal is still cached. @@ -305,6 +312,10 @@ internal static class AutoIdService ? Interlocked.Read(ref _openedAtMs) : 0, SettleUntilMs = PlayerLifecycleLog.SettleUntilMs, LoginCompleteAtMs = LoginLifecycleHooks.LoginCompleteAtMs, + // Each 0xC8 raises AC's busy count, which plugins gate their casts on: the + // pack waits while a target is selected, a cast is in flight or an attack runs. + CombatBusy = target != 0 || CastGate.GetCastBusyState() != 0 + || (ClientActionGates.TryReadAttacking(out bool attacking) && attacking), }; _drain.Tick(ctx, sent); @@ -354,7 +365,7 @@ internal static class AutoIdService 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, _lastSkipRate; + private static long _lastForeign, _lastSkipMode, _lastSkipAge, _lastSkipDefer, _lastSkipFresh, _lastSkipRate, _lastSkipCombat; /// /// The last minute's IdentifyObject counts (heartbeat thread, once a minute): sent per @@ -365,7 +376,7 @@ internal static class AutoIdService public static string TakeMinuteLine() { long foreign = FlightRecorder.ForeignIdentifyTotal; - long sm = _drain.SkipMode, sa = _drain.SkipAge, sd = _drain.SkipDefer, sf = _drain.SkipFresh, sr = _drain.SkipRate; + long sm = _drain.SkipMode, sa = _drain.SkipAge, sd = _drain.SkipDefer, sf = _drain.SkipFresh, sr = _drain.SkipRate, sc = _drain.SkipCombat; var sb = new System.Text.StringBuilder(176); sb.Append("autoid 60s: mode=").Append(AutoIdPolicy.Name(Mode)).Append(" sent"); long total = 0; @@ -392,9 +403,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); + .Append(" rate=").Append(sr - _lastSkipRate).Append(" combat=").Append(sc - _lastSkipCombat); sb.Append(" pend=").Append(_drain.PendingCount); - _lastSkipMode = sm; _lastSkipAge = sa; _lastSkipDefer = sd; _lastSkipFresh = sf; _lastSkipRate = sr; + _lastSkipMode = sm; _lastSkipAge = sa; _lastSkipDefer = sd; _lastSkipFresh = sf; _lastSkipRate = sr; _lastSkipCombat = sc; return sb.ToString(); } @@ -425,7 +436,7 @@ internal static class AutoIdService { 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 login or a portal/death/teleport; inventory at most {1000 / AutoIdPolicy.InventoryMinIntervalMs}/s)", + _ => $"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, and not while a target is selected or a cast or attack is in flight)", }; string extra = ""; if (_drain.Overflow > 0) extra += $", overflow {_drain.Overflow}"; @@ -435,7 +446,7 @@ internal static class AutoIdService $"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 {_drain.SkipMode}, fresh {_drain.SkipFresh}, recent re-create {SkippedRecentCount}; " + - $"waited: age {_drain.SkipAge}, defer {_drain.SkipDefer}, rate {_drain.SkipRate}; refused {_drain.Refused} (kept); " + + $"waited: age {_drain.SkipAge}, defer {_drain.SkipDefer}, rate {_drain.SkipRate}, combat {_drain.SkipCombat}; refused {_drain.Refused} (kept); " + $"login sweep {_drain.Swept}; pending now {_drain.PendingCount}{extra}.", }; } diff --git a/src/RynthCore.Engine/Compatibility/ClientObjectHooks.cs b/src/RynthCore.Engine/Compatibility/ClientObjectHooks.cs index 539ef79..d0d7cd9 100644 --- a/src/RynthCore.Engine/Compatibility/ClientObjectHooks.cs +++ b/src/RynthCore.Engine/Compatibility/ClientObjectHooks.cs @@ -3830,16 +3830,21 @@ internal static class ClientObjectHooks && PwdLayout.TryGetInstanceId(e.Bytes, stype, out value); } - /// - /// Off-thread helper for UpdateObjectInventoryHooks: writes the ids whose PWD - /// container or wielder is from the main-thread - /// snapshot, under one lock, with no AC access. Returns the count written. - /// + /// The PWD snapshot has been filled at least once (AutoId: an object missing from it may still come). internal static bool HasPwdSnapshot { get { lock (_weeniePtrSwapLock) return _pwdFront.Count > 0; } } + /// The object holds items (ItemsCapacity, stype 6, > 0 in the PWD snapshot: a pack, a chest). + internal static bool IsContainerInSnapshot(uint objectId) => + TryGetPwdSnapshotInt(objectId, 6, out int capacity) && capacity > 0; + + /// + /// Off-thread helper for UpdateObjectInventoryHooks: writes the ids whose PWD + /// container or wielder is from the main-thread + /// snapshot, under one lock, with no AC access. Returns the count written. + /// internal static int CollectOwnedIdsFromSnapshot(uint containerId, Span dest) { int found = 0; diff --git a/src/RynthCore.Engine/Compatibility/CombatActionHooks.cs b/src/RynthCore.Engine/Compatibility/CombatActionHooks.cs index ee4ec4e..f4b18fe 100644 --- a/src/RynthCore.Engine/Compatibility/CombatActionHooks.cs +++ b/src/RynthCore.Engine/Compatibility/CombatActionHooks.cs @@ -468,21 +468,20 @@ internal static class CombatActionHooks if (AcMainThreadQueue.MustQueue(teardown: false)) return AcMainThreadQueue.EnqueueRequestId(objectId, who); + // Registered BEFORE the call, so the tag is in place whether AC puts the 0xC8 on the + // wire inside the call or later. A call that fails or throws retires its entry, so it + // cannot mis-tag a later 0xC8 for the same object. + int tag = who != Net.IdRequester.None ? Net.FlightRecorder.EngineSend((byte)who, objectId) : -1; try { 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); - } + if (sent) Net.IdSendStats.CountSent(who); + else Net.FlightRecorder.EngineSendFailed(tag, objectId); return sent; } catch { + Net.FlightRecorder.EngineSendFailed(tag, objectId); return false; } } diff --git a/src/RynthCore.Engine/Net/FlightCapture.cs b/src/RynthCore.Engine/Net/FlightCapture.cs index 1faec0b..e079749 100644 --- a/src/RynthCore.Engine/Net/FlightCapture.cs +++ b/src/RynthCore.Engine/Net/FlightCapture.cs @@ -611,17 +611,35 @@ internal sealed unsafe class FlightCapture /// /// 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>]. + /// EngineMatchMs is tagged [eng:<who>]. Called BEFORE the send, so a 0xC8 that AC puts + /// on the wire inside the call is still matched. Returns a token for EngineSendFailed, or -1. /// - public void EngineSend(byte who, uint id) + public int EngineSend(byte who, uint id) { - if (who == 0) return; + if (who == 0) return -1; long now = _clock(); lock (_engineLock) { - ref IdPending p = ref _idPending[_idPendingNext]; + int slot = _idPendingNext; + ref IdPending p = ref _idPending[slot]; _idPendingNext = (_idPendingNext + 1) & (_idPending.Length - 1); p.Id = id; p.Who = who; p.Stamp = now; p.Used = false; + return slot; + } + } + + /// + /// The send registered as did not happen (the call returned false or + /// threw): retire its entry so it cannot tag a later 0xC8 for the same id. A no-op when the + /// entry was already matched or the slot has since been reused for another id. + /// + public void EngineSendFailed(int token, uint id) + { + if (token < 0 || token >= _idPending.Length) return; + lock (_engineLock) + { + ref IdPending p = ref _idPending[token]; + if (p.Id == id && !p.Used) p.Used = true; } } diff --git a/src/RynthCore.Engine/Net/FlightRecorder.cs b/src/RynthCore.Engine/Net/FlightRecorder.cs index c2cb398..998a98a 100644 --- a/src/RynthCore.Engine/Net/FlightRecorder.cs +++ b/src/RynthCore.Engine/Net/FlightRecorder.cs @@ -126,12 +126,22 @@ internal static unsafe class FlightRecorder } /// 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) + /// (IdRequester): the 0xC8 it produces is tagged [eng:<who>]. Call it before the send; the + /// token goes to EngineSendFailed when the send does not happen. -1 while the recorder is off. + public static int EngineSend(byte who, uint id) { FlightCapture? c = _cap; - if (c == null || _paused) return; - try { c.EngineSend(who, id); } catch { } + if (c == null || _paused) return -1; + try { return c.EngineSend(who, id); } catch { return -1; } + } + + /// The send registered as did not happen: retire its entry. + public static void EngineSendFailed(int token, uint id) + { + if (token < 0) return; + FlightCapture? c = _cap; + if (c == null) return; + try { c.EngineSendFailed(token, id); } catch { } } /// IdentifyObject messages sent with no engine send to match (AC or Decal); -1 while the recorder is off. diff --git a/tools/EngineRobustnessTests/AutoIdDrainTests.cs b/tools/EngineRobustnessTests/AutoIdDrainTests.cs index 69b2c26..193bcae 100644 --- a/tools/EngineRobustnessTests/AutoIdDrainTests.cs +++ b/tools/EngineRobustnessTests/AutoIdDrainTests.cs @@ -17,6 +17,8 @@ internal static partial class Program public readonly HashSet Cached = new(); public readonly HashSet Released = new(); public bool Refuse; + public readonly HashSet Containers = new(); + public readonly List Looked = new(); // every CollectOwned call public readonly List<(uint Id, IdRequester Who, long At)> Sent = new(); public long Now; @@ -30,6 +32,7 @@ internal static partial class Program public bool SnapshotWarm => Warm; public int CollectOwned(uint container, Span dest) { + Looked.Add(container); if (!Warm) return 0; int n = 0; foreach (var kv in Snapshot) @@ -42,7 +45,8 @@ internal static partial class Program 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) + public bool IsContainer(uint id) => Containers.Contains(id); + public bool QueueIdentify(uint id, IdRequester who) { if (Refuse) return false; Sent.Add((id, who, Now)); @@ -53,9 +57,10 @@ internal static partial class Program private const uint Me = 0x50000001, SidePack = 0x80000900; - private static AutoIdDrain.Context Ctx(FakeWorld w, long loginAt, AutoIdMode mode = AutoIdMode.Limited, long settle = 0) => new() + private static AutoIdDrain.Context Ctx(FakeWorld w, long loginAt, AutoIdMode mode = AutoIdMode.Limited, long settle = 0, bool combat = false) => new() { Now = w.Now, Mode = mode, PlayerId = Me, OpenContainer = 0, OpenedAtMs = 0, SettleUntilMs = settle, LoginCompleteAtMs = loginAt, + CombatBusy = combat, }; /// Runs the 100 ms drain from w.Now to . @@ -75,6 +80,8 @@ internal static partial class Program DrainUnknownWaitsForSnapshotThenGivesUp(); DrainRefusedEnqueueIsKept(); DrainBounds(); + DrainCombatHoldsInventory(); + DrainSweepRetriesAfterOverflow(); } // The pack is created at login, before the snapshot is warm; it must still go out. @@ -86,7 +93,7 @@ internal static partial class Program // The login create burst: 20 pack items and a side pack with 5 more, created at 10 s. var pack = new List(); for (uint i = 1; i <= 20; i++) { pack.Add(0x80001000 + i); w.Snapshot[0x80001000 + i] = (Me, 0); } - w.Snapshot[SidePack] = (Me, 0); + w.Snapshot[SidePack] = (Me, 0); w.Containers.Add(SidePack); 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); @@ -117,7 +124,7 @@ internal static partial class Program 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); + w.Snapshot[SidePack] = (Me, 0); w.Containers.Add(SidePack); 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 @@ -133,6 +140,9 @@ internal static partial class Program 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"); + // Only containers are looked into: the player, then the side pack; never a sword. + Check(w.Looked.All(x => x == Me || x == SidePack) && w.Looked.Contains(SidePack), + $"only containers looked into ({string.Join(",", w.Looked.Distinct().Select(x => x.ToString("X8")))})"); Check(d.Swept == 13, $"13 swept (7 main pack, the side pack, its 4, 1 worn), got {d.Swept}"); int count = w.Sent.Count; @@ -229,4 +239,60 @@ internal static partial class Program f.Tick(Ctx(h, 0, AutoIdMode.All), AutoIdDrain.MaxPerTick); Check(f.PendingCount == AutoIdDrain.MaxIncoming, $"the newest {AutoIdDrain.MaxIncoming} kept, got {f.PendingCount}"); } -} + + // The pack waits through combat (target selected, cast or attack in flight); kept, not + // dropped; an open container is not held. + private static void DrainCombatHoldsInventory() + { + _case = "drain combat"; + const uint Chest = 0x80000A00, Loot = 0x80000A01; + var w = new FakeWorld { Now = 1_000_000, Warm = true }; + var d = new AutoIdDrain(w); + for (uint i = 1; i <= 3; i++) { w.Snapshot[0x8000C000 + i] = (Me, 0); d.Offer(0x8000C000 + i, w.Now - 10_000); } + w.Snapshot[Loot] = (Chest, 0); d.Offer(Loot, w.Now - 10_000); + AutoIdDrain.Context Fight(bool combat) => new() + { + Now = w.Now, Mode = AutoIdMode.Limited, PlayerId = Me, OpenContainer = Chest, OpenedAtMs = w.Now - 5_000, + SettleUntilMs = 0, LoginCompleteAtMs = 1, CombatBusy = combat, + }; + for (int k = 0; k < 50; k++) { d.Tick(Fight(true), 0); w.Now += 100; } + Check(w.Sent.Count == 1 && w.Sent[0].Id == Loot, $"in combat: only the open container's item is sent ({w.Sent.Count})"); + Check(d.PendingCount == 3, $"the pack is kept, pending {d.PendingCount}"); + Check(d.SkipCombat == 3, $"each counted once, got {d.SkipCombat}"); + for (int k = 0; k < 20; k++) { d.Tick(Fight(false), 0); w.Now += 100; } + Check(w.Sent.Count == 4 && d.PendingCount == 0, $"out of combat: the pack goes out (sent {w.Sent.Count}, pending {d.PendingCount})"); + Check(w.Sent.Skip(1).All(s => s.Who == IdRequester.AutoIdInventory), "as autoid-inventory"); + } + + // A sweep that overflowed the pending list is not marked done; it runs again once + // there is room, and every pack item is still sent. + private static void DrainSweepRetriesAfterOverflow() + { + _case = "drain sweep overflow"; + long loginAt = 100_000, sweepAt = loginAt + AutoIdPolicy.DeferMs; + var pack = new List(); + for (uint i = 1; i <= 5; i++) pack.Add(0x8000D000 + i); + + // Full: the sweep does not walk (no overflow counted) and is not done. + var w = new FakeWorld { Now = sweepAt, Warm = true }; + foreach (uint id in pack) w.Snapshot[id] = (Me, 0); + var d = new AutoIdDrain(w); + for (uint i = 0; i < AutoIdDrain.MaxPendingLimited; i++) d.Offer(0x84000000 + i, w.Now); // young, unplaced: they wait + d.Tick(Ctx(w, loginAt), AutoIdDrain.MaxPerTick); + Check(d.PendingCount == AutoIdDrain.MaxPendingLimited && d.Swept == 0 && d.Overflow == 0, + $"pending full: no sweep yet (pending {d.PendingCount}, swept {d.Swept}, overflow {d.Overflow})"); + RunUntil(d, w, sweepAt + 20_000, loginAt); + Check(pack.All(id => w.Sent.Any(s => s.Id == id)), $"swept once there was room: all 5 sent ({w.Sent.Count})"); + + // Partly full: 2 fit, 3 overflow; the sweep runs again and the other 3 go out too. + var v = new FakeWorld { Now = sweepAt, Warm = true }; + foreach (uint id in pack) v.Snapshot[id] = (Me, 0); + var e = new AutoIdDrain(v); + for (uint i = 0; i < AutoIdDrain.MaxPendingLimited - 2; i++) e.Offer(0x85000000 + i, v.Now); + e.Tick(Ctx(v, loginAt), AutoIdDrain.MaxPerTick); + Check(e.Swept == 2 && e.Overflow == 3, $"2 fit, 3 overflowed (swept {e.Swept}, overflow {e.Overflow})"); + RunUntil(e, v, sweepAt + 20_000, loginAt); + Check(pack.All(id => v.Sent.Any(s => s.Id == id)), $"the overflowed 3 are swept again and sent ({v.Sent.Count})"); + Check(e.Swept == 5, $"5 swept in all, got {e.Swept}"); + } +} \ No newline at end of file diff --git a/tools/EngineRobustnessTests/AutoIdLimitTests.cs b/tools/EngineRobustnessTests/AutoIdLimitTests.cs index f0d95a7..82dbf3d 100644 --- a/tools/EngineRobustnessTests/AutoIdLimitTests.cs +++ b/tools/EngineRobustnessTests/AutoIdLimitTests.cs @@ -30,7 +30,7 @@ internal static partial class Program private static readonly long[] Ages = { 0, AutoIdPolicy.MinAgeMs - 1, AutoIdPolicy.MinAgeMs, 60_000, AutoIdPolicy.UnknownMaxWaitMs - 1, AutoIdPolicy.UnknownMaxWaitMs }; /// 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, bool rateOk, bool warm) + private static V Expected(AutoIdMode mode, C cls, long age, bool defer, bool openedAfter, bool fresh, bool cached, bool rateOk, bool warm, bool combat) { if (mode == AutoIdMode.Off) return V.SkipMode; if (mode == AutoIdMode.All) return cls == C.Target && fresh ? V.SkipFresh : V.Send; @@ -39,7 +39,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.Inventory => cached ? V.SkipFresh : young ? V.WaitAge : defer ? V.WaitDefer : combat ? V.WaitCombat : !rateOk ? V.WaitRate : V.Send, C.Unknown => young ? V.WaitAge : !warm && age < AutoIdPolicy.UnknownMaxWaitMs ? V.WaitSnapshot : V.SkipMode, _ => V.SkipMode, }; @@ -58,16 +58,17 @@ internal static partial class Program foreach (bool fresh in new[] { false, true }) foreach (bool rateOk in new[] { false, true }) foreach (bool warm in new[] { false, true }) + foreach (bool combat in new[] { false, true }) { if (fresh && !cached) continue; // fresh implies cached rows++; - 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); + V got = AutoIdPolicy.Decide(mode, cls, age, defer, opened, fresh, cached, rateOk, warm, combat); + V want = Expected(mode, cls, age, defer, opened, fresh, cached, rateOk, warm, combat); if (got != want && wrong++ < 10) - Check(false, $"{mode} {cls} age={age} defer={defer} opened={opened} cached={cached} fresh={fresh} rateOk={rateOk} warm={warm}: want {want}, got {got}"); + Check(false, $"{mode} {cls} age={age} defer={defer} opened={opened} cached={cached} fresh={fresh} rateOk={rateOk} warm={warm} combat={combat}: want {want}, got {got}"); } Check(wrong == 0, $"{wrong} of {rows} rows wrong"); - Check(rows == 3 * 5 * 6 * 2 * 2 * 3 * 2 * 2, $"row count {rows}"); + Check(rows == 3 * 5 * 6 * 2 * 2 * 3 * 2 * 2 * 2, $"row count {rows}"); } /// The same rules as named cases, so a mutation is easy to read off a failure. @@ -104,6 +105,11 @@ internal static partial class Program Check(AutoIdPolicy.Decide(AutoIdMode.Limited, C.Container, Old, false, true, false, false, inventoryRateOk: false) == V.Send, "the rate cap is the inventory's only (container)"); Check(AutoIdPolicy.Decide(AutoIdMode.Limited, C.Target, 0, true, false, false, false, inventoryRateOk: false) == V.Send, "the rate cap never holds the selected target"); Check(AutoIdPolicy.Decide(AutoIdMode.All, C.Inventory, 0, false, false, false, false, inventoryRateOk: false) == V.Send, "All mode keeps the old behaviour (no cap)"); + // Combat: only the pack waits; the target and an open container do not. + Check(AutoIdPolicy.Decide(AutoIdMode.Limited, C.Inventory, Old, false, false, false, false, combatBusy: true) == V.WaitCombat, "pack item waits while in combat"); + Check(AutoIdPolicy.Decide(AutoIdMode.Limited, C.Target, 0, false, false, false, false, combatBusy: true) == V.Send, "combat never holds the selected target"); + Check(AutoIdPolicy.Decide(AutoIdMode.Limited, C.Container, Old, false, true, false, false, combatBusy: true) == V.Send, "combat never holds an open container"); + Check(AutoIdPolicy.Decide(AutoIdMode.All, C.Inventory, Old, false, false, false, false, combatBusy: true) == V.Send, "All mode: no combat hold (old behaviour)"); // 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"); diff --git a/tools/FlightRecorderTests/Program.cs b/tools/FlightRecorderTests/Program.cs index 8627749..83e8f4f 100644 --- a/tools/FlightRecorderTests/Program.cs +++ b/tools/FlightRecorderTests/Program.cs @@ -419,6 +419,34 @@ internal static unsafe class Program c.EngineSend(0, Corpse); Out(c, Identify(Corpse)); Has(Last(c), "[cli]", "a send without a requester is not registered"); + Eq(c.EngineSend(0, Corpse), -1, "no requester: no token"); + + // Registered before the call (CombatActionHooks.RequestId): a 0xC8 that AC sends + // synchronously, inside the call, is still tagged. + int sync = c.EngineSend((byte)IdRequester.AutoIdInventory, Corpse); + Out(c, Identify(Corpse)); + Has(Last(c), "[eng:autoid-inventory] IdentifyObject 0x80068ACE", "a send made inside the call is tagged"); + c.EngineSendFailed(sync, Corpse); // already matched: a no-op + Out(c, Identify(Corpse)); + Has(Last(c), "[cli]", "a matched entry is not revived"); + + // The call returned false (or threw): its entry is retired, so a later 0xC8 for the + // same id is AC's or Decal's. + long foreignFail = c.IdentifyForeignTotal; + int failed = c.EngineSend((byte)IdRequester.AutoIdInventory, Corpse); + Check(failed >= 0, "a registration returns a token"); + c.EngineSendFailed(failed, Corpse); + Out(c, Identify(Corpse)); + Has(Last(c), "[cli]", "a failed send leaves no live entry"); + Eq(c.IdentifyForeignTotal, foreignFail + 1, "and that 0xC8 counts as foreign"); + + // Retiring a token whose slot now holds another id leaves that entry alone. + int stale = c.EngineSend((byte)IdRequester.AutoIdTarget, Other); + c.EngineSendFailed(stale, Corpse); + c.EngineSendFailed(-1, Other); + c.EngineSendFailed(int.MaxValue, Other); + Out(c, Identify(Other)); + Has(Last(c), "[eng:autoid-target]", "a retire for another id, or a bad token, is a no-op"); // 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. diff --git a/tools/check_offthread_mutators.py b/tools/check_offthread_mutators.py index 44efa09..2cfa23a 100644 --- a/tools/check_offthread_mutators.py +++ b/tools/check_offthread_mutators.py @@ -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", "Enqueue"), # LiveWorld.Enqueue, called from AutoIdDrain on the drain timer: only EnqueueRequestId + ("AutoIdService.cs", "QueueIdentify"), # LiveWorld.QueueIdentify, AutoIdDrain's send 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) }