fix(runtime,net): OP1 review fixes — server-seed gate, tick-wired auto-save/logout flush, fellowship mutual exclusion

Closes the two mechanism-lens and blast-lens dual reviews of Campaign OP
slice OP1 (86c0a7e0): docs/research/2026-08-10-op1-review-mechanism.md and
docs/research/2026-08-10-op1-review-blast.md.

MUST-FIX M1 (blast): RuntimeCharacterOptionsState gains a HasServerSeed
latch, set by Replace (the PlayerDescription seed) and cleared by
ResetSession. TryFlush/TryFlushIfAutoSaveDue now refuse before the seed
arrives — closing the window where a bot (or, after this commit, the
timer/logout triggers) could flush client-default option words over a
character's real server-side options before any PlayerDescription ever
landed.

MUST-FIX 1 (mechanism): the 480 s auto-save timer and the pre-logoff
flush are now wired into production, closing TS-71 (retired). Both ride
LiveSessionController's own tick/stop transaction via two new hooks
(ConfigureAutoSaveTick/ConfigurePreLogoffFlush), wired once by
GameRuntime's constructor — a Runtime-internal change requiring zero
host edits, exactly as the review identified. The flush body talks to
WorldSession directly rather than through App's LiveSessionCommandRouter,
which is what keeps this off the S2 lock-order hazard (below). Filed
TS-73 for the two OnChanged side-effect cases (weather/day/combat-
target/fog) TrySetOption still doesn't model — pre-anchored to OP4's
Group B consumer binds.

SHOULD-FIX S2 (blast, prerequisite for MUST-FIX 1): TryFlush/
TryFlushIfAutoSaveDue no longer invoke the flush callback while holding
_dirtyGate — the decision is made and cleared under the lock, but the
callback itself runs outside it, closing the lock-inversion hazard the
natural timer wiring would have hit (Runtime tick's _dirtyGate-then-
_gate vs the router's _gate-then-_dirtyGate).

SHOULD-FIX MF-2 (mechanism): TrySetOption now ports the two
PlayerModule-state-mutating cases of CPlayerModule::OnChanged's local
side-effect switch — turning ON IgnoreFellowshipRequests or
FellowshipAutoAcceptRequests clears the other through a real recursive
TrySetOption call, reproducing retail's second 0x0005 (the clear's send
reaches the wire before the primary option's own send, matching the
nested-call order in the decomp). The signature widened from
Action sendAutoSave to Action<uint,bool> so the recursion can send a
different (id, value) than the caller's own; every production call site
now passes WorldSession.SendSetSingleCharacterOption directly.

SHOULD-FIX MF-3 (mechanism): a hand-transcribed 53-row (id, isOptions1,
mask) theory in CharacterOptionTableTests, independently re-derived from
acclient.h's PlayerOption/CharacterOption/CharacterOptions2 enums rather
than copied from CharacterOptionTable.cs — closes the one column with no
id-by-id pin. Also added the pairwise-distinctness check blast NOTE N7
named.

SHOULD-FIX S1 (blast): LiveSessionCommandRouterTests' CH3/CH4 regression
test now drives the REAL TrySetOption binding instead of a hand-rolled
SetOptionBit substitute that had silently drifted from production after
OP1.

SHOULD-FIX S3 (blast): RuntimeCharacterOwnershipSnapshot gains
OptionsAreClean (!Options.IsDirty), included in IsConverged — a module
whose two words happen to cycle back to their default bit pattern while
still dirty is now caught by the combined ownership ledger, not just by
OptionsAreDefaults.

SHOULD-FIX S4 (blast): SaveOptions no longer encodes "did it actually
flush" as PrimaryObjectId 1u/0u (which read as object guid 0x00000001 in
the K2 event stream). Both host adapters now report the identical shape
(Accepted, objectId 0) — the graphical host never could report this
anyway (LiveCommandBus.Publish has no return channel).

SHOULD-FIX S5 (blast): Replace (the server-seed arrival) now also clears
IsDirty/FirstDirtiedAt — a wholesale re-seed supersedes any pending
batched-but-unflushed local intent (retail's own PlayerModule has no
partial-merge path either), documented at the member.

SHOULD-FIX S6 (blast): a cross-check theory asserting CharacterOptionTable's
masks equal PlayerDescriptionParser.CharacterOptions1/2's independently
(the write path vs the read path TurbineChatMembershipGate/
RuntimeSettingsController consume) — guards the exact CH3 failure class.

Also fixed a real allocation regression found while landing MUST-FIX 1:
the naive per-tick flush closure would have allocated on EVERY
LiveSessionController.Tick() call regardless of dirty state, which broke
the K4 headless 30-session resource-envelope gate. GameRuntime.
FlushCharacterOptions now pre-checks Options.IsDirty (itself retail-
faithful — CPlayerModule::UseTime opens with the identical m_bDirty byte
compare) before allocating the flush closure, so the allocation only
happens on the rare tick that might actually flush.

Dispositions on findings not changed this round:
- Mechanism NOTE 6 / not independently re-flagged: a re-entrant MarkDirty
  from inside a flush callback can still be erased by the trailing
  "_isDirty = false" — pre-existing, unchanged by the S2 lock restructure
  (same outcome whether the callback runs inside or outside the lock),
  not reachable from any current caller, not a one-liner to close
  correctly (needs a per-dirty-period generation token). Left as documented
  in the review; worth closing before the Options panel ever flushes from
  inside a change handler.
- Mechanism NOTE 9, blast N2/N3/N4/N5/N6/N8: informational or require
  touching files this round doesn't otherwise edit (SocialActions.cs,
  CharacterOptionsBlobSource.cs, GameRuntimeContractTests.cs) — left per
  the "one-liner in a file already being edited" instruction.

Register: TS-71 retired (both remaining SetCharacterOptions flush
triggers now production-wired); TS-73 filed (the two unmodeled OnChanged
presentation-binding cases, pre-anchored to OP4).

Quality bar: Release build green; full solution suite 12,853 passed / 4
skipped / 0 failed (baseline 12,770/4/0 post-OP2 — 83 new tests added,
zero regressions).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
Erik 2026-08-11 00:39:51 +02:00
parent 26b119354d
commit 09029f9f4b
12 changed files with 1043 additions and 51 deletions

View file

@ -487,16 +487,22 @@ public sealed class LiveSessionCommandRouterTests
societyEldrytchWebRoom: 0u,
societyRadiantBloodRoom: 0u);
var sent = new List<(uint OptionId, bool Value)>();
// Mirrors LiveSessionRuntimeFactory.CreateCommandBindings' shared
// SendSingleCharacterOption local function: local write FIRST, then
// the wire send.
// S1 (Campaign OP OP1 review fix, blast lens, 2026-08-11): drives the
// REAL production binding — RuntimeCharacterOptionsState.
// TrySetOption, the SAME shared local-write-then-send/dirty seam
// LiveSessionRuntimeFactory.CreateCommandBindings' SendSingleCharacterOption
// local function calls — instead of a hand-rolled substitute that had
// silently drifted from it after OP1 (the previous shape called
// SetOptionBit directly, which does not run TrySetOption's
// unchanged-value early return or its MF-2 fellowship
// mutual-exclusion side effect).
LiveSessionCommandRouter router = NewRouter(
characterState: characterState,
sendSingleCharacterOption: (id, value) =>
{
characterState.Options.SetOptionBit(id, value);
sent.Add((id, value));
});
characterState.Options.TrySetOption(
id,
value,
sendAutoSave: (sentId, sentValue) => sent.Add((sentId, sentValue))));
router.Activate();
Assert.Equal(

View file

@ -185,4 +185,114 @@ public sealed class CharacterOptionTableTests
for (uint id = 0x00; id <= 0x34; id++)
yield return [(CharacterOptionId)id];
}
// ── SHOULD-FIX MF-3 (Campaign OP OP1 review fix, mechanism lens,
// 2026-08-11): a hand-transcribed 53-row (word, mask) pin, the SAME
// shape as AutoSaveIds/ClientDefaultOnIds above — a transposition among
// the 37 non-ClientDefault masks (e.g. swapping DisplayAge's O2 0x20
// with DisplayNumberDeaths' O2 0x10) would previously pass the entire
// suite silently; this is the id-by-id guard against exactly that.
// Transcribed independently from named-retail/acclient.h:4162-4218
// (`enum PlayerOption`, the id space) cross-referenced by NAME against
// :3404-3436 (`enum CharacterOption`, Options1) and :3451-3481
// (`enum CharacterOptions2`) — not derived from CharacterOptionTable.cs.
[Theory]
[InlineData(CharacterOptionId.AutoRepeatAttack, true, 0x00000002u)]
[InlineData(CharacterOptionId.IgnoreAllegianceRequests, true, 0x00000004u)]
[InlineData(CharacterOptionId.IgnoreFellowshipRequests, true, 0x00000008u)]
[InlineData(CharacterOptionId.IgnoreTradeRequests, true, 0x00020000u)]
[InlineData(CharacterOptionId.DisableMostWeatherEffects, true, 0x00010000u)]
[InlineData(CharacterOptionId.PersistentAtDay, false, 0x00000001u)]
[InlineData(CharacterOptionId.AllowGive, true, 0x00000040u)]
[InlineData(CharacterOptionId.ViewCombatTarget, true, 0x00000080u)]
[InlineData(CharacterOptionId.ShowTooltips, true, 0x00000100u)]
[InlineData(CharacterOptionId.UseDeception, true, 0x00000200u)]
[InlineData(CharacterOptionId.ToggleRun, true, 0x00000400u)]
[InlineData(CharacterOptionId.StayInChatMode, true, 0x00000800u)]
[InlineData(CharacterOptionId.AdvancedCombatUI, true, 0x00001000u)]
[InlineData(CharacterOptionId.AutoTarget, true, 0x00002000u)]
[InlineData(CharacterOptionId.VividTargetingIndicator, true, 0x00008000u)]
[InlineData(CharacterOptionId.FellowshipShareXP, true, 0x00040000u)]
[InlineData(CharacterOptionId.AcceptLootPermits, true, 0x00080000u)]
[InlineData(CharacterOptionId.FellowshipShareLoot, true, 0x00100000u)]
[InlineData(CharacterOptionId.FellowshipAutoAcceptRequests, true, 0x20000000u)]
[InlineData(CharacterOptionId.SideBySideVitals, true, 0x00200000u)]
[InlineData(CharacterOptionId.CoordinatesOnRadar, true, 0x00400000u)]
[InlineData(CharacterOptionId.SpellDuration, true, 0x00800000u)]
[InlineData(CharacterOptionId.DisableHouseRestrictionEffects, true, 0x02000000u)]
[InlineData(CharacterOptionId.DragItemOnPlayerOpensSecureTrade, true, 0x04000000u)]
[InlineData(CharacterOptionId.DisplayAllegianceLogonNotifications, true, 0x08000000u)]
[InlineData(CharacterOptionId.UseChargeAttack, true, 0x10000000u)]
[InlineData(CharacterOptionId.UseCraftSuccessDialog, true, 0x80000000u)]
[InlineData(CharacterOptionId.ListenToAllegianceChat, true, 0x40000000u)]
[InlineData(CharacterOptionId.DisplayDateOfBirth, false, 0x00000002u)]
[InlineData(CharacterOptionId.DisplayAge, false, 0x00000020u)]
[InlineData(CharacterOptionId.DisplayChessRank, false, 0x00000004u)]
[InlineData(CharacterOptionId.DisplayFishingSkill, false, 0x00000008u)]
[InlineData(CharacterOptionId.DisplayNumberDeaths, false, 0x00000010u)]
[InlineData(CharacterOptionId.DisplayTimeStamps, false, 0x00000040u)]
[InlineData(CharacterOptionId.SalvageMultiple, false, 0x00000080u)]
[InlineData(CharacterOptionId.ListenToGeneralChat, false, 0x00000100u)]
[InlineData(CharacterOptionId.ListenToTradeChat, false, 0x00000200u)]
[InlineData(CharacterOptionId.ListenToLFGChat, false, 0x00000400u)]
[InlineData(CharacterOptionId.ListenToRoleplayChat, false, 0x00000800u)]
[InlineData(CharacterOptionId.AppearOffline, false, 0x00001000u)]
[InlineData(CharacterOptionId.DisplayNumberCharacterTitles, false, 0x00002000u)]
[InlineData(CharacterOptionId.MainPackPreferred, false, 0x00004000u)]
[InlineData(CharacterOptionId.LeadMissileTargets, false, 0x00008000u)]
[InlineData(CharacterOptionId.UseFastMissiles, false, 0x00010000u)]
[InlineData(CharacterOptionId.FilterLanguage, false, 0x00020000u)]
[InlineData(CharacterOptionId.ConfirmVolatileRareUse, false, 0x00040000u)]
[InlineData(CharacterOptionId.ListenToSocietyChat, false, 0x00080000u)]
[InlineData(CharacterOptionId.ShowHelm, false, 0x00100000u)]
[InlineData(CharacterOptionId.DisableDistanceFog, false, 0x00200000u)]
[InlineData(CharacterOptionId.UseMouseTurning, false, 0x00400000u)]
[InlineData(CharacterOptionId.ShowCloak, false, 0x00800000u)]
[InlineData(CharacterOptionId.LockUI, false, 0x01000000u)]
// D3 / register row: ACE-sourced (ListenToPKDeathMessages), unverifiable
// against the 2013 binary — see the type doc on CharacterOptionTable.
[InlineData(CharacterOptionId.HearPkDeathMessages, false, 0x02000000u)]
public void WordAndMask_MatchesIndependentTranscriptionOfVerbatimAcclientEnums(
CharacterOptionId id, bool expectedIsOptions1, uint expectedMask)
{
Assert.True(CharacterOptionTable.TryGet(id, out CharacterOptionTableEntry entry));
Assert.Equal(expectedIsOptions1, entry.IsOptions1);
Assert.Equal(expectedMask, entry.Mask);
}
[Fact]
public void WordAndMask_AreAllPairwiseDistinct()
{
// N7 (blast lens): the reconstruction test above cannot catch a
// duplicate because OR is idempotent — this is the direct guard.
var pairs = CharacterOptionTable.All
.Select(static e => (e.IsOptions1, e.Mask))
.ToList();
Assert.Equal(53, pairs.Distinct().Count());
}
// ── S6 (Campaign OP OP1 review fix, blast lens, 2026-08-11): the write
// path (this table) and the read path (PlayerDescriptionParser.
// CharacterOptions1/2, consumed by TurbineChatMembershipGate and
// RuntimeSettingsController) define the SAME retail bits independently,
// in different projects, with nothing else asserting they agree — an
// edit to one without the other silently diverges the write path from
// the membership gate (the exact CH3 failure class). Covers every
// non-None/Default member of both parser enums.
[Theory]
[InlineData(CharacterOptionId.AllowGive, true, (uint)PlayerDescriptionParser.CharacterOptions1.AllowGive)]
[InlineData(CharacterOptionId.ListenToAllegianceChat, true, (uint)PlayerDescriptionParser.CharacterOptions1.HearAllegianceChat)]
[InlineData(CharacterOptionId.DragItemOnPlayerOpensSecureTrade, true, (uint)PlayerDescriptionParser.CharacterOptions1.DragItemOnPlayerOpensSecureTrade)]
[InlineData(CharacterOptionId.ListenToGeneralChat, false, (uint)PlayerDescriptionParser.CharacterOptions2.HearGeneralChat)]
[InlineData(CharacterOptionId.ListenToTradeChat, false, (uint)PlayerDescriptionParser.CharacterOptions2.HearTradeChat)]
[InlineData(CharacterOptionId.ListenToLFGChat, false, (uint)PlayerDescriptionParser.CharacterOptions2.HearLFGChat)]
[InlineData(CharacterOptionId.ListenToRoleplayChat, false, (uint)PlayerDescriptionParser.CharacterOptions2.HearRoleplayChat)]
[InlineData(CharacterOptionId.ListenToSocietyChat, false, (uint)PlayerDescriptionParser.CharacterOptions2.HearSocietyChat)]
public void CharacterOptionTable_AgreesWithPlayerDescriptionParserEnums(
CharacterOptionId id, bool expectedIsOptions1, uint expectedMask)
{
Assert.True(CharacterOptionTable.TryGet(id, out CharacterOptionTableEntry entry));
Assert.Equal(expectedIsOptions1, entry.IsOptions1);
Assert.Equal(expectedMask, entry.Mask);
}
}

View file

@ -299,8 +299,7 @@ public sealed class RuntimeCharacterStateTests
bool accepted = options.TrySetOption(
(uint)CharacterOptionId.ListenToGeneralChat,
true,
sendAutoSave: () => sent.Add(
((uint)CharacterOptionId.ListenToGeneralChat, true)));
sendAutoSave: (id, value) => sent.Add((id, value)));
Assert.True(accepted);
Assert.Equal(
@ -323,7 +322,7 @@ public sealed class RuntimeCharacterStateTests
bool accepted = options.TrySetOption(
(uint)CharacterOptionId.AutoTarget,
false,
sendAutoSave: () => sent.Add(((uint)CharacterOptionId.AutoTarget, false)));
sendAutoSave: (id, value) => sent.Add((id, value)));
Assert.True(accepted);
// AutoTarget_CharacterOption = 0x2000 (acclient.h:3417).
@ -343,7 +342,7 @@ public sealed class RuntimeCharacterStateTests
bool accepted = options.TrySetOption(
(uint)CharacterOptionId.AutoTarget,
true,
sendAutoSave: () => sent.Add(((uint)CharacterOptionId.AutoTarget, true)));
sendAutoSave: (id, value) => sent.Add((id, value)));
Assert.True(accepted);
Assert.Empty(sent);
@ -356,13 +355,118 @@ public sealed class RuntimeCharacterStateTests
var options = new RuntimeCharacterOptionsState();
bool invoked = false;
bool accepted = options.TrySetOption(0x35u, true, () => invoked = true);
bool accepted = options.TrySetOption(0x35u, true, (_, _) => invoked = true);
Assert.False(accepted);
Assert.False(invoked);
Assert.False(options.IsDirty);
}
// ── MF-2 (Campaign OP OP1 review fix, 2026-08-11): CPlayerModule::
// OnChanged @0x0059A8E0's fellowship mutual-exclusion side effect ──────
[Fact]
public void TrySetOption_TurningOnIgnoreFellowshipRequests_ClearsAutoAccept_ClearSendsBeforePrimary()
{
var options = new RuntimeCharacterOptionsState();
// Arm AutoAcceptFellowshipRequests ON first so there is something
// for the recursive clear to actually clear.
options.TrySetOption(
(uint)CharacterOptionId.FellowshipAutoAcceptRequests, true, (_, _) => { });
var sent = new List<(uint OptionId, bool Value)>();
bool accepted = options.TrySetOption(
(uint)CharacterOptionId.IgnoreFellowshipRequests,
true,
sendAutoSave: (id, value) => sent.Add((id, value)));
Assert.True(accepted);
// Retail's OnChanged runs the recursive clear (a REAL nested
// accessor call, complete with its own immediate 0x0005) BEFORE
// returning to finish the outer call's own IsAutoSaveOption branch
// — so the clear reaches the wire FIRST.
Assert.Equal(
[
((uint)CharacterOptionId.FellowshipAutoAcceptRequests, false),
((uint)CharacterOptionId.IgnoreFellowshipRequests, true),
],
sent);
Assert.NotEqual(0u, options.Options1 & 0x00000008u); // IgnoreFellowshipRequests set
Assert.Equal(0u, options.Options1 & 0x20000000u); // AutoAccept cleared
}
[Fact]
public void TrySetOption_TurningOnAutoAcceptFellowship_ClearsIgnoreRequests_ClearSendsBeforePrimary()
{
var options = new RuntimeCharacterOptionsState();
options.TrySetOption(
(uint)CharacterOptionId.IgnoreFellowshipRequests, true, (_, _) => { });
var sent = new List<(uint OptionId, bool Value)>();
bool accepted = options.TrySetOption(
(uint)CharacterOptionId.FellowshipAutoAcceptRequests,
true,
sendAutoSave: (id, value) => sent.Add((id, value)));
Assert.True(accepted);
Assert.Equal(
[
((uint)CharacterOptionId.IgnoreFellowshipRequests, false),
((uint)CharacterOptionId.FellowshipAutoAcceptRequests, true),
],
sent);
Assert.NotEqual(0u, options.Options1 & 0x20000000u); // AutoAccept set
Assert.Equal(0u, options.Options1 & 0x00000008u); // IgnoreFellowshipRequests cleared
}
[Fact]
public void TrySetOption_TurningOnFellowshipOption_WhenTheOtherIsAlreadyOff_SendsOnlyThePrimary()
{
var options = new RuntimeCharacterOptionsState();
// IgnoreFellowshipRequests defaults ON (ClientDefault=true) — flip
// it off first so the "turn on" below is a REAL transition.
options.TrySetOption(
(uint)CharacterOptionId.IgnoreFellowshipRequests, false, (_, _) => { });
var sent = new List<(uint OptionId, bool Value)>();
// FellowshipAutoAcceptRequests already off — the recursive clear's
// own TrySetOption call must early-return silently (retail's
// accessor's own unchanged-value early return), producing exactly
// ONE wire send, not two.
bool accepted = options.TrySetOption(
(uint)CharacterOptionId.IgnoreFellowshipRequests,
true,
sendAutoSave: (id, value) => sent.Add((id, value)));
Assert.True(accepted);
Assert.Equal([((uint)CharacterOptionId.IgnoreFellowshipRequests, true)], sent);
}
[Fact]
public void TrySetOption_TurningOffAFellowshipOption_NeverTriggersTheClear()
{
var options = new RuntimeCharacterOptionsState();
// Force BOTH bits on directly — SetOptionBit bypasses OnChanged's
// side-effect switch entirely, so this reaches a state retail's OWN
// accessors (and TrySetOption) can never produce, but one a fresh
// PlayerDescription CAN carry (ACE performs no validation/clamping
// on these bits, wire research §5.1).
options.SetOptionBit((uint)CharacterOptionId.IgnoreFellowshipRequests, true);
options.SetOptionBit((uint)CharacterOptionId.FellowshipAutoAcceptRequests, true);
var sent = new List<(uint OptionId, bool Value)>();
// Retail's case 2/0x12 only fire "if now true" — turning ONE off
// must not touch the other.
bool accepted = options.TrySetOption(
(uint)CharacterOptionId.IgnoreFellowshipRequests,
false,
sendAutoSave: (id, value) => sent.Add((id, value)));
Assert.True(accepted);
Assert.Equal([((uint)CharacterOptionId.IgnoreFellowshipRequests, false)], sent);
Assert.NotEqual(0u, options.Options1 & 0x20000000u); // AutoAccept untouched (still on)
}
[Fact]
public void MarkDirty_OnlySecondCallDoesNotPushOutFirstDirtiedAt()
{
@ -370,17 +474,174 @@ public sealed class RuntimeCharacterStateTests
var options = new RuntimeCharacterOptionsState(clock);
options.TrySetOption(
(uint)CharacterOptionId.AutoTarget, false, () => { });
(uint)CharacterOptionId.AutoTarget, false, (_, _) => { });
DateTimeOffset? firstStamp = options.FirstDirtiedAt;
Assert.NotNull(firstStamp);
clock.Advance(TimeSpan.FromSeconds(10));
options.TrySetOption(
(uint)CharacterOptionId.ShowTooltips, false, () => { });
(uint)CharacterOptionId.ShowTooltips, false, (_, _) => { });
Assert.Equal(firstStamp, options.FirstDirtiedAt);
}
// ── MUST-FIX M1 (Campaign OP OP1 review fix, 2026-08-11): the server-
// seed latch guarding TryFlush/TryFlushIfAutoSaveDue ───────────────────
[Fact]
public void TryFlush_RefusesBeforeServerSeed_EvenWhenDirty_ThenSucceedsAfterSeed()
{
var options = new RuntimeCharacterOptionsState();
Assert.False(options.HasServerSeed);
options.TrySetOption(
(uint)CharacterOptionId.AutoTarget, false, (_, _) => { });
Assert.True(options.IsDirty);
int flushes = 0;
Assert.False(options.TryFlush(() => flushes++));
Assert.Equal(0, flushes);
// Nothing lost, nothing sent — the pending change is still pending.
Assert.True(options.IsDirty);
// A real PlayerDescription lands. S5: the seed supersedes the
// pending change (retail's own PlayerModule is likewise clobbered by
// a wholesale re-seed), so re-dirty AFTER the seed to prove the
// GATE (not the module) was what refused above.
options.Replace(options.Options1, options.Options2);
Assert.True(options.HasServerSeed);
Assert.False(options.IsDirty);
options.TrySetOption(
(uint)CharacterOptionId.AutoTarget, true, (_, _) => { });
Assert.True(options.TryFlush(() => flushes++));
Assert.Equal(1, flushes);
}
[Fact]
public void TryFlushIfAutoSaveDue_RefusesBeforeServerSeed_EvenAtThreshold()
{
var clock = new ManualTimeProvider();
var options = new RuntimeCharacterOptionsState(clock);
options.TrySetOption(
(uint)CharacterOptionId.AutoTarget, false, (_, _) => { });
clock.Advance(RuntimeCharacterOptionsState.AutoSaveDelay + TimeSpan.FromSeconds(1));
int flushes = 0;
Assert.False(options.TryFlushIfAutoSaveDue(() => flushes++));
Assert.Equal(0, flushes);
Assert.True(options.IsDirty);
}
[Fact]
public void ReconnectSequence_ResetSessionClearsSeed_NewReplaceUnblocksFlushAgain()
{
var options = new RuntimeCharacterOptionsState();
options.Replace(options.Options1, options.Options2); // first session's seed
options.TrySetOption(
(uint)CharacterOptionId.AutoTarget, false, (_, _) => { });
int flushes = 0;
Assert.True(options.TryFlush(() => flushes++));
Assert.Equal(1, flushes);
// Simulated reconnect: the generation-reset transaction clears the
// seed along with everything else.
options.ResetSession();
Assert.False(options.HasServerSeed);
// Anything that dirties the module BEFORE the new session's
// PlayerDescription arrives must not be flushable yet.
options.TrySetOption(
(uint)CharacterOptionId.AutoTarget, false, (_, _) => { });
Assert.True(options.IsDirty);
Assert.False(options.TryFlush(() => flushes++));
Assert.Equal(1, flushes);
Assert.True(options.IsDirty);
// The new session's PlayerDescription lands — S5 supersedes the
// stale pending change; a FRESH change after the reseed flushes.
options.Replace(options.Options1, options.Options2);
Assert.True(options.HasServerSeed);
Assert.False(options.IsDirty);
options.TrySetOption(
(uint)CharacterOptionId.ShowTooltips, false, (_, _) => { });
Assert.True(options.TryFlush(() => flushes++));
Assert.Equal(2, flushes);
}
// ── S5 (Campaign OP OP1 review fix, blast lens, 2026-08-11) ────────────
[Fact]
public void Replace_ClearsDirtyState_ServerTruthSupersedesPendingLocalIntent()
{
var options = new RuntimeCharacterOptionsState();
options.TrySetOption(
(uint)CharacterOptionId.AutoTarget, false, (_, _) => { });
Assert.True(options.IsDirty);
Assert.NotNull(options.FirstDirtiedAt);
options.Replace(0x11111111u, 0x22222222u);
Assert.False(options.IsDirty);
Assert.Null(options.FirstDirtiedAt);
Assert.Equal(0x11111111u, options.Options1);
Assert.Equal(0x22222222u, options.Options2);
}
// ── S2 (Campaign OP OP1 review fix, blast lens, 2026-08-11): the
// decide-and-clear/callback-outside-the-lock split ─────────────────────
[Fact]
public async Task TryFlush_ReleasesTheDirtyGate_DuringTheCallback_SoAConcurrentMarkDirtyDoesNotBlock()
{
var options = new RuntimeCharacterOptionsState();
options.Replace(options.Options1, options.Options2);
options.TrySetOption(
(uint)CharacterOptionId.AutoTarget, false, (_, _) => { });
using var callbackEntered = new ManualResetEventSlim(false);
using var releaseCallback = new ManualResetEventSlim(false);
Task<bool> flushTask = Task.Run(() =>
options.TryFlush(() =>
{
callbackEntered.Set();
releaseCallback.Wait(TimeSpan.FromSeconds(10));
}));
Assert.True(callbackEntered.Wait(TimeSpan.FromSeconds(5)));
// While the callback above is still blocked and holds NO lock (per
// the fix), a concurrent MarkDirty from another thread must
// complete promptly. Under the pre-fix shape (callback invoked
// INSIDE _dirtyGate) this would block until releaseCallback fires.
Task probe = Task.Run(options.MarkDirty);
Task probeCompletion = await Task.WhenAny(probe, Task.Delay(TimeSpan.FromSeconds(2)));
bool probeCompletedPromptly = ReferenceEquals(probeCompletion, probe);
releaseCallback.Set();
bool flushed = await flushTask.WaitAsync(TimeSpan.FromSeconds(5));
Assert.True(flushed);
Assert.True(probeCompletedPromptly);
}
[Fact]
public void TryFlush_PreservesDirtyState_WhenTheCallbackThrows()
{
var options = new RuntimeCharacterOptionsState();
options.Replace(options.Options1, options.Options2);
options.TrySetOption(
(uint)CharacterOptionId.AutoTarget, false, (_, _) => { });
Assert.True(options.IsDirty);
Assert.Throws<InvalidOperationException>(() =>
options.TryFlush(() => throw new InvalidOperationException("network down")));
Assert.True(options.IsDirty);
}
[Fact]
public void TryFlush_NoOpWhenClean_FlushesAndClearsWhenDirty()
{
@ -389,8 +650,9 @@ public sealed class RuntimeCharacterStateTests
Assert.False(options.TryFlush(() => cleanFlushes++));
Assert.Equal(0, cleanFlushes);
options.Replace(options.Options1, options.Options2); // seed (M1)
options.TrySetOption(
(uint)CharacterOptionId.AutoTarget, false, () => { });
(uint)CharacterOptionId.AutoTarget, false, (_, _) => { });
Assert.True(options.IsDirty);
int dirtyFlushes = 0;
@ -410,8 +672,9 @@ public sealed class RuntimeCharacterStateTests
{
var clock = new ManualTimeProvider();
var options = new RuntimeCharacterOptionsState(clock);
options.Replace(options.Options1, options.Options2); // seed (M1)
options.TrySetOption(
(uint)CharacterOptionId.AutoTarget, false, () => { });
(uint)CharacterOptionId.AutoTarget, false, (_, _) => { });
int flushes = 0;
clock.Advance(RuntimeCharacterOptionsState.AutoSaveDelay - TimeSpan.FromSeconds(1));
@ -429,7 +692,7 @@ public sealed class RuntimeCharacterStateTests
{
var options = new RuntimeCharacterOptionsState();
options.TrySetOption(
(uint)CharacterOptionId.AutoTarget, false, () => { });
(uint)CharacterOptionId.AutoTarget, false, (_, _) => { });
Assert.True(options.IsDirty);
options.ResetSession();
@ -438,6 +701,63 @@ public sealed class RuntimeCharacterStateTests
Assert.Null(options.FirstDirtiedAt);
}
// ── S3 (Campaign OP OP1 review fix, blast lens, 2026-08-11): the
// combined ownership ledger observes IsDirty ────────────────────────────
[Fact]
public void CaptureOwnership_OptionsAreClean_ReflectsOptionsIsDirty_EvenWhenBitsReturnToDefault()
{
using var state = new RuntimeCharacterState();
Assert.True(state.CaptureOwnership().OptionsAreClean);
// AutoTarget (0x0D) defaults ON. Flip off then back on: the WORDS
// return to their default value, but m_bDirty was set on the first
// (real) transition and never cleared by a flush/reset — exactly
// the gap S3 flags: the pre-existing OptionsAreDefaults check alone
// cannot see this (it would read true here despite a real pending
// save being owed).
state.Options.TrySetOption(
(uint)CharacterOptionId.AutoTarget, false, (_, _) => { });
state.Options.TrySetOption(
(uint)CharacterOptionId.AutoTarget, true, (_, _) => { });
Assert.Equal(RuntimeCharacterOptionsState.DefaultOptions1, state.Options.Options1);
Assert.True(state.Options.IsDirty);
Assert.False(state.CaptureOwnership().OptionsAreClean);
state.ResetSession();
Assert.True(state.CaptureOwnership().OptionsAreClean);
}
[Fact]
public void RuntimeCharacterOwnershipSnapshot_IsConverged_RequiresOptionsAreClean()
{
// Direct record-level pin: IsConverged must fail on OptionsAreClean
// alone, exactly like every other convergence field, even when
// every other field is in its converged shape.
var converged = new RuntimeCharacterOwnershipSnapshot(
IsDisposed: true,
InternalSubscriptionsAttached: false,
LearnedSpellCount: 0,
ActiveEnchantmentCount: 0,
DesiredComponentCount: 0,
FavoriteSpellCount: 0,
VitalCount: 0,
AttributeCount: 0,
SkillCount: 0,
PositionCount: 0,
PropertyCount: 0,
OptionsAreDefaults: true,
MovementSkillsAreReset: true,
AutonomyIsDefault: true,
OptionsAreClean: true);
Assert.True(converged.IsConverged);
RuntimeCharacterOwnershipSnapshot dirty = converged with { OptionsAreClean = false };
Assert.False(dirty.IsConverged);
}
private sealed class ManualTimeProvider : TimeProvider
{
private DateTimeOffset _now = new(2026, 8, 10, 0, 0, 0, TimeSpan.Zero);

View file

@ -350,6 +350,11 @@ public sealed class DirectGameRuntimeCommandAdapterTests
CreateStartedHarness();
var gameActions = new List<byte[]>();
operations.Sessions[^1].GameActionCapture = body => gameActions.Add(body);
// MUST-FIX M1 (OP1 review fix, 2026-08-11): seed the server truth
// (as a real session's PlayerDescription would) before the flush —
// otherwise TryFlush now refuses outright (see
// SaveOptions_RefusesBeforeServerSeed_EvenWhenDirty below).
SeedServerOptions(runtime);
adapter.Character.SetSingleOption(
runtime.Generation, (uint)CharacterOptionId.AutoTarget, false);
@ -365,17 +370,142 @@ public sealed class DirectGameRuntimeCommandAdapterTests
SocialActions.SetCharacterOptionsOpcode,
System.Buffers.Binary.BinaryPrimitives.ReadUInt32LittleEndian(
blob.AsSpan(8)));
// S4 (OP1 review fix, blast lens): PrimaryObjectId no longer encodes
// whether the flush actually fired — both hosts report the SAME
// shape (Accepted, objectId 0).
Assert.Equal(0u, saved.ResultObjectId);
// A clean module's second SaveOptions sends nothing more.
RuntimeCommandResult savedAgain =
adapter.Character.SaveOptions(runtime.Generation);
Assert.True(savedAgain.Accepted);
Assert.Equal(0u, savedAgain.ResultObjectId);
Assert.Single(gameActions);
runtime.Dispose();
}
[Fact]
public void SaveOptions_RefusesBeforeServerSeed_EvenWhenDirty_ThenSucceedsAfterSeed()
{
(GameRuntime runtime, DirectGameRuntimeCommandAdapter adapter, FixtureSessionOperations operations) =
CreateStartedHarness();
var gameActions = new List<byte[]>();
operations.Sessions[^1].GameActionCapture = body => gameActions.Add(body);
// MUST-FIX M1 (OP1 review fix, 2026-08-11): CreateStartedHarness's
// RuntimeCharacterOptionsState starts at CLIENT constructor defaults
// — no PlayerDescription has landed yet (HasServerSeed is false). A
// blob flush here would ship acdream's defaults over the
// character's real server-side options — the wipe class M1 closes.
adapter.Character.SetSingleOption(
runtime.Generation, (uint)CharacterOptionId.AutoTarget, false);
Assert.True(runtime.CharacterOwner.Options.IsDirty);
RuntimeCommandResult saved = adapter.Character.SaveOptions(runtime.Generation);
Assert.True(saved.Accepted);
Assert.Empty(gameActions);
// Nothing lost, nothing sent — the pending change is still pending.
Assert.True(runtime.CharacterOwner.Options.IsDirty);
// The server's real PlayerDescription lands. S5: the seed
// supersedes the (unsent) pending change, so dirty a FRESH change
// after the seed to prove the GATE — not the module — was what
// refused above.
SeedServerOptions(runtime);
Assert.False(runtime.CharacterOwner.Options.IsDirty);
adapter.Character.SetSingleOption(
runtime.Generation, (uint)CharacterOptionId.ShowTooltips, false);
RuntimeCommandResult savedAfterSeed =
adapter.Character.SaveOptions(runtime.Generation);
Assert.True(savedAfterSeed.Accepted);
Assert.Single(gameActions);
Assert.False(runtime.CharacterOwner.Options.IsDirty);
runtime.Dispose();
}
// ── MUST-FIX 1 (Campaign OP OP1 review fix, mechanism lens, 2026-08-11):
// end-to-end proof that GameRuntime's real wiring — not just
// LiveSessionController's hook mechanics in isolation
// (LiveSessionControllerTests.cs) — actually auto-flushes the batched
// blob from an ordinary Session.Tick() once the 480 s timer is due.
[Fact]
public void Session_Tick_AutoFlushesTheDirtyBlob_OnceThe480sTimerIsDue()
{
var clock = new ManualTimeProvider();
(GameRuntime runtime, DirectGameRuntimeCommandAdapter adapter, FixtureSessionOperations operations) =
CreateStartedHarness(clock);
var gameActions = new List<byte[]>();
operations.Sessions[^1].GameActionCapture = body => gameActions.Add(body);
SeedServerOptions(runtime);
adapter.Character.SetSingleOption(
runtime.Generation, (uint)CharacterOptionId.AutoTarget, false);
Assert.True(runtime.CharacterOwner.Options.IsDirty);
// Before the timer: an ordinary tick must not flush.
runtime.Session.Tick();
Assert.Empty(gameActions);
Assert.True(runtime.CharacterOwner.Options.IsDirty);
clock.Advance(RuntimeCharacterOptionsState.AutoSaveDelay + TimeSpan.FromSeconds(1));
runtime.Session.Tick();
byte[] blob = Assert.Single(gameActions);
Assert.Equal(
SocialActions.SetCharacterOptionsOpcode,
System.Buffers.Binary.BinaryPrimitives.ReadUInt32LittleEndian(
blob.AsSpan(8)));
Assert.False(runtime.CharacterOwner.Options.IsDirty);
runtime.Dispose();
}
[Fact]
public void Stop_AutoFlushesTheDirtyBlob_BeforeTheCharacterLogoffRequest()
{
(GameRuntime runtime, DirectGameRuntimeCommandAdapter adapter, FixtureSessionOperations operations) =
CreateStartedHarness();
var order = new List<string>();
operations.Sessions[^1].GameActionCapture = body =>
{
uint opcode = System.Buffers.Binary.BinaryPrimitives.ReadUInt32LittleEndian(
body.AsSpan(8));
if (opcode == SocialActions.SetCharacterOptionsOpcode)
order.Add("options-blob");
};
SeedServerOptions(runtime);
adapter.Character.SetSingleOption(
runtime.Generation, (uint)CharacterOptionId.AutoTarget, false);
Assert.True(runtime.CharacterOwner.Options.IsDirty);
RuntimeTeardownAcknowledgement stopped =
adapter.Session.Stop(runtime.Generation);
Assert.True(stopped.IsComplete);
Assert.Equal(["options-blob"], order);
runtime.Dispose();
}
private sealed class ManualTimeProvider : TimeProvider
{
private DateTimeOffset _now = new(2026, 8, 11, 0, 0, 0, TimeSpan.Zero);
public override DateTimeOffset GetUtcNow() => _now;
public void Advance(TimeSpan elapsed) => _now += elapsed;
}
private static void SeedServerOptions(GameRuntime runtime) =>
runtime.CharacterOwner.Options.Replace(
runtime.CharacterOwner.Options.Options1,
runtime.CharacterOwner.Options.Options2);
private static (GameRuntime Runtime, DirectGameRuntimeCommandAdapter Adapter, FixtureSessionOperations Operations)
CreateStartedHarness()
CreateStartedHarness(TimeProvider? timeProvider = null)
{
var operations = new FixtureSessionOperations();
var gameplay = new FixtureGameplayOperations();
@ -384,6 +514,7 @@ public sealed class DirectGameRuntimeCommandAdapterTests
gameplay,
gameplay,
gameplay,
TimeProvider: timeProvider,
SessionOperations: operations));
gameplay.Bind(runtime);
var resetHost = new FixtureResetHost();

View file

@ -897,6 +897,133 @@ public sealed class LiveSessionControllerTests
StringComparison.Ordinal);
}
// ── MUST-FIX 1 (Campaign OP OP1 review fix, mechanism lens,
// 2026-08-11): the TS-71 auto-save-timer and pre-logoff-flush hooks ────
[Fact]
public void Tick_InvokesConfiguredAutoSaveHook_WithTheCurrentSessionWhileInWorld()
{
var calls = new List<string>();
var operations = new TestOperations(calls);
var host = new TestHost(calls);
var controller = new LiveSessionController(operations);
controller.Start(LiveOptions(), host);
WorldSession session = operations.Sessions[0];
WorldSession? seen = null;
controller.ConfigureAutoSaveTick(s => seen = s);
controller.Tick();
Assert.Same(session, seen);
}
[Fact]
public void Tick_DoesNotInvokeAutoSaveHook_WhenNotInWorld()
{
var calls = new List<string>();
var operations = new TestOperations(calls);
var controller = new LiveSessionController(operations);
bool invoked = false;
controller.ConfigureAutoSaveTick(_ => invoked = true);
// Never started — Tick() early-returns before any hook can fire.
controller.Tick();
Assert.False(invoked);
Assert.Equal(0, operations.TickCount);
}
[Fact]
public void Tick_AutoSaveHookThrowing_DoesNotFailTheTickOrTearDownTheSession()
{
var calls = new List<string>();
var operations = new TestOperations(calls);
var host = new TestHost(calls);
var controller = new LiveSessionController(operations);
controller.Start(LiveOptions(), host);
WorldSession session = operations.Sessions[0];
controller.ConfigureAutoSaveTick(
_ => throw new InvalidOperationException("send failed"));
// Must not throw — a transient send error on a background auto-save
// must not tear down the whole live session.
controller.Tick();
Assert.True(controller.IsInWorld);
Assert.Same(session, controller.CurrentSession);
Assert.False(operations.DisposeCounts.ContainsKey(session));
}
[Fact]
public void Stop_InvokesConfiguredPreLogoffFlushHook_BeforeSessionDisposed()
{
var calls = new List<string>();
var operations = new TestOperations(calls);
var host = new TestHost(calls);
var controller = new LiveSessionController(operations);
controller.Start(LiveOptions(), host);
WorldSession session = operations.Sessions[0];
WorldSession? seen = null;
controller.ConfigurePreLogoffFlush(s =>
{
seen = s;
calls.Add("pre-logoff-flush");
});
controller.Stop();
Assert.Same(session, seen);
// Retail's CPlayerSystem::LogOffCharacter calls SaveToServer BEFORE
// the character-logoff wire request — the flush must precede
// WorldSession disposal.
int flushIndex = calls.IndexOf("pre-logoff-flush");
int disposeIndex = calls.IndexOf("dispose-session");
Assert.True(flushIndex >= 0);
Assert.True(disposeIndex >= 0);
Assert.True(flushIndex < disposeIndex);
}
[Fact]
public void Stop_DoesNotInvokePreLogoffFlushHook_WhenNeverEnteredWorld()
{
var calls = new List<string>();
var operations = new TestOperations(calls) { ThrowOnEnterWorld = true };
var host = new TestHost(calls);
var controller = new LiveSessionController(operations);
bool invoked = false;
controller.ConfigurePreLogoffFlush(_ => invoked = true);
// Fails before _inWorld ever becomes true — StartCore's own
// StopAfterFailure -> StopCore() runs, but the hook must not fire;
// matches retail's own call site, which only exists on an actual
// in-world character.
controller.Start(LiveOptions(), host);
Assert.False(invoked);
Assert.False(controller.IsInWorld);
}
[Fact]
public void Stop_PreLogoffFlushHookThrowing_DoesNotBlockGracefulTeardown()
{
var calls = new List<string>();
var operations = new TestOperations(calls);
var host = new TestHost(calls);
var controller = new LiveSessionController(operations);
controller.Start(LiveOptions(), host);
WorldSession session = operations.Sessions[0];
controller.ConfigurePreLogoffFlush(
_ => throw new InvalidOperationException("flush failed"));
// Must not throw — a failed flush must not block the graceful-
// shutdown sequence.
controller.Stop();
Assert.False(controller.IsInWorld);
Assert.Null(controller.CurrentSession);
Assert.Equal(1, operations.DisposeCounts[session]);
}
[Fact]
public void DisposeIsIdempotentAndMakesOldCommandsInert()
{