From ad8df0b67164c37aaf52692820ad1bcbf6004513 Mon Sep 17 00:00:00 2001 From: Daniel Wallace Date: Mon, 12 Oct 2026 16:20:32 -0700 Subject: [PATCH] Corpse ID: retry refused requests, re-ask the target, cap the burst The corpse's LongDesc (its killer name, which "my kills" mode needs) arrives only after an ID request, and AutoId may not appraise a corpse in time, so this request has to land. CorpseOpenController recorded the corpse as asked whether or not Host.RequestId returned true. The engine refuses RequestId during the teleport and death settle and drops stale queued requests, so a refused or dropped request was never retried and the claim stayed tentatively lootable until the 12 s timeout. - A corpse is recorded as asked only when RequestId returned true; a refused one is asked again, at least 250 ms apart per corpse. - An accepted request that brought no LongDesc within 3 s is asked once more, once per 3 s, with no give-up cap. Only the targeted corpse or the open container re-asks: HasLootWork evaluates every in-range corpse, and the others would send a stream of requests for corpses the bot is not going for. They get one accepted request each. - When a refusal window ends (after a teleport) every uncached corpse would be accepted in the same tick, so at most 2 new requests go out per scan tick, the target or open corpse first. The budget restarts after 250 ms for evaluations made outside a scan, so it never stays exhausted. - _corpseIdAskedAt and _corpseIdRefusedAt are cleared on delete and on the >200 prune. Tests (ActionPacingTests): refused-then-accepted; re-ask at 3 s and not before; two corpses where only the target re-asks; 20 uncached corpses through a refusal window; the open-container branch; the id map clears. Each case was mutation-checked. The test fake's RequestId can now refuse (RequestIdAccepts, RefusedIdRequests). Co-Authored-By: Claude Sonnet 5.5 Co-Authored-By: Claude Opus 5.5 (1M context) --- .../CorpseOpenController.cs | 60 ++++++- .../Fakes/FakeHost.cs | 12 +- .../Tests/ActionPacingTests.cs | 159 ++++++++++++++++++ 3 files changed, 225 insertions(+), 6 deletions(-) diff --git a/Plugins/RynthCore.Plugin.RynthAi/CorpseOpenController.cs b/Plugins/RynthCore.Plugin.RynthAi/CorpseOpenController.cs index 21dff24..611c35c 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/CorpseOpenController.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/CorpseOpenController.cs @@ -40,7 +40,14 @@ public sealed partial class RynthAiPlugin private readonly Dictionary _corpseAbandonCounts = new(); private const int NeverOpenedAbandonRetryMs = 30_000; private readonly HashSet _ownershipSkipLogged = new(); - private readonly HashSet _corpseIdRequested = new(); // corpses whose LongDesc ID was already requested + private readonly HashSet _corpseIdRequested = new(); // corpses whose LongDesc ID request the engine ACCEPTED + private readonly Dictionary _corpseIdAskedAt = new(); // ActionPacer.NowMs of the newest accepted request, for the re-ask + private readonly Dictionary _corpseIdRefusedAt = new(); // ActionPacer.NowMs of the newest REFUSED request + private const long CorpseIdRefusedRetryMs = 250; // a refused request is retried no faster than this, per corpse + private const int CorpseIdPerTick = 2; // new accepted requests per scan tick (the refusal window ending must not burst) + private int _corpseIdAcceptedThisTick; + private long _corpseIdBudgetAt; // when the budget last started over (a scan tick, or CorpseIdRefusedRetryMs without one) + private const long CorpseIdReaskMs = 3000; // no appraisal data this long after an accepted request: ask once more private int _busyCount; private long _busyCountLastIncrementAt; private long _busyCountBecamePositiveAt; // when count first went 0→positive @@ -341,7 +348,11 @@ public sealed partial class RynthAiPlugin Log($"[RynthAi] Pruned _ownershipSkipLogged"); } if (_corpseIdRequested.Count > 200) + { _corpseIdRequested.Clear(); + _corpseIdAskedAt.Clear(); + _corpseIdRefusedAt.Clear(); + } if (_corpseSkipLogged.Count > 200) _corpseSkipLogged.Clear(); if (_corpseWaitingSince.Count > 200) @@ -910,6 +921,38 @@ public sealed partial class RynthAiPlugin return EvaluateCorpseLootDecision(corpse).ShouldLoot; } + /// + /// Asks the engine to identify a corpse so its LongDesc (the killer name) arrives. Only a request the + /// engine accepted counts: it refuses RequestId around a teleport or a death and drops stale queued + /// requests, so a refused or dropped one is asked again. A refused one is retried every + /// CorpseIdRefusedRetryMs; an accepted one with no data is asked again every CorpseIdReaskMs, and only for + /// the corpse the bot is targeting or has open (any other corpse in range gets one accepted request, not a + /// stream). At most CorpseIdPerTick requests are accepted per scan tick, so a refusal window ending with + /// many uncached corpses in range does not burst. No give-up cap. + /// + private void TryRequestCorpseId(WorldObject corpse, string longDesc) + { + if (!string.IsNullOrWhiteSpace(longDesc) || !Host.HasRequestId) return; + long idNow = ActionPacer.NowMs(); + if (idNow - _corpseIdBudgetAt >= CorpseIdRefusedRetryMs) { _corpseIdAcceptedThisTick = 0; _corpseIdBudgetAt = idNow; } // evaluations outside a scan must not exhaust it for good + bool candidate = corpse.Id == _targetCorpseId || (_openedContainerId != 0 && corpse.Id == _openedContainerId); + bool due = !_corpseIdRequested.Contains(corpse.Id) + || (candidate && _corpseIdAskedAt.TryGetValue(corpse.Id, out long askedAt) && idNow - askedAt >= CorpseIdReaskMs); + if (!due || _corpseIdAcceptedThisTick >= CorpseIdPerTick) return; + if (_corpseIdRefusedAt.TryGetValue(corpse.Id, out long refusedAt) && idNow - refusedAt < CorpseIdRefusedRetryMs) return; + if (Host.RequestId(unchecked((uint)corpse.Id))) + { + _corpseIdRequested.Add(corpse.Id); + _corpseIdAskedAt[corpse.Id] = idNow; + _corpseIdRefusedAt.Remove(corpse.Id); + _corpseIdAcceptedThisTick++; + } + else + { + _corpseIdRefusedAt[corpse.Id] = idNow; + } + } + private CorpseLootDecision EvaluateCorpseLootDecision(WorldObject? corpse) { var settings = _dashboard?.Settings; @@ -929,9 +972,7 @@ public sealed partial class RynthAiPlugin // Corpse LongDesc is only available after the object is identified. // Request ID so the killer name is populated for the next check. - if (string.IsNullOrWhiteSpace(longDesc) && Host.HasRequestId && _corpseIdRequested.Add(corpse.Id)) - Host.RequestId(unchecked((uint)corpse.Id)); - + TryRequestCorpseId(corpse, longDesc); string killerName = ExtractCorpseKillerName(longDesc) ?? string.Empty; string myName = GetPlayerNameForLootOwnership(); bool inFellowship = _fellowshipTracker?.IsInFellowship == true; @@ -1847,7 +1888,8 @@ public sealed partial class RynthAiPlugin /// /// Caveat, deliberately kept: the in-range scan calls ShouldLootCorpse, /// which fires one Host.RequestId per corpse to populate the killer name - /// (guarded by _corpseIdRequested, so once per corpse ever). That is a + /// (guarded by _corpseIdRequested: once per accepted request, asked again after + /// CorpseIdReaskMs while no data has arrived). That is a /// memoized fetch rather than a mutation, and the old bottom-of-tick /// IsCorpseNavigationClaimActive call already did it on the same cadence — /// this moves it earlier in the tick, it does not add it. @@ -1932,6 +1974,12 @@ public sealed partial class RynthAiPlugin if (_objectCache == null || _playerId == 0) return false; + // A new scan tick: the identify budget starts over, and the corpse the bot is going for asks first. + _corpseIdAcceptedThisTick = 0; + _corpseIdBudgetAt = ActionPacer.NowMs(); + foreach (int cid in new[] { _targetCorpseId, _openedContainerId }) + if (cid != 0 && _objectCache[cid] is { } cand && cand.ObjectClass == AcObjectClass.Corpse) + TryRequestCorpseId(cand, cand.Values(StringValueKey.LongDesc, string.Empty)); long now = CorpseNowMs; int playerId = unchecked((int)_playerId); foreach (WorldObject candidate in _objectCache.GetLandscapeObjects()) @@ -2933,6 +2981,8 @@ public sealed partial class RynthAiPlugin _corpseCooldownUntil.Remove(sid); _ownershipSkipLogged.Remove(sid); _corpseIdRequested.Remove(sid); + _corpseIdAskedAt.Remove(sid); + _corpseIdRefusedAt.Remove(sid); _corpseSkipLogged.Remove(sid); _corpseWaitingSince.Remove(sid); diff --git a/Tools/RynthCore.RynthAiHostTests/Fakes/FakeHost.cs b/Tools/RynthCore.RynthAiHostTests/Fakes/FakeHost.cs index 8410c23..d846d9e 100644 --- a/Tools/RynthCore.RynthAiHostTests/Fakes/FakeHost.cs +++ b/Tools/RynthCore.RynthAiHostTests/Fakes/FakeHost.cs @@ -117,6 +117,10 @@ internal static unsafe class FakeHost public static readonly List<(uint Id, uint Pack, int Amount)> Moves = new(); /// Objects the fake says have appraisal data (HasAppraisalData). public static readonly HashSet Appraised = new(); + /// False = RequestId refuses (as the engine does around a teleport or a death): returns 0 + /// and is counted in , not in . + public static bool RequestIdAccepts = true; + public static int RefusedIdRequests; /// Opt-in (set before Create): UseObject, RequestId, HasAppraisalData and /// GetCurrentCombatMode (answering ). Tests written without /// them keep seeing those calls as absent. @@ -213,6 +217,7 @@ internal static unsafe class FakeHost Logs.Clear(); Chat.Clear(); ChatCommands.Clear(); AutoRunCalls.Clear(); AutoRun = false; Jumps = 0; TapJumpCalls = false; TapJumps = 0; Order.Clear(); Turns = 0; Casts.Clear(); StopCalls = false; Stops = 0; SetMotionCalls = false; MotionCalls.Clear(); Sent.Clear(); GiveCalls = false; Gives.Clear(); GiveLands = true; Uses.Clear(); IdRequests.Clear(); Moves.Clear(); Appraised.Clear(); WeaponCalls = false; CombatModeValue = 1; + RequestIdAccepts = true; RefusedIdRequests = 0; VTankFlags = -1; VTankSeq = 0; LogCostMicros = 0; ServerGates = false; UseDoneSeq = 0; CastBusy = 0; LastUseDoneError = 0; LastUseDoneCalls = false; // Spell mana costs "unknown" (no reserve beyond Get Mana At, no cost gate), so a portal.dat on @@ -726,7 +731,12 @@ internal static unsafe class FakeHost } [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] - private static int RequestId(uint id) { IdRequests.Add(id); return 1; } + private static int RequestId(uint id) + { + if (!RequestIdAccepts) { RefusedIdRequests++; return 0; } + IdRequests.Add(id); + return 1; + } [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] private static int HasAppraisalData(uint id) => Appraised.Contains(id) ? 1 : 0; diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/ActionPacingTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/ActionPacingTests.cs index 1356aa0..92b68bc 100644 --- a/Tools/RynthCore.RynthAiHostTests/Tests/ActionPacingTests.cs +++ b/Tools/RynthCore.RynthAiHostTests/Tests/ActionPacingTests.cs @@ -54,6 +54,11 @@ internal static class ActionPacingTests r.Add("pacing: no answer - each kind's time limit lets the next action go, logged, and nothing is force-cleared", TimeLimits); r.Add("pacing: heals (a plain heal waits for a corpse use's answer, 300 ms at Emergency, one behind a cast's result, 300 ms after the stance reads)", HealRules); r.Add("pacing (vitals): Drakkon 07:03 - a cast whose result is in waits for its UseDone: one cast, not a too-busy flood", CastWaitsForUseDone); + r.Add("corpse id: a refused RequestId is not recorded as asked - the next evaluation asks again and the accepted one goes out", CorpseIdRefusedRetried); + r.Add("corpse id: an accepted request with no data is asked again after 3 s (not before), once per 3 s, with no give-up cap", CorpseIdReaskedWithoutData); + r.Add("corpse id: two corpses in range, no data for either - only the targeted one re-asks; the other stays at one accepted request (a refused one is still retried)", CorpseIdOnlyCandidateReasks); + r.Add("corpse id: 20 uncached corpses, a refusal window, then accept - at most 2 requests in the first accepted tick, the target among them; refused retries are 250 ms apart", CorpseIdBurstCapped); + r.Add("corpse id: the open container is a candidate and re-asks; delete and the >200 prune clear every id map", CorpseIdOpenContainerAndCleanup); r.Add("pacing (vitals): a heal waits for an unanswered corpse use's answer, then goes at once; the emergency stance settle is unchanged", HealLatencyKept); r.Add("pacing (looting): one open per server answer, never re-sent on top of an unanswered one", LootOneOpenPerAnswer); r.Add("pacing (looting): Drakkon's stall is still found and said once with pacing on", LootStallStillDetected); @@ -468,6 +473,160 @@ internal static class ActionPacingTests finally { PaceOff(); } } + private static (Bot Bot, WorldObject Corpse) CorpseIdRig() + { + LootWorld(); + FakeHost.Strings.Remove((Corpse, LongDescKey)); // nothing appraised yet: no killer name + var host = FakeHost.Create(Player); + var bot = new Bot(host); + bot.Set("_targetCorpseId", unchecked((int)Corpse)); // the corpse the bot is going for: the only one that re-asks + var obj = bot.Get("_objectCache")[unchecked((int)Corpse)]!; + return (bot, obj); + } + + private static void CorpseIdRefusedRetried() => Paced(() => + { + var (bot, obj) = CorpseIdRig(); + FakeHost.RequestIdAccepts = false; + bot.Call("EvaluateCorpseLootDecision", obj); + Check.Eq(FakeHost.RefusedIdRequests, 1, "the engine refused the first RequestId"); + Check.Eq(FakeHost.IdRequests.Count(i => i == Corpse), 0, "so nothing went out"); + _t += 250; + FakeHost.RequestIdAccepts = true; + bot.Call("EvaluateCorpseLootDecision", obj); + Check.Eq(FakeHost.IdRequests.Count(i => i == Corpse), 1, "the next evaluation asked again and it was accepted"); + _t += 100; + bot.Call("EvaluateCorpseLootDecision", obj); + Check.Eq(FakeHost.IdRequests.Count(i => i == Corpse), 1, "an accepted request is not repeated at once"); + }); + + private static void CorpseIdReaskedWithoutData() => Paced(() => + { + var (bot, obj) = CorpseIdRig(); + int Asked() => FakeHost.IdRequests.Count(i => i == Corpse); + bot.Call("EvaluateCorpseLootDecision", obj); + Check.Eq(Asked(), 1, "t=0: the first request goes out"); + _t += 2_999; + bot.Call("EvaluateCorpseLootDecision", obj); + Check.Eq(Asked(), 1, "2.999 s, no data: not yet"); + _t += 1; + bot.Call("EvaluateCorpseLootDecision", obj); + Check.Eq(Asked(), 2, "3 s, no data: asked again"); + _t += 1_000; + bot.Call("EvaluateCorpseLootDecision", obj); + Check.Eq(Asked(), 2, "1 s after the re-ask: waits"); + _t += 2_000; + bot.Call("EvaluateCorpseLootDecision", obj); + Check.Eq(Asked(), 3, "one re-ask per 3 s, and no cap"); + for (int i = 0; i < 10; i++) { _t += 3_000; bot.Call("EvaluateCorpseLootDecision", obj); } + Check.Eq(Asked(), 13, "ten more 3 s periods, ten more asks"); + FakeHost.Strings[(Corpse, LongDescKey)] = $"Killed by {Me}."; + _t += 3_000; + bot.Call("EvaluateCorpseLootDecision", obj); + Check.Eq(Asked(), 13, "once the data has arrived nothing more is asked"); + }); + private static void CorpseIdOnlyCandidateReasks() => Paced(() => + { + LootWorld(); + FakeHost.Strings.Remove((Corpse, LongDescKey)); + FakeHost.Strings.Remove((CorpseB, LongDescKey)); + var host = FakeHost.Create(Player); + var bot = new Bot(host); + var cache = bot.Get("_objectCache"); + var a = cache[unchecked((int)Corpse)]!; + var b = cache[unchecked((int)CorpseB)]!; + bot.Set("_targetCorpseId", unchecked((int)Corpse)); + int Asked(uint id) => FakeHost.IdRequests.Count(i => i == id); + void Both() { bot.Call("EvaluateCorpseLootDecision", a); bot.Call("EvaluateCorpseLootDecision", b); } + + FakeHost.RequestIdAccepts = false; + Both(); + FakeHost.RequestIdAccepts = true; + _t += 250; Both(); + Check.Eq(Asked(Corpse), 1, "the candidate: refused once, then one accepted request"); + Check.Eq(Asked(CorpseB), 1, "the other corpse: a refused request is retried, one accepted request"); + for (int i = 0; i < 4; i++) { _t += 3_000; Both(); } + Check.Eq(Asked(Corpse), 5, "no data: the candidate re-asks once per 3 s"); + Check.Eq(Asked(CorpseB), 1, "the other corpse never asks a second time"); + bot.Set("_targetCorpseId", unchecked((int)CorpseB)); + _t += 3_000; Both(); + Check.Eq(Asked(CorpseB), 2, "once it becomes the candidate it re-asks"); + }); + private static void CorpseIdBurstCapped() => Paced(() => + { + LootWorld(); + FakeHost.Strings.Remove((Corpse, LongDescKey)); + FakeHost.Strings.Remove((CorpseB, LongDescKey)); + var host = FakeHost.Create(Player); + var bot = new Bot(host); + var cache = bot.Get("_objectCache"); + var ids = new System.Collections.Generic.List { Corpse, CorpseB }; + for (uint i = 0; i < 18; i++) + { + uint id = 0x80090000 + i; + FakeHost.Names[id] = "Corpse of Olthoi Swarm Worker"; + FakeHost.ItemTypes[id] = ItemTypeContainer; + FakeHost.NotAttackable.Add(id); + FakeHost.Positions[id] = (Me0.Cell, Me0.X + 2.0f + i * 0.1f, Me0.Y, Me0.Z); + cache.OnCreateObject(id); + ids.Add(id); + } + cache.Tick(); + uint target = ids[^1]; // created last: the scan reaches it last, so only the candidate-first rule puts it among the first two + bot.Set("_targetCorpseId", unchecked((int)target)); + void Scan() => bot.Call("HasUnlootedCorpsesInRange", 30.0); + + FakeHost.RequestIdAccepts = false; + for (int k = 0; k < 3; k++) { _t += 300; Scan(); } + Check.Eq(FakeHost.IdRequests.Count, 0, "the refusal window: nothing accepted"); + Check.True(FakeHost.RefusedIdRequests >= 20, $"every corpse was tried ({FakeHost.RefusedIdRequests} refusals)"); + int refusals = FakeHost.RefusedIdRequests; + _t += 100; Scan(); + Check.Eq(FakeHost.RefusedIdRequests, refusals, "100 ms later: refused corpses are not retried yet (250 ms apart)"); + + FakeHost.RequestIdAccepts = true; + _t += 300; Scan(); + Check.True(FakeHost.IdRequests.Count <= 2, $"the first accepted tick sends at most 2 ({FakeHost.IdRequests.Count})"); + Check.True(FakeHost.IdRequests.Contains(target), "and the candidate is among them"); + for (int k = 0; k < 12; k++) + { + int before = FakeHost.IdRequests.Count; + _t += 200; Scan(); + Check.True(FakeHost.IdRequests.Count - before <= 2, $"tick {k + 2}: at most 2 new requests"); + } + Check.Eq(FakeHost.IdRequests.Distinct().Count(), 20, "within a few ticks every corpse has been asked once"); + }); + + private static void CorpseIdOpenContainerAndCleanup() => Paced(() => + { + const BindingFlags F = BindingFlags.Instance | BindingFlags.NonPublic; + var (bot, obj) = CorpseIdRig(); + bot.Set("_targetCorpseId", 0); + bot.Set("_openedContainerId", unchecked((int)Corpse)); + int Asked() => FakeHost.IdRequests.Count(i => i == Corpse); + bot.Call("EvaluateCorpseLootDecision", obj); + _t += 3_000; + bot.Call("EvaluateCorpseLootDecision", obj); + Check.Eq(Asked(), 2, "the open container is a candidate: it re-asks after 3 s"); + + var asked = bot.Get>("_corpseIdAskedAt"); + var refused = bot.Get>("_corpseIdRefusedAt"); + var requested = bot.Get>("_corpseIdRequested"); + int sid = unchecked((int)Corpse); + refused[sid] = _t; + Check.True(asked.ContainsKey(sid) && requested.Contains(sid), "set-up: the corpse is recorded"); + bot.Call("HandleCorpseObjectDeleted", Corpse); + Check.False(asked.ContainsKey(sid), "delete clears _corpseIdAskedAt"); + Check.False(refused.ContainsKey(sid), "delete clears _corpseIdRefusedAt"); + Check.False(requested.Contains(sid), "delete clears _corpseIdRequested"); + + for (int i = 0; i < 201; i++) { requested.Add(i + 1); asked[i + 1] = _t; refused[i + 1] = _t; } + bot.Set("_lastCorpsePruneAt", 0L); + bot.Call("PruneCorpseCollections"); + Check.Eq(requested.Count, 0, "the >200 prune clears _corpseIdRequested"); + Check.Eq(asked.Count, 0, "the >200 prune clears _corpseIdAskedAt"); + Check.Eq(refused.Count, 0, "the >200 prune clears _corpseIdRefusedAt"); + }); // ── Looting ────────────────────────────────────────────────────────────────── private static void LootWorld()