Skip to content

Bugfix: offlevel fixes#806

Open
eduardosmaniotto wants to merge 9 commits into
MUnique:masterfrom
eduardosmaniotto:bugfix/offlevel-reconnect
Open

Bugfix: offlevel fixes#806
eduardosmaniotto wants to merge 9 commits into
MUnique:masterfrom
eduardosmaniotto:bugfix/offlevel-reconnect

Conversation

@eduardosmaniotto

@eduardosmaniotto eduardosmaniotto commented Jun 18, 2026

Copy link
Copy Markdown
Contributor

Closes #804

Phantom online entries

SuppressDisconnectedEvent() nulled all PlayerDisconnected subscribers, including GameContext.RemovePlayerAsync. Since RemovePlayerAsync is the only place that cleans up _playerList PlayerCounter, and PlayersByCharacterName, the real player leaked as a "phantom online" entry that permanently inflated the online count until server restart.

Client not closing gracefully

DisconnectAsync() just dropped the TCP connection without sending a close-game packet, so the client's auto-reconnect feature kicked in and tried to reconnect immediately.

Offlevel jewel pickup

Match jewels by concrete (group, number) instead of broad group-14 check in offline helper. Add test case for this.

Cross-context entity corruption

OfflinePlayer.InitializeAsync received the real player's already-tracked Account/Character references and attached them to a fresh DbContext via Attach. If SaveProgressAsync failed during the handover, entities with non-default GUIDs got Unchanged instead of Added in the new context, causing DbUpdateConcurrencyException on subsequent saves. Fixed by loading the account fresh via GetAccountByLoginNameAsync instead.

Leak on session end

Both termination paths (Zen-exhaustion and death) now route through
OfflinePlayerManager.StopAsync, which properly cleans up _activePlayers
(resetting IsActive) and guarantees _playerList removal via its finally
block. Intelligence disposal is deferred to a background task and awaited
in DisposeAsyncCore before player resource teardown, preventing a race
between pet handler shutdown and PersistenceContext disposal.

@eduardosmaniotto eduardosmaniotto marked this pull request as draft June 18, 2026 01:44
@gemini-code-assist

Copy link
Copy Markdown

Summary of Changes

Hello, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request addresses critical bugs related to player disconnection and server state management. By ensuring that players are explicitly removed from the GameContext and improving the client-server handshake during disconnection, the server now maintains accurate online counts and prevents unnecessary reconnection attempts. The PR also includes a wide range of maintenance tasks, including documentation updates, code refactoring, and improved test assertions.

Highlights

  • Phantom Online Entries: Fixed an issue where players were not correctly removed from the GameContext, causing phantom entries and inflated online counts.
  • Graceful Disconnection: Updated the disconnection process to send a close-game packet, preventing clients from entering an infinite auto-reconnect loop.
  • Code Refactoring and Cleanup: Performed extensive refactoring of the Player experience logic, improved documentation across various modules, and cleaned up unused code and imports.
New Features

🧠 You can now enable Memory (public preview) to help Gemini Code Assist learn from your team's feedback. This makes future code reviews more consistent and personalized to your project's style. Click here to enable Memory in your admin console.

Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize the Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counterproductive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for GitHub and other Google products, sign up here.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request performs extensive code cleanup, refactoring, and documentation updates across the codebase. Key changes include extracting the ResetProgression struct and AppearanceChangedExtendedPlugIn class into separate files, updating unit tests to use modern NUnit constraint-based assertions, and fixing various XML documentation comments. Additionally, minor logic improvements were introduced, such as explicitly removing disconnected players in OfflinePlayerManager to ensure player list consistency. As there are no review comments provided, we have no feedback to offer.

Important

The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.

nolt added a commit to nolt/OpenMU that referenced this pull request Jun 19, 2026
… the online list is purged

Replace SuppressDisconnectedEvent() in the offline-session handover with a
proper close-game logout view call before DisconnectAsync(). Letting the
PlayerDisconnected event fire naturally makes GameContext.RemovePlayerAsync
run (removing the phantom-online entry), while the close-game packet stops
the client from auto-reconnecting. Removes the now-unused
Player.SuppressDisconnectedEvent().

Extracted minimal fix from eduardosmaniotto's bugfix/offlevel-reconnect (PR MUnique#806).
@nolt

nolt commented Jun 20, 2026

Copy link
Copy Markdown
Contributor

▎ Heads-up on a data-loss issue I hit with this offline flow: OfflinePlayer attaches the real player's already-tracked Account/Character graph into its own fresh PersistenceContext instead of loading it fresh, which corrupts EF change tracking — so every periodic SaveChangesAsync throws DbUpdateConcurrencyException ("expected 1 row, affected 0") and no offline progress is ever persisted. The result is that the character silently rolls back to its pre-/offlevel state on the next login (also worth disposing the OfflinePlayer on stop, since the connectionless ghost never triggers the game server's disconnect/dispose path).

▎ Fix that worked for me: load the account/character via GetAccountByLoginNameAsync into the offline player's own context (no cross-context Attach), mirroring the normal login.

@nolt

nolt commented Jun 21, 2026

Copy link
Copy Markdown
Contributor

Heads-up: offline MU Helper hoards non-jewel items when "Pick Jewels" is enabled

With "Pick Jewels" on, a /offlevel session fills the inventory with non-jewels — Ale, Devil's Eye/Key/Invitation, Symbol of Kundun and potions. Root cause is in ItemPickupHandler.ShouldPickUp, where the jewel check is item.Definition?.Group == 14: group 14 is "Pots and Misc", not just jewels, so the whole group gets collected. The online MU Helper only picks actual jewels, so the offline behavior diverges and the bag fills up over a long session.

Fix hint: match jewels by concrete (group, number) instead of the whole group — Bless (14,13), Soul (14,14), Life (14,16), Creation (14,22), Guardian (14,31), Gemstone (14,41), Harmony (14,42), Lower/Higher refine stone (14,43/44), plus Jewel of Chaos (12,15) which the group-14-only check misses today.

@eduardosmaniotto eduardosmaniotto changed the title Bugfix: offlevel reconnect and player count Bugfix: offlevel fixes Jun 21, 2026
@eduardosmaniotto eduardosmaniotto marked this pull request as ready for review June 23, 2026 21:11

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request refactors the offline player initialization and lifecycle management. Key changes include loading accounts and characters fresh from the database during initialization, replacing the Timer in OfflinePlayerMuHelper with a PeriodicTimer loop, and refining the disconnect and cleanup process. Additionally, jewel pickup logic was improved to target specific jewel IDs, supported by new unit tests. Feedback on these changes highlights a potential ObjectDisposedException during shutdown in the timer loop, a possible NullReferenceException if account.Characters is null, and redundant progress saving during player disconnection.

Important

The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.

Comment thread src/GameLogic/Offline/OfflinePlayerMuHelper.cs
Comment thread src/GameLogic/Offline/OfflinePlayer.cs Outdated
Comment thread src/GameLogic/Offline/OfflinePlayer.cs
@nolt

nolt commented Jun 24, 2026

Copy link
Copy Markdown
Contributor

Heads-up: /offlevel leaves an orphaned ghost (Id 0) when the offline session ends — both on Zen-exhaustion and on death

Observed (reproduced on a local lab)
When an offline-leveling (/offlevel) session terminates, the ghost player can be left as a stuck orphan:

  • It lingers in the game's player list and shows up on the admin panel map as Id 0 / blank name.
  • It persists until a full server restart (clears the in-memory player list).
  • Confirmed for two independent triggers:
    a. Insufficient Zen — the offline grind fee can no longer be paid.
    b. Death / respawn — the ghost dies and the session is stopped after respawn.
  • Zen path only, additional symptom: OfflinePlayerManager.IsActive(loginName) stays true, so the account cannot start /offlevel again ("already active") until a restart.

Common factor in code (high confidence)
Both termination paths call OfflinePlayer.StopAsync() from inside the MuHelper's own running tick:

  • Death: OfflinePlayerMuHelper.HandleDeathAsync() → OfflinePlayerManager.StopAsync(loginName) → OfflinePlayer.StopAsync().
  • Zen: ZenConsumptionHandler.DeductZenAsync() → OfflinePlayer.StopAsync() directly (this one also bypasses OfflinePlayerManager.StopAsync, so _activePlayers is never TryRemoved → IsActive stuck true).

OfflinePlayer.StopAsync() first does intelligence.DisposeAsync(), which cancels and disposes the very CancellationTokenSource whose token the current tick is running under — i.e. the teardown disposes itself mid-flight. The net effect is that the ghost is removed from the map (Player.Id reset to 0) but not reliably removed from the game's player list / disposed.

Exact "not removed from player list" step — NOT yet pinned (candidates for you to confirm):

  • Re-entrant self-cancel: StopAsync disposing the tick's own CTS aborts the rest of StopAsync (SaveProgressAsync / DisconnectAsync) before list removal.
  • DisconnectAsync removes from the list only by raising PlayerDisconnected (→ GameContext.RemovePlayerAsync). If the ghost's PlayerDisconnected is already null (e.g. via SuppressDisconnectedEvent() used during the real-client handoff), the ghost is never removed from _playerList.
  • OfflineRespawnPlugIn.RespawnAsync() is a no-op; combined with RespawnAtAsync removing-from-map before re-adding, a ghost can end up off-map (Id 0) if the path is cut short.

Suggested direction

  • Never tear the session down synchronously from inside the tick. Mirror the death-defer pattern (_isDead flag → stop on a later/outer turn) for the Zen case too, so StopAsync does not dispose its own running tick.
  • Route the Zen-exhaustion stop through OfflinePlayerManager.StopAsync(loginName) (so _activePlayers is cleared and IsActive is reset).
  • Ensure StopAsync/teardown guarantees removal from the player list + disposal regardless of PlayerDisconnected state.

Minor, separate (pre-existing): MovementHandler.MoveCloserToTargetAsync dereferences this._player.CurrentMap! with no null guard (unlike WalkToAsync). While a ghost is momentarily off-map, the 500 ms tick throws NullReferenceException ("Error in offline player helper tick"), swallowed by SafeTickAsync but spamming the log. Add the same CurrentMap is not { } map guard.

Repro (Zen path)
Set a character's Zen to just above the startup fee (CostPerStage[0] × (Level + MasterLevel)), /offlevel, wait one PayInterval (default 5 min). The next

@nolt

nolt commented Jun 25, 2026

Copy link
Copy Markdown
Contributor

You will hate me 😄

Heads-up: offline player (/offlevel) auto-repair drains Zen far faster than the online MU Helper

Symptom

A high-level character left on /offlevel returns with almost no carried Zen, and the
offline session often stops early ("insufficient Zen"). The same character running the
online MU Helper with the same settings is strongly Zen-positive. Players read this
as "offline loses my money" / "offline doesn't pick up Zen", but PickZen works fine — the
drain is auto-repair.

Root cause: a repair parity gap between the online (client) MU Helper and the offline re-implementation

Two differences make the offline ghost repair far more aggressively, and both ends pay the
expensive no-NPC self-repair rate:

  1. Repair threshold.

    • Offline GameLogic/Offline/RepairHandler.PerformRepairsAsync() (called every tick from
      OfflinePlayerMuHelper.TickAsync, ~500 ms) repairs each equipped slot via
      ItemRepairAction.RepairItemAsync, which repairs whenever
      item.Durability != item.GetMaximumDurabilityOfOnePiece() — i.e. on any wear.
    • The client MU Helper (MuMain/src/source/MUHelper/MuHelper.cpp CMuHelper::RepairEquipments)
      only repairs when item durability health <= DEFAULT_DURABILITY_THRESHOLD (50%), then
      sends SendRepairItemRequest(slot, /*isSelfRepair*/ 1).
  2. Self-repair rate (2.5×), common to both but only ever hit by MU Helper.

    • ItemRepairAction.RepairItemAsync (PlayerActions/Items/ItemRepairAction.cs:106):
      CalculateRepairPrice(item, player.OpenedNpc != null).
    • The offline ghost never has an OpenedNpc; the online MU Helper self-repairs without
      opening an NPC (isSelfRepair=1). Both therefore pass npcDiscount = false, and
      ItemPriceCalculator.CalculateRepairPrice applies repairPrice *= 2.5f.
    • The server packet handler ItemRepairHandlerPlugIn ignores the client's self-repair flag;
      price depends solely on OpenedNpc. A normal player repairs at an NPC (1×); only the
      MU Helper (online or offline) ever takes the 2.5× field-repair path.

The repair price is roughly linear in missing-durability, but for high-value gear the
coefficient is huge (base = min(buyPrice/3, 400M); 3·√base·⁴√base·missing·2.5). Repairing
even a few % of an expensive set costs ~hundreds of thousands. Because the offline ghost
repairs on any wear (vs the client's 50% threshold) and can only spend carried Zen (no
vault access), it bleeds the carried buffer to zero within a couple of minutes and stops on
"insufficient Zen", while the online MU Helper defers repairs and the player out-earns them.

Live evidence (lab, imported prod config x300/x30; Blade Master, Level+MasterLevel ≈ 908)

Same character, same MU Helper config (PickZen + PickSelect on), only RepairItem toggled:

RepairItem Start Zen After ~1.5–2 min Outcome
ON 1,038,578 208 session stopped (insufficient Zen); −~1.03M
OFF 288,785 768,241 net +~480k (~320k/min), session healthy

With RepairItem ON the ghost still hunted (MasterExp +31.7M) and still picked up Zen
(observed +1,891 / +3,034 increments), confirming PickZen is fine — repair simply swamped income.

Suggested direction

  1. Align the offline repair threshold to the client's 50% (only repair at
    durability <= 50% of max) so offline matches online MU Helper frequency. This alone
    removes the offline-specific drain.
  2. Optionally reconsider whether MU Helper self-repair should use the NPC (1×) rate rather
    than the 2.5× field penalty — this affects both online and offline MU Helper and, at high
    level, can make MU Helper repair disproportionately expensive.

Note: per-unit repair cost is identical for online-MU-Helper vs offline; the offline-specific
behaviour is (a) the any-wear threshold and (b) carried-Zen-only spending.

Files / symbols

  • src/GameLogic/Offline/RepairHandler.csPerformRepairsAsync (repairs on any wear).
  • src/GameLogic/Offline/OfflinePlayerMuHelper.cs (~line 158) — calls PerformRepairsAsync every tick.
  • src/GameLogic/PlayerActions/Items/ItemRepairAction.cs:106CalculateRepairPrice(item, player.OpenedNpc != null).
  • src/GameLogic/ItemPriceCalculator.csCalculateRepairPrice, if (!npcDiscount) repairPrice *= 2.5f.
  • src/GameServer/MessageHandler/Items/ItemRepairHandlerPlugIn.cs — repair packet handler (ignores self-repair flag).
  • Client: MuMain/src/source/MUHelper/MuHelper.cppCMuHelper::RepairEquipments (DEFAULT_DURABILITY_THRESHOLD=50, SendRepairItemRequest(slot, 1)).

@eduardosmaniotto

Copy link
Copy Markdown
Contributor Author
  1. Align the offline repair threshold to the client's 50% (only repair at
    durability <= 50% of max) so offline matches online MU Helper frequency. This alone
    removes the offline-specific drain.

No problem, it makes sense to use the same threshold. Option 2 should not be implemented since it is a field repair.
About being expensive, that should be a server configuration, for example CalculateRepairPrice could be refactored to use configured values instead of hardcoded. But that is not in the scope of this PR.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Command /offlevel leaks the real player from the player list: online count stays inflated ("phantom online") after offline leveling starts

2 participants