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

File diff suppressed because one or more lines are too long

View file

@ -348,8 +348,10 @@ internal sealed class LiveSessionRuntimeFactory
_domain.Character.Options.TrySetOption( _domain.Character.Options.TrySetOption(
optionId, optionId,
value, value,
sendAutoSave: () => // MF-2 (OP1 review fix, 2026-08-11): TrySetOption now takes
session.SendSetSingleCharacterOption(optionId, value)); // (id, value) so its fellowship mutual-exclusion recursion
// can send a DIFFERENT id/value than this call's own.
sendAutoSave: session.SendSetSingleCharacterOption);
// OP1: the explicit SaveOptions verb — retail's // OP1: the explicit SaveOptions verb — retail's
// CPlayerModule::SaveToServer(force: 0). No-ops when the batched // CPlayerModule::SaveToServer(force: 0). No-ops when the batched

View file

@ -701,6 +701,11 @@ internal sealed class CurrentGameRuntimeCommandAdapter
if (gate != RuntimeCommandStatus.Accepted) if (gate != RuntimeCommandStatus.Accepted)
return Result(gate); return Result(gate);
_commands.Publish(new SaveCharacterOptionsRuntimeCmd()); _commands.Publish(new SaveCharacterOptionsRuntimeCmd());
// S4 (OP1 review fix, blast lens, 2026-08-11): objectId 0 — the bus
// has no return channel to report whether the deferred flush
// actually fired, so this host reports the SAME shape
// DirectGameRuntimeCommandAdapter.SaveOptions now does (Accepted,
// objectId 0) rather than a host-specific encoding.
return EmitResult( return EmitResult(
RuntimeCommandDomain.Character, RuntimeCommandDomain.Character,
operation: 5, operation: 5,

View file

@ -1,4 +1,5 @@
using System.Numerics; using System.Numerics;
using AcDream.Core.Net;
using AcDream.Runtime.Entities; using AcDream.Runtime.Entities;
using AcDream.Runtime.Gameplay; using AcDream.Runtime.Gameplay;
using AcDream.Runtime.Physics; using AcDream.Runtime.Physics;
@ -323,6 +324,23 @@ public sealed class GameRuntime
TransitOwner = transit; TransitOwner = transit;
GenerationReset = generationReset; GenerationReset = generationReset;
_events = context.Events; _events = context.Events;
// MUST-FIX 1 (Campaign OP OP1 review fix, 2026-08-11): wire
// retail's two remaining CPlayerModule::SaveToServer trigger
// sites — the 480 s auto-save timer (CPlayerModule::UseTime) and
// the pre-logoff flush (CPlayerSystem::LogOffCharacter) — through
// LiveSessionController's own tick/stop transaction, closing
// TS-71. Both share the SAME flush body the explicit SaveOptions
// command already uses (CharacterOptionsBlobSource.Capture +
// WorldSession.SendSetCharacterOptions); this talks to the
// WorldSession directly rather than through App's
// LiveSessionCommandRouter/LiveCommandBus, which is what keeps
// it off the S2 lock-order hazard the blast-lens review named.
context.Session.ConfigureAutoSaveTick(
session => FlushCharacterOptions(session, ifAutoSaveDue: true));
context.Session.ConfigurePreLogoffFlush(
session => FlushCharacterOptions(session, ifAutoSaveDue: false));
construction.Complete(); construction.Complete();
} }
catch (Exception failure) catch (Exception failure)
@ -332,6 +350,59 @@ public sealed class GameRuntime
} }
} }
/// <summary>
/// The one flush body shared by every trigger that can send the batched
/// <c>SetCharacterOptions (0x01A1)</c> blob: the explicit
/// <c>SaveOptions</c> command (both <c>IRuntimeCharacterCommands</c>
/// adapters), the 480 s auto-save timer, and the pre-logoff flush (the
/// latter two wired via <see cref="LiveSessionController.
/// ConfigureAutoSaveTick"/>/<see cref="LiveSessionController.
/// ConfigurePreLogoffFlush"/> in the constructor above). Reads
/// <see cref="CharacterOwner"/>/<see cref="InventoryOwner"/> at
/// invocation time, not construction time, so this is safe to bind
/// before either property's backing value is technically "public" —
/// both are always populated long before the session can ever tick or
/// stop.
/// <para>
/// The <see cref="RuntimeCharacterOptionsState.IsDirty"/> pre-check
/// below is retail-faithful (<c>CPlayerModule::UseTime @0x0059A710</c>
/// opens with the identical <c>m_bDirty</c> byte compare before it ever
/// touches the FPU timer math) AND load-bearing for allocation: without
/// it, the auto-save-tick hook would allocate a fresh flush closure on
/// EVERY <see cref="LiveSessionController.Tick"/> call — every frame,
/// for every live session, whether or not anything is actually
/// dirty — which is exactly the per-tick allocation the K4 headless
/// resource-envelope gate measures. Gating on the cheap flag first means
/// the closure below is only ever allocated on the rare tick where a
/// flush might really happen.
/// </para>
/// </summary>
private void FlushCharacterOptions(WorldSession session, bool ifAutoSaveDue)
{
RuntimeCharacterOptionsState options = CharacterOwner.Options;
if (!options.IsDirty)
return;
void SendBlob()
{
CharacterOptionsBlobEcho echo = CharacterOptionsBlobSource.Capture(
CharacterOwner,
InventoryOwner.Shortcuts);
session.SendSetCharacterOptions(
echo.Options1,
echo.Options2,
echo.Shortcuts,
echo.FavoriteSpells,
echo.DesiredComponents,
echo.SpellbookFilters);
}
if (ifAutoSaveDue)
options.TryFlushIfAutoSaveDue(SendBlob);
else
options.TryFlush(SendBlob);
}
public GameRuntimeClock Clock { get; } public GameRuntimeClock Clock { get; }
public LiveSessionController Session { get; } public LiveSessionController Session { get; }
public RuntimeLocalPlayerIdentityState PlayerIdentity { get; } public RuntimeLocalPlayerIdentityState PlayerIdentity { get; }

View file

@ -21,7 +21,16 @@ public readonly record struct RuntimeCharacterOwnershipSnapshot(
bool OptionsAreDefaults, bool OptionsAreDefaults,
bool MovementSkillsAreReset, bool MovementSkillsAreReset,
/// <summary>C0-2: <see cref="RuntimeCharacterState.AutonomyLevel"/> is back at retail's default (<see cref="RuntimeCharacterState.FullAutonomyLevel"/>).</summary> /// <summary>C0-2: <see cref="RuntimeCharacterState.AutonomyLevel"/> is back at retail's default (<see cref="RuntimeCharacterState.FullAutonomyLevel"/>).</summary>
bool AutonomyIsDefault = true) bool AutonomyIsDefault = true,
/// <summary>
/// S3 (Campaign OP OP1 review fix, 2026-08-11): <c>!Options.IsDirty</c>.
/// <see cref="OptionsAreDefaults"/> alone cannot catch a module whose
/// two words happen to have cycled back to their default bit pattern
/// (e.g. an option flipped off then back on) while <c>m_bDirty</c> is
/// still set — the ledger exists precisely to catch state a reset must
/// clear but a value-only comparison would miss.
/// </summary>
bool OptionsAreClean = true)
{ {
public bool IsConverged => public bool IsConverged =>
IsDisposed IsDisposed
@ -37,7 +46,8 @@ public readonly record struct RuntimeCharacterOwnershipSnapshot(
&& PropertyCount == 0 && PropertyCount == 0
&& OptionsAreDefaults && OptionsAreDefaults
&& MovementSkillsAreReset && MovementSkillsAreReset
&& AutonomyIsDefault; && AutonomyIsDefault
&& OptionsAreClean;
} }
/// <summary> /// <summary>
@ -221,7 +231,8 @@ public sealed class RuntimeCharacterState : IDisposable
&& _runSkillBase == -1 && _runSkillBase == -1
&& _jumpSkillBase == -1 && _jumpSkillBase == -1
&& _movementSkillAugmentations == default, && _movementSkillAugmentations == default,
AutonomyLevel == FullAutonomyLevel); AutonomyLevel == FullAutonomyLevel,
OptionsAreClean: !Options.IsDirty);
} }
/// <summary> /// <summary>
@ -651,6 +662,7 @@ public sealed class RuntimeCharacterOptionsState
private long _revision; private long _revision;
private bool _isDirty; private bool _isDirty;
private DateTimeOffset _firstDirtiedAt; private DateTimeOffset _firstDirtiedAt;
private bool _hasServerSeed;
public RuntimeCharacterOptionsState(TimeProvider? timeProvider = null) public RuntimeCharacterOptionsState(TimeProvider? timeProvider = null)
{ {
@ -678,14 +690,49 @@ public sealed class RuntimeCharacterOptionsState
get { lock (_dirtyGate) return _isDirty ? _firstDirtiedAt : null; } get { lock (_dirtyGate) return _isDirty ? _firstDirtiedAt : null; }
} }
/// <summary>
/// MUST-FIX M1 (Campaign OP OP1 review fix, 2026-08-11): has a real
/// <c>PlayerDescription</c> ever landed via <see cref="Replace"/> since
/// construction / the last <see cref="ResetSession"/>? Starts
/// <c>false</c> — this module's two words start at the CLIENT
/// constructor defaults (<see cref="DefaultOptions1"/>/
/// <see cref="DefaultOptions2"/>), not the character's server-side
/// options, so flushing the batched <c>0x01A1</c> blob before the seed
/// arrives would ship client defaults over whatever ACE actually has
/// stored — the wipe class this gate exists to close. See
/// <see cref="TryFlush"/>/<see cref="TryFlushIfAutoSaveDue"/>.
/// </summary>
public bool HasServerSeed
{
get { lock (_dirtyGate) return _hasServerSeed; }
}
public bool DragItemOnPlayerOpensSecureTrade => public bool DragItemOnPlayerOpensSecureTrade =>
Snapshot.DragItemOnPlayerOpensSecureTrade; Snapshot.DragItemOnPlayerOpensSecureTrade;
/// <summary>
/// Installs a fresh <c>PlayerDescription</c>'s two option words as
/// server truth and arms <see cref="HasServerSeed"/> (MUST-FIX M1).
/// S5 (OP1 review fix, blast lens): also clears <see cref="IsDirty"/>/
/// <see cref="FirstDirtiedAt"/> — a re-seed WHOLESALE overwrites both
/// words with no partial-merge path (retail's own
/// <c>PlayerModule::UnPack</c> has none either), so any batched-but-
/// unflushed local intent is superseded the instant this runs: the
/// server's own values are now current, and a later flush would only
/// echo them back. Continuing to report the module dirty after a
/// wholesale overwrite would let a stale pending-save appear to persist
/// a change that no longer exists locally.
/// </summary>
public void Replace(uint options1, uint options2) public void Replace(uint options1, uint options2)
{ {
Volatile.Write(ref _options1, options1); Volatile.Write(ref _options1, options1);
Volatile.Write(ref _options2, options2); Volatile.Write(ref _options2, options2);
Interlocked.Increment(ref _revision); Interlocked.Increment(ref _revision);
lock (_dirtyGate)
{
_isDirty = false;
_hasServerSeed = true;
}
} }
/// <summary> /// <summary>
@ -693,14 +740,17 @@ public sealed class RuntimeCharacterOptionsState
/// flip a character option funnels through — @join/@leave, the Settings /// flip a character option funnels through — @join/@leave, the Settings
/// Chat toggles, the Options panel, a headless bot, both /// Chat toggles, the Options panel, a headless bot, both
/// <c>IRuntimeCharacterCommands.SetSingleOption</c> host adapters. /// <c>IRuntimeCharacterCommands.SetSingleOption</c> host adapters.
/// Mirrors <c>CPlayerModule::OnChanged(PlayerOption) @0x0059A8E0</c> /// Mirrors <c>CPlayerModule::OnChanged(PlayerOption) @0x0059A8E0</c>'s
/// exactly: write the bit into this LOCAL copy FIRST (so a same-session /// four-step body: write the bit into this LOCAL copy FIRST (so a
/// consumer like <see cref="TurbineChatMembershipGate"/> is correct /// same-session consumer like <see cref="TurbineChatMembershipGate"/> is
/// before any round trip), THEN either invoke /// correct before any round trip; step 1's local UI broadcast has no
/// <paramref name="sendAutoSave"/> immediately (retail's /// acdream consumer today), THEN run the PlayerModule-state-mutating
/// half of step 2's side-effect switch (MF-2, Campaign OP OP1 review
/// fix, 2026-08-11 — see below), THEN either invoke
/// <paramref name="sendAutoSave"/> immediately (step 3, retail's
/// <c>IsAutoSaveOption</c> branch — <c>Event_PlayerOptionChangedEvent</c>, /// <c>IsAutoSaveOption</c> branch — <c>Event_PlayerOptionChangedEvent</c>,
/// the <c>0x0005</c> send) or <see cref="MarkDirty"/> for the batched /// the <c>0x0005</c> send) or <see cref="MarkDirty"/> for the batched
/// <c>0x01A1</c> flush (the else branch). Matches retail's own /// <c>0x01A1</c> flush (step 4, the else branch). Matches retail's own
/// unchanged-value early return (wire research §3.1 — "an unchanged /// unchanged-value early return (wire research §3.1 — "an unchanged
/// option produces no notice, no side effect, no message at all") by /// option produces no notice, no side effect, no message at all") by
/// no-op'ing when <paramref name="value"/> already holds. Returns /// no-op'ing when <paramref name="value"/> already holds. Returns
@ -708,8 +758,31 @@ public sealed class RuntimeCharacterOptionsState
/// (retail's own <c>IsAutoSaveOption</c>/id-cast bounds check would /// (retail's own <c>IsAutoSaveOption</c>/id-cast bounds check would
/// reject it too) — callers turn that into a /// reject it too) — callers turn that into a
/// <see cref="RuntimeCommandStatus.Rejected"/>, never a silent send. /// <see cref="RuntimeCommandStatus.Rejected"/>, never a silent send.
/// <paramref name="sendAutoSave"/> takes the (id, value) actually being
/// sent rather than closing over a fixed pair, because MF-2's recursive
/// clear below needs to send a DIFFERENT id/value than the caller's own
/// — every production caller now passes
/// <c>WorldSession.SendSetSingleCharacterOption</c> directly as the
/// method group.
/// </summary> /// </summary>
public bool TrySetOption(uint characterOptionId, bool value, Action sendAutoSave) /// <remarks>
/// MF-2: step 2's local side-effect switch has six cases. Four are
/// presentation bindings (weather/day/combat-target/fog — Campaign OP's
/// later slices own those consumers) and stay unmodeled here. The other
/// two are the ONLY cases that mutate <c>PlayerModule</c> state itself —
/// <c>case 2 IgnoreFellowshipRequests</c> and
/// <c>case 0x12 FellowshipAutoAcceptRequests</c> each clear the OTHER
/// option when turned ON, through a real recursive accessor call in
/// retail (not an inlined bit-twiddle) — so turning one on while the
/// other is set produces the clear's own <c>0x0005</c> BEFORE the
/// primary option's own send (the nested call's IsAutoSaveOption branch
/// fires and returns before the outer call resumes past its own switch).
/// Both ids are themselves auto-save, so the recursion never touches
/// <see cref="MarkDirty"/> and always terminates after one level (the
/// clear passes <c>value: false</c>, which never re-triggers either
/// case's own "if now true" guard).
/// </remarks>
public bool TrySetOption(uint characterOptionId, bool value, Action<uint, bool> sendAutoSave)
{ {
ArgumentNullException.ThrowIfNull(sendAutoSave); ArgumentNullException.ThrowIfNull(sendAutoSave);
if (!CharacterOptionTable.TryGet(characterOptionId, out CharacterOptionTableEntry entry)) if (!CharacterOptionTable.TryGet(characterOptionId, out CharacterOptionTableEntry entry))
@ -721,8 +794,26 @@ public sealed class RuntimeCharacterOptionsState
SetOptionBit(characterOptionId, value); SetOptionBit(characterOptionId, value);
// MF-2: OnChanged @0x0059A8E0, cases 2/0x12 — read AFTER the local
// write above, exactly like retail's post-write accessor jump, so
// checking `value` directly is equivalent to re-reading the bit.
if (value && characterOptionId == (uint)CharacterOptionId.IgnoreFellowshipRequests)
{
TrySetOption(
(uint)CharacterOptionId.FellowshipAutoAcceptRequests,
false,
sendAutoSave);
}
else if (value && characterOptionId == (uint)CharacterOptionId.FellowshipAutoAcceptRequests)
{
TrySetOption(
(uint)CharacterOptionId.IgnoreFellowshipRequests,
false,
sendAutoSave);
}
if (entry.IsAutoSave) if (entry.IsAutoSave)
sendAutoSave(); sendAutoSave(characterOptionId, value);
else else
MarkDirty(); MarkDirty();
@ -784,47 +875,82 @@ public sealed class RuntimeCharacterOptionsState
/// Retail's <c>CPlayerModule::SaveToServer(force: 0) @0x0059A660</c> — /// Retail's <c>CPlayerModule::SaveToServer(force: 0) @0x0059A660</c> —
/// both production call sites (Apply, logout) pass <c>force = 0</c>, so /// both production call sites (Apply, logout) pass <c>force = 0</c>, so
/// a clean module sends nothing. The explicit <c>SaveOptions</c> /// a clean module sends nothing. The explicit <c>SaveOptions</c>
/// Runtime command flushes through here. /// Runtime command flushes through here. MUST-FIX M1 (Campaign OP OP1
/// review fix, 2026-08-11): also refuses before <see cref="HasServerSeed"/>
/// — flushing client-default words over the character's real server-side
/// options is the exact wipe class this gate exists to close; the module
/// stays dirty (nothing is lost) until a real <see cref="Replace"/>
/// arrives. S2 (blast lens): the decision (dirty AND seeded) is made and
/// cleared under <c>_dirtyGate</c>, but <paramref name="flush"/> itself
/// runs OUTSIDE the lock — the natural TS-71 auto-save-timer wiring
/// invokes this from Runtime's own tick while a DIFFERENT thread may be
/// routing a same-tick option toggle through App's
/// <c>LiveSessionCommandRouter</c> (which holds ITS OWN <c>_gate</c>
/// before reaching <see cref="MarkDirty"/>'s <c>_dirtyGate</c>); holding
/// <c>_dirtyGate</c> across a caller-supplied callback that could
/// transitively want <c>_gate</c> is the lock-inversion shape that
/// finding named. A throw from <paramref name="flush"/> propagates with
/// the module left dirty (nothing cleared) — the correct direction, since
/// nothing actually reached the wire.
/// </summary> /// </summary>
public bool TryFlush(Action flush) public bool TryFlush(Action flush)
{ {
ArgumentNullException.ThrowIfNull(flush); ArgumentNullException.ThrowIfNull(flush);
lock (_dirtyGate) lock (_dirtyGate)
{ {
if (!_isDirty) return false; if (!_isDirty || !_hasServerSeed) return false;
flush();
_isDirty = false;
return true;
} }
flush();
lock (_dirtyGate)
{
_isDirty = false;
}
return true;
} }
/// <summary> /// <summary>
/// Retail's <c>CPlayerModule::UseTime @0x0059A710</c>: flush iff dirty /// Retail's <c>CPlayerModule::UseTime @0x0059A710</c>: flush iff dirty
/// AND at least <see cref="AutoSaveDelay"/> (480 s, BYTE-VERIFIED) has /// AND seeded (MUST-FIX M1 — see <see cref="TryFlush"/>) AND at least
/// elapsed since <see cref="FirstDirtiedAt"/>. A no-op host may call /// <see cref="AutoSaveDelay"/> (480 s, BYTE-VERIFIED) has elapsed since
/// this once per tick; it is cheap and inert unless the timer is /// <see cref="FirstDirtiedAt"/>. A no-op host may call this once per
/// actually due. /// tick; it is cheap and inert unless the timer is actually due. S2: the
/// decide-and-clear/callback-outside-the-lock split matches
/// <see cref="TryFlush"/> exactly, for the same lock-order reason.
/// </summary> /// </summary>
public bool TryFlushIfAutoSaveDue(Action flush) public bool TryFlushIfAutoSaveDue(Action flush)
{ {
ArgumentNullException.ThrowIfNull(flush); ArgumentNullException.ThrowIfNull(flush);
lock (_dirtyGate) lock (_dirtyGate)
{ {
if (!_isDirty) return false; if (!_isDirty || !_hasServerSeed) return false;
if (_timeProvider.GetUtcNow() - _firstDirtiedAt < AutoSaveDelay) return false; if (_timeProvider.GetUtcNow() - _firstDirtiedAt < AutoSaveDelay) return false;
flush();
_isDirty = false;
return true;
} }
flush();
lock (_dirtyGate)
{
_isDirty = false;
}
return true;
} }
/// <summary>
/// Restores the client-constructor defaults AND clears
/// <see cref="HasServerSeed"/> (MUST-FIX M1) — a reconnect's fresh
/// <c>PlayerDescription</c> must re-arm the seed via a NEW
/// <see cref="Replace"/> call before the next flush can succeed; a stale
/// seed surviving a session boundary could let a flush ship the PRIOR
/// character's words over the new one's.
/// </summary>
public void ResetSession() public void ResetSession()
{ {
Volatile.Write(ref _options1, DefaultOptions1); Volatile.Write(ref _options1, DefaultOptions1);
Volatile.Write(ref _options2, DefaultOptions2); Volatile.Write(ref _options2, DefaultOptions2);
Interlocked.Increment(ref _revision); Interlocked.Increment(ref _revision);
lock (_dirtyGate) lock (_dirtyGate)
{
_isDirty = false; _isDirty = false;
_hasServerSeed = false;
}
} }
} }

View file

@ -666,8 +666,11 @@ public sealed class DirectGameRuntimeCommandAdapter
bool accepted = _runtime.CharacterOwner.Options.TrySetOption( bool accepted = _runtime.CharacterOwner.Options.TrySetOption(
optionId, optionId,
value, value,
sendAutoSave: () => // MF-2 (OP1 review fix, 2026-08-11): TrySetOption now takes
session!.SendSetSingleCharacterOption(optionId, value)); // (id, value) rather than a fixed pair — its fellowship
// mutual-exclusion recursion needs to send a DIFFERENT id/value
// than this call's own.
sendAutoSave: session!.SendSetSingleCharacterOption);
return EmitResult( return EmitResult(
RuntimeCommandDomain.Character, RuntimeCommandDomain.Character,
operation: 4, operation: 4,
@ -681,7 +684,11 @@ public sealed class DirectGameRuntimeCommandAdapter
Validate(expectedGeneration, out WorldSession? session); Validate(expectedGeneration, out WorldSession? session);
if (gate != RuntimeCommandStatus.Accepted) if (gate != RuntimeCommandStatus.Accepted)
return Result(gate); return Result(gate);
bool flushed = _runtime.CharacterOwner.Options.TryFlush(() => // MUST-FIX M1 (OP1 review fix, 2026-08-11): TryFlush itself now
// refuses before RuntimeCharacterOptionsState.HasServerSeed, so a
// SaveOptions called before the first PlayerDescription lands is a
// safe no-op rather than a wipe.
_runtime.CharacterOwner.Options.TryFlush(() =>
{ {
CharacterOptionsBlobEcho echo = CharacterOptionsBlobSource.Capture( CharacterOptionsBlobEcho echo = CharacterOptionsBlobSource.Capture(
_runtime.CharacterOwner, _runtime.CharacterOwner,
@ -694,11 +701,18 @@ public sealed class DirectGameRuntimeCommandAdapter
echo.DesiredComponents, echo.DesiredComponents,
echo.SpellbookFilters); echo.SpellbookFilters);
}); });
// S4 (OP1 review fix, blast lens): PrimaryObjectId is a typed guid
// field in the K2 bot-facing event stream (GameRuntimeEventHub.cs /
// GameRuntimeEvents.cs) — the previous `flushed ? 1u : 0u` encoding
// read as object guid 0x00000001 there.
// CurrentGameRuntimeCommandAdapter's graphical route cannot report
// whether the flush actually fired at all (LiveCommandBus.Publish
// has no return channel), so both hosts now report the identical
// shape: Accepted, objectId 0.
return EmitResult( return EmitResult(
RuntimeCommandDomain.Character, RuntimeCommandDomain.Character,
operation: 5, operation: 5,
RuntimeCommandStatus.Accepted, RuntimeCommandStatus.Accepted);
primaryObjectId: flushed ? 1u : 0u);
} }
public RuntimeCommandResult Execute( public RuntimeCommandResult Execute(

View file

@ -266,6 +266,8 @@ public sealed class LiveSessionController
private ulong _generation; private ulong _generation;
private RuntimeTeardownStage _lastTeardownStages; private RuntimeTeardownStage _lastTeardownStages;
private LiveSessionCharacterSelection? _activeSelection; private LiveSessionCharacterSelection? _activeSelection;
private Action<WorldSession>? _autoSaveTickHook;
private Action<WorldSession>? _preLogoffFlushHook;
public LiveSessionController() public LiveSessionController()
: this(ProductionLiveSessionOperations.Instance) : this(ProductionLiveSessionOperations.Instance)
@ -297,6 +299,38 @@ public sealed class LiveSessionController
get { lock (_gate) return new RuntimeGenerationToken(_generation); } get { lock (_gate) return new RuntimeGenerationToken(_generation); }
} }
/// <summary>
/// MUST-FIX 1 (Campaign OP OP1 review fix, 2026-08-11 — mechanism lens
/// finding): reaches retail's <c>CPlayerModule::UseTime</c> (the 480 s
/// batched character-option auto-save) from the SAME per-session tick
/// both the graphical host (<c>RetailLiveFrameCoordinator</c>) and the
/// no-window host (<c>HeadlessSessionHost.Tick</c>) already call —
/// <see cref="Tick()"/> — with ZERO host edits. <c>GameRuntime</c> wires
/// this once, after constructing <c>CharacterOwner</c>/
/// <c>InventoryOwner</c>, with a flush body that talks to the
/// <see cref="WorldSession"/> directly rather than through App's
/// <c>LiveSessionCommandRouter</c>/<c>LiveCommandBus</c> — which is what
/// keeps this wiring off the S2 lock-order hazard the blast-lens finding
/// named (this hook never touches the router's own gate). A hook
/// throwing is caught and logged (<see cref="Tick()"/>), never treated
/// as a tick failure — a transient send error on a background auto-save
/// must not tear down the whole live session.
/// </summary>
internal void ConfigureAutoSaveTick(Action<WorldSession> hook) =>
_autoSaveTickHook = hook ?? throw new ArgumentNullException(nameof(hook));
/// <summary>
/// MUST-FIX 1: reaches retail's <c>CPlayerSystem::LogOffCharacter</c> →
/// <c>SaveToServer</c> ordering — flush the batched option module BEFORE
/// the character-logoff wire request goes out — from Runtime's own
/// Stop/teardown transaction (<see cref="StopCore"/>), using the
/// CURRENT (not-yet-retired) session. Caught and logged rather than
/// propagated: a failed flush must not block the graceful-shutdown
/// sequence CLAUDE.md flags as ACE-timing-sensitive.
/// </summary>
internal void ConfigurePreLogoffFlush(Action<WorldSession> hook) =>
_preLogoffFlushHook = hook ?? throw new ArgumentNullException(nameof(hook));
public bool IsDisposalComplete public bool IsDisposalComplete
{ {
get { lock (_gate) return _disposed; } get { lock (_gate) return _disposed; }
@ -440,10 +474,31 @@ public sealed class LiveSessionController
throw; throw;
throw error; throw error;
} }
// MUST-FIX 1: TS-71's 480 s auto-save timer half. Runs after
// the protocol pump above and only when the scope/generation
// are still current — a reconnect that happened mid-tick
// must not flush against a retired session.
InvokeAutoSaveTick(scope.Session);
}); });
} }
} }
private void InvokeAutoSaveTick(WorldSession session)
{
if (_autoSaveTickHook is not { } hook)
return;
try
{
hook(session);
}
catch (Exception error)
{
Console.Error.WriteLine(
$"live: auto-save character-options tick failed: {error.Message}");
}
}
public void Dispose() public void Dispose()
{ {
lock (_gate) lock (_gate)
@ -621,6 +676,16 @@ public sealed class LiveSessionController
private void StopCore() private void StopCore()
{ {
// MUST-FIX 1: TS-71's logout-flush half — retail's
// CPlayerSystem::LogOffCharacter calls SaveToServer BEFORE the
// character-logoff wire request, so this runs before anything below
// touches the scope (teardown, generation bump). Gated on _inWorld
// so a failed/never-entered-world Stop (still connecting, no
// character session) never fires it — matching retail's own call
// site, which only exists on an actual in-world character.
if (_inWorld && _scope is { } activeScope)
InvokePreLogoffFlush(activeScope.Session);
++_generation; ++_generation;
_inWorld = false; _inWorld = false;
_activeSelection = null; _activeSelection = null;
@ -638,6 +703,21 @@ public sealed class LiveSessionController
_lastTeardownStages = RuntimeTeardownStage.Complete; _lastTeardownStages = RuntimeTeardownStage.Complete;
} }
private void InvokePreLogoffFlush(WorldSession session)
{
if (_preLogoffFlushHook is not { } hook)
return;
try
{
hook(session);
}
catch (Exception error)
{
Console.Error.WriteLine(
$"live: pre-logoff character-options flush failed: {error.Message}");
}
}
private void DrainRetiredScope() private void DrainRetiredScope()
{ {
if (_retiredScope is not { } retired) if (_retiredScope is not { } retired)

View file

@ -487,16 +487,22 @@ public sealed class LiveSessionCommandRouterTests
societyEldrytchWebRoom: 0u, societyEldrytchWebRoom: 0u,
societyRadiantBloodRoom: 0u); societyRadiantBloodRoom: 0u);
var sent = new List<(uint OptionId, bool Value)>(); var sent = new List<(uint OptionId, bool Value)>();
// Mirrors LiveSessionRuntimeFactory.CreateCommandBindings' shared // S1 (Campaign OP OP1 review fix, blast lens, 2026-08-11): drives the
// SendSingleCharacterOption local function: local write FIRST, then // REAL production binding — RuntimeCharacterOptionsState.
// the wire send. // 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( LiveSessionCommandRouter router = NewRouter(
characterState: characterState, characterState: characterState,
sendSingleCharacterOption: (id, value) => sendSingleCharacterOption: (id, value) =>
{ characterState.Options.TrySetOption(
characterState.Options.SetOptionBit(id, value); id,
sent.Add((id, value)); value,
}); sendAutoSave: (sentId, sentValue) => sent.Add((sentId, sentValue))));
router.Activate(); router.Activate();
Assert.Equal( Assert.Equal(

View file

@ -185,4 +185,114 @@ public sealed class CharacterOptionTableTests
for (uint id = 0x00; id <= 0x34; id++) for (uint id = 0x00; id <= 0x34; id++)
yield return [(CharacterOptionId)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( bool accepted = options.TrySetOption(
(uint)CharacterOptionId.ListenToGeneralChat, (uint)CharacterOptionId.ListenToGeneralChat,
true, true,
sendAutoSave: () => sent.Add( sendAutoSave: (id, value) => sent.Add((id, value)));
((uint)CharacterOptionId.ListenToGeneralChat, true)));
Assert.True(accepted); Assert.True(accepted);
Assert.Equal( Assert.Equal(
@ -323,7 +322,7 @@ public sealed class RuntimeCharacterStateTests
bool accepted = options.TrySetOption( bool accepted = options.TrySetOption(
(uint)CharacterOptionId.AutoTarget, (uint)CharacterOptionId.AutoTarget,
false, false,
sendAutoSave: () => sent.Add(((uint)CharacterOptionId.AutoTarget, false))); sendAutoSave: (id, value) => sent.Add((id, value)));
Assert.True(accepted); Assert.True(accepted);
// AutoTarget_CharacterOption = 0x2000 (acclient.h:3417). // AutoTarget_CharacterOption = 0x2000 (acclient.h:3417).
@ -343,7 +342,7 @@ public sealed class RuntimeCharacterStateTests
bool accepted = options.TrySetOption( bool accepted = options.TrySetOption(
(uint)CharacterOptionId.AutoTarget, (uint)CharacterOptionId.AutoTarget,
true, true,
sendAutoSave: () => sent.Add(((uint)CharacterOptionId.AutoTarget, true))); sendAutoSave: (id, value) => sent.Add((id, value)));
Assert.True(accepted); Assert.True(accepted);
Assert.Empty(sent); Assert.Empty(sent);
@ -356,13 +355,118 @@ public sealed class RuntimeCharacterStateTests
var options = new RuntimeCharacterOptionsState(); var options = new RuntimeCharacterOptionsState();
bool invoked = false; bool invoked = false;
bool accepted = options.TrySetOption(0x35u, true, () => invoked = true); bool accepted = options.TrySetOption(0x35u, true, (_, _) => invoked = true);
Assert.False(accepted); Assert.False(accepted);
Assert.False(invoked); Assert.False(invoked);
Assert.False(options.IsDirty); 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] [Fact]
public void MarkDirty_OnlySecondCallDoesNotPushOutFirstDirtiedAt() public void MarkDirty_OnlySecondCallDoesNotPushOutFirstDirtiedAt()
{ {
@ -370,17 +474,174 @@ public sealed class RuntimeCharacterStateTests
var options = new RuntimeCharacterOptionsState(clock); var options = new RuntimeCharacterOptionsState(clock);
options.TrySetOption( options.TrySetOption(
(uint)CharacterOptionId.AutoTarget, false, () => { }); (uint)CharacterOptionId.AutoTarget, false, (_, _) => { });
DateTimeOffset? firstStamp = options.FirstDirtiedAt; DateTimeOffset? firstStamp = options.FirstDirtiedAt;
Assert.NotNull(firstStamp); Assert.NotNull(firstStamp);
clock.Advance(TimeSpan.FromSeconds(10)); clock.Advance(TimeSpan.FromSeconds(10));
options.TrySetOption( options.TrySetOption(
(uint)CharacterOptionId.ShowTooltips, false, () => { }); (uint)CharacterOptionId.ShowTooltips, false, (_, _) => { });
Assert.Equal(firstStamp, options.FirstDirtiedAt); 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] [Fact]
public void TryFlush_NoOpWhenClean_FlushesAndClearsWhenDirty() public void TryFlush_NoOpWhenClean_FlushesAndClearsWhenDirty()
{ {
@ -389,8 +650,9 @@ public sealed class RuntimeCharacterStateTests
Assert.False(options.TryFlush(() => cleanFlushes++)); Assert.False(options.TryFlush(() => cleanFlushes++));
Assert.Equal(0, cleanFlushes); Assert.Equal(0, cleanFlushes);
options.Replace(options.Options1, options.Options2); // seed (M1)
options.TrySetOption( options.TrySetOption(
(uint)CharacterOptionId.AutoTarget, false, () => { }); (uint)CharacterOptionId.AutoTarget, false, (_, _) => { });
Assert.True(options.IsDirty); Assert.True(options.IsDirty);
int dirtyFlushes = 0; int dirtyFlushes = 0;
@ -410,8 +672,9 @@ public sealed class RuntimeCharacterStateTests
{ {
var clock = new ManualTimeProvider(); var clock = new ManualTimeProvider();
var options = new RuntimeCharacterOptionsState(clock); var options = new RuntimeCharacterOptionsState(clock);
options.Replace(options.Options1, options.Options2); // seed (M1)
options.TrySetOption( options.TrySetOption(
(uint)CharacterOptionId.AutoTarget, false, () => { }); (uint)CharacterOptionId.AutoTarget, false, (_, _) => { });
int flushes = 0; int flushes = 0;
clock.Advance(RuntimeCharacterOptionsState.AutoSaveDelay - TimeSpan.FromSeconds(1)); clock.Advance(RuntimeCharacterOptionsState.AutoSaveDelay - TimeSpan.FromSeconds(1));
@ -429,7 +692,7 @@ public sealed class RuntimeCharacterStateTests
{ {
var options = new RuntimeCharacterOptionsState(); var options = new RuntimeCharacterOptionsState();
options.TrySetOption( options.TrySetOption(
(uint)CharacterOptionId.AutoTarget, false, () => { }); (uint)CharacterOptionId.AutoTarget, false, (_, _) => { });
Assert.True(options.IsDirty); Assert.True(options.IsDirty);
options.ResetSession(); options.ResetSession();
@ -438,6 +701,63 @@ public sealed class RuntimeCharacterStateTests
Assert.Null(options.FirstDirtiedAt); 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 sealed class ManualTimeProvider : TimeProvider
{ {
private DateTimeOffset _now = new(2026, 8, 10, 0, 0, 0, TimeSpan.Zero); private DateTimeOffset _now = new(2026, 8, 10, 0, 0, 0, TimeSpan.Zero);

View file

@ -350,6 +350,11 @@ public sealed class DirectGameRuntimeCommandAdapterTests
CreateStartedHarness(); CreateStartedHarness();
var gameActions = new List<byte[]>(); var gameActions = new List<byte[]>();
operations.Sessions[^1].GameActionCapture = body => gameActions.Add(body); 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( adapter.Character.SetSingleOption(
runtime.Generation, (uint)CharacterOptionId.AutoTarget, false); runtime.Generation, (uint)CharacterOptionId.AutoTarget, false);
@ -365,17 +370,142 @@ public sealed class DirectGameRuntimeCommandAdapterTests
SocialActions.SetCharacterOptionsOpcode, SocialActions.SetCharacterOptionsOpcode,
System.Buffers.Binary.BinaryPrimitives.ReadUInt32LittleEndian( System.Buffers.Binary.BinaryPrimitives.ReadUInt32LittleEndian(
blob.AsSpan(8))); 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. // A clean module's second SaveOptions sends nothing more.
RuntimeCommandResult savedAgain = RuntimeCommandResult savedAgain =
adapter.Character.SaveOptions(runtime.Generation); adapter.Character.SaveOptions(runtime.Generation);
Assert.True(savedAgain.Accepted); Assert.True(savedAgain.Accepted);
Assert.Equal(0u, savedAgain.ResultObjectId);
Assert.Single(gameActions); Assert.Single(gameActions);
runtime.Dispose(); 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) private static (GameRuntime Runtime, DirectGameRuntimeCommandAdapter Adapter, FixtureSessionOperations Operations)
CreateStartedHarness() CreateStartedHarness(TimeProvider? timeProvider = null)
{ {
var operations = new FixtureSessionOperations(); var operations = new FixtureSessionOperations();
var gameplay = new FixtureGameplayOperations(); var gameplay = new FixtureGameplayOperations();
@ -384,6 +514,7 @@ public sealed class DirectGameRuntimeCommandAdapterTests
gameplay, gameplay,
gameplay, gameplay,
gameplay, gameplay,
TimeProvider: timeProvider,
SessionOperations: operations)); SessionOperations: operations));
gameplay.Bind(runtime); gameplay.Bind(runtime);
var resetHost = new FixtureResetHost(); var resetHost = new FixtureResetHost();

View file

@ -897,6 +897,133 @@ public sealed class LiveSessionControllerTests
StringComparison.Ordinal); 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] [Fact]
public void DisposeIsIdempotentAndMakesOldCommandsInert() public void DisposeIsIdempotentAndMakesOldCommandsInert()
{ {