Skip to content

Deadlock Detection and State Machine

buntatoes edited this page Nov 28, 2026 · 1 revision

Deadlock Detection and State Machine

RubyLock RPC reconstructs Deadlock's live state by combining two lightweight, read-only signals:

  1. ProcessWatcher (lib/rubylock_rpc/process_watcher.rb) — detects when deadlock.exe starts or exits.
  2. LogWatcher (lib/rubylock_rpc/log_watcher.rb) — tails Deadlock's -condebug output file (game/citadel/console.log) and feeds structured transitions into GameState (lib/rubylock_rpc/game_state.rb).

Game Phases & Match Modes

Game Phases (RubylockRpc::GamePhase)

Phase Constant Symbol Hero Portrait Shown? Description
NOT_RUNNING :not_running No Deadlock process is not active or has shut down.
MAIN_MENU :main_menu No Deadlock is running (or console.log initialized), before entering Hideout.
HIDEOUT :hideout Yes Local player is in dl_hideout. Displays hero-specific Hideout flavor text and party headcount when party_size > 1.
IN_QUEUE :in_queue Yes Player is searching for a match (k_EMsgClientToGCStartMatchmaking). Displays Hideout line as details and matchmaking text as state.
MATCH_INTRO :match_intro Yes Lobby created or non-loopback server connected; loading into match or intro phase.
IN_MATCH :in_match Yes Active match gameplay on a non-hideout map. Tracks elapsed match duration via Process::CLOCK_MONOTONIC.
POST_MATCH :post_match No Match lobby destroyed, disconnected from match server, or ChangeGameState: PostGame (6).
SPECTATING :spectating No Watching a live broadcast (Playing Broadcast). Hero signals and map changes are ignored while spectating.

Match Modes (RubylockRpc::MatchMode)

Mode Constant Display Name Uses in_match Template? How Detected
STANDARD "Standard Match" Yes Map street_test / street_test_bridge, or dl_midtown with >= 9 players.
RANKED "Ranked Match" Yes Defined mode display & template support.
STREET_BRAWL "Street Brawl" Yes dl_midtown with 4..8 players (pending_player_count >= 4 and < 9).
BOT_MATCH "Bot Match" No (uses display name + timer) Initializing bot for player slot <N>: k_ECitadelBotDifficulty_* while mode is UNKNOWN.
TRAINING_RANGE "Training Range" No (uses display name + timer) Map new_player_basics. Allows free hero swapping.
HERO_LABS "Hero Labs" No (uses display name + timer) Allows free hero swapping.
UNKNOWN "In Match" Yes Fallback when a match map is loaded before player count or bot lines resolve the mode.

State Machine Flow

stateDiagram-v2
    [*] --> NOT_RUNNING
    NOT_RUNNING --> MAIN_MENU : deadlock.exe detected / console.log found
    MAIN_MENU --> HIDEOUT : Map dl_hideout
    HIDEOUT --> IN_QUEUE : k_EMsgClientToGCStartMatchmaking
    IN_QUEUE --> HIDEOUT : k_EMsgClientToGCStopMatchmaking
    MAIN_MENU --> IN_QUEUE : k_EMsgClientToGCStartMatchmaking

    HIDEOUT --> MATCH_INTRO : Lobby created / Remote server connect
    IN_QUEUE --> MATCH_INTRO : Lobby created / Remote server connect
    MAIN_MENU --> MATCH_INTRO : Lobby created / Remote server connect

    MATCH_INTRO --> IN_MATCH : Non-hideout map physics / ChangeGameState GameInProgress (7)
    HIDEOUT --> IN_MATCH : Non-hideout map loaded directly
    IN_MATCH --> POST_MATCH : Lobby destroyed / Disconnect / LoopMode menu / PostGame (6)
    MATCH_INTRO --> POST_MATCH : Server disconnect / LoopMode menu
    POST_MATCH --> HIDEOUT : Map dl_hideout

    HIDEOUT --> SPECTATING : Playing Broadcast
    MAIN_MENU --> SPECTATING : Playing Broadcast
    SPECTATING --> POST_MATCH : Server disconnect / LoopMode menu

    IN_MATCH --> NOT_RUNNING : deadlock.exe exited / EXITING / Source2Shutdown / 300s stale
    HIDEOUT --> NOT_RUNNING : deadlock.exe exited / EXITING / Source2Shutdown
Loading

LogWatcher Regex Patterns (PATTERNS)

Every line read from game/citadel/console.log is evaluated by LogWatcher.process_line(line, state). The table below documents every log signature recognized by RubyLock RPC:

Pattern Key Regex / Substring Effect on GameState
local_account_id /\[U:1:(\d+)\]/ Captures the local player's Steam3 account ID (first positive match) for party reconciliation and optional Statlocker link.
party_event /CMsgGCToClientPartyEvent:\s+\{\s*party_id:\s+(\d+)\s+event:\s+(k_e\w+)\s+initiator_account_id:\s+(\d+)\s*\}/ Updates party membership on joinedparty, leftparty / removedfromparty / kickedfromparty, and disband events.
map_created_physics /\[Client\] Created physics for\s+([^\s]+)/ Applies map change (dl_hideout -> HIDEOUT; other maps -> IN_MATCH + mode inference).
map_info /\[Client\] Map:\s+"([^"]+)"/ Applies map change (ignoring "start" and "<empty>").
(substring) "k_EMsgClientToGCStartMatchmaking" Enters IN_QUEUE from HIDEOUT or MAIN_MENU.
(substring) "k_EMsgClientToGCStopMatchmaking" Leaves IN_QUEUE back to HIDEOUT.
lobby_created /Lobby\s+\d+\s+for\s+Match\s+\d+\s+created/ Prepares match hero tracking and enters MATCH_INTRO (from menu/hideout/queue/intro).
lobby_destroyed /Lobby\s+\d+\s+for\s+Match\s+\d+\s+destroyed/ Transitions to POST_MATCH and clears match_started_at.
spectate_broadcast /Playing Broadcast/ Enters SPECTATING and sets hideout_loaded = false.
server_connect /\[Client\] CL:\s+Connected to '([^']+)'/ For non-loopback addresses, prepares match hero tracking and enters MATCH_INTRO.
loaded_hero /\[Server\] Loaded hero \d+\/(hero_\w+)/ Normalizes hero key and calls apply_hero_signal (ignored in HIDEOUT until hideout_loaded is true to avoid precache noise).
client_hero_vmdl `/VMDL Camera Pose Success!.*models/heroes(?:_wip _staging)?/(\w+)//`
server_disconnect /\[Client\] Disconnecting from server:\s+(\S+)/ Resets state if reason includes EXITING; transitions active match/intro/spectating to POST_MATCH unless reason includes LOOPDEACTIVATE.
loop_mode_menu /LoopMode:\s*menu/ Transitions IN_MATCH, MATCH_INTRO, or SPECTATING to POST_MATCH.
change_game_state /ChangeGameState:\s+(\w+)\s+\((\d+)\)/ Ignored while spectating or in Hideout. Maps MatchIntro/4 -> MATCH_INTRO, GameInProgress/InProgress/7 -> start_match, PostGame/6 -> POST_MATCH.
hideout_lobby_state /\[Hideout\] Hideout Lobby Connection State:\s+(\w+)\s+\((-?\d+)\)/ Clears party if lobby ID is 0 while in HIDEOUT.
host_activate /\[HostStateManager\] Host activate:.*\(([^)]+)\)/ Marks hideout_loaded = true once dl_hideout activates.
server_shutdown /\[Server\] SV:\s+Server shutting down:\s+(\S+)/ Resets state if reason contains EXITING.
(substrings) "Dispatching EventAppShutdown_t" or "Source2Shutdown" Full state.reset on clean Source 2 engine shutdown.
precaching_heroes /Precaching (\d+) heroes in CCitadelGameRules/ Sets hideout_loaded = false when count > 0 so bulk hero precaching does not overwrite the active hero.
player_info /\[Client\] Players:\s+(\d+)\s+\(\d+ bots\)\s+\/\s+\d+ humans/ In HIDEOUT, reconciles Hideout player count into party_size (max 6). In MATCH_INTRO/IN_MATCH, records peak pending_player_count and triggers mode inference.
bot_init /Initializing bot for player slot \d+:\s+k_ECitadelBotDifficulty_\w+/ Sets match_mode = BOT_MATCH when mode is still UNKNOWN during MATCH_INTRO or IN_MATCH.

Hero Normalization & Lock-In Logic

Key Normalization (LogWatcher.normalize_hero_key)

Deadlock console logs emit hero identifiers in several formats (for example hero_inferno_v2, ratking, or models/heroes/haze/haze.vmdl). Normalization converts them into canonical hero_<name> keys:

  1. Lowercases the raw string.
  2. Strips trailing version suffixes matching _v<digits> (e.g., hero_inferno_v2 -> hero_inferno, hero_ratking_v2 -> hero_ratking).
  3. Prepends hero_ if not already present (e.g., haze -> hero_haze).

Hero Lock-In Guard (GameState#apply_hero_signal)

During a real match, Source 2 loads models for enemy and teammate heroes as well as the local player. To keep Rich Presence locked onto your hero:

  • In MATCH_INTRO and IN_MATCH:
    • When entering a match (enter_match_intro / prepare_match_hero_tracking), @hero_key is cleared and @hero_window_open is set to true.
    • The first hero signal received locks @hero_key and closes @hero_window_open = false; subsequent different hero signals are ignored.
    • Exception: In TRAINING_RANGE and HERO_LABS, free_swap is enabled so switching heroes on the fly updates Discord immediately.
  • In HIDEOUT: Hero signals are accepted freely once hideout_loaded is true (after [HostStateManager] Host activate: (dl_hideout)), so swapping heroes in the Hideout updates your portrait and flavor text immediately without being polluted by initial hero precaching.
  • In MAIN_MENU, POST_MATCH, and SPECTATING: Hero signals are ignored.

Party Tracking in the Hideout

RubyLock RPC combines two sources to keep Hideout party headcounts accurate (clamped to 1..6):

  1. GC Party Events (CMsgGCToClientPartyEvent): Tracks known party_members by account ID on joinedparty / leftparty / removedfromparty / kickedfromparty / disband. When the local player joins a party, party_unknown_members starts at 1 to account for the host/other member(s) already present before subsequent events arrive.
  2. Hideout Player Count ([Client] Players: N ...): apply_hideout_player_count(count) clamps count to 6 and reconciles @party_unknown_members = [clamped - @party_members.size, 0].max, ensuring the displayed (X of 6) badge in Discord reflects everyone physically in the Hideout even if RubyLock RPC was started mid-party.

Log Tailing Resilience & Resync

LogWatcher#run handles every real-world lifecycle edge case of console.log:

  • Mid-Session Startup (RESYNC_BYTES = 10 MiB): If RubyLock RPC starts after Deadlock is already running, it seeks to [file_size - 10 MiB, 0].max (skipping the first partial line if seeking past byte 0), enters MAIN_MENU, and replays the tail slice to immediately reconstruct your current phase, map, mode, hero, account ID, and party size.
  • Log Truncation: When Deadlock restarts and overwrites console.log, file_size < last_pos triggers an immediate reset and resync from byte 0.
  • Log Removal: If console.log disappears after initialization, GameState resets and logs the session duration.
  • Crash Staleness (MATCH_STALE_SECS = 300): If Deadlock crashes silently during IN_MATCH or MATCH_INTRO and no bytes are appended to console.log for 300 seconds, LogWatcher assumes a crash and resets GameState.
  • Invalid UTF-8 Protection: Bytes are read in binary mode ("rb") and transcoded with encode("UTF-8", invalid: :replace, undef: :replace) so malformed console bytes never crash the watcher thread.

Native Process Monitoring (ProcessWatcher)

RubylockRpc::ProcessWatcher polls every 3 seconds (POLL_INTERVAL_S = 3) for deadlock.exe without spawning external shells or tools (tasklist, pgrep, or ps):

  • Windows (Win32Snapshot via Fiddle):
    • Dynamically binds CreateToolhelp32Snapshot, Process32First, Process32Next, and CloseHandle from kernel32.dll.
    • Uses architecture-aware PROCESSENTRY32 layout (EXE_NAME_OFFSET = 44, total 304 bytes on 64-bit Windows; 36 / 296 bytes on 32-bit Windows).
    • Never flashes a console window when running under rubyw.exe.
  • Linux (/proc filesystem):
    • Scans /proc/[0-9]*, checking both comm and the basename of the first NUL-delimited argument in cmdline (normalizing \ to / so Proton/Wine deadlock.exe processes match seamlessly).
    • Matches both "deadlock.exe" and its stem "deadlock" case-insensitively.

Clone this wiki locally