Skip to content

[JIT] fix(jit): treat a zombie lock holder as dead in FileBaton - #7148

Open
Woody-Hu wants to merge 2 commits into
ROCm:mainfrom
Woody-Hu:fix/file-baton-zombie-pid
Open

Woody-Hu wants to merge 2 commits into
ROCm:mainfrom
Woody-Hu:fix/file-baton-zombie-pid

Conversation

@Woody-Hu

@Woody-Hu Woody-Hu commented Oct 29, 2026 •

Copy link
Copy Markdown

Summary

FileBaton treats a lock holder that is a zombie (exited but not yet reaped) as dead, so a crashed builder's lock is broken instead of hanging every later import aiter. The same /proc/<pid>/stat state check is mirrored in the two sibling kill(pid, 0) probes: the jit_cache codegen-owner probe and the mp_tuner worker-exit probe.

Motivation

FileBaton serialises the AOT module builds in aiter/jit. A builder killed mid-build (SIGKILL, OOM kill, container stop) never reaches release(), so it leaves <build_dir>/lock behind. The class docstring states the intent explicitly:

The lock file records the owning pid and host so that a crashed or killed builder ... leaves behind a stale lock that waiters can detect and break, instead of deadlocking forever.

On Linux that detection is implemented as:

try:
    os.kill(pid, 0)
except ProcessLookupError:
    return False
return True

A zombie still answers kill(pid, 0) with success, so _pid_alive() returns True, _is_stale() returns False forever, and wait() spins at 0.2 s intervals with no timeout and a single INFO line. From the outside the process simply hangs, with no diagnostics.

Because these locks are per build module and nested (the outer lock is held by the very process blocked on the inner one), a single crashed build can leave several stale locks that block every subsequent startup of every process that imports aiter, indefinitely, until the files are removed by hand.

Observed in the wild: two nested locks (aiter/jit/build/lock_module_custom_all_reduce and aiter/jit/build/module_custom_all_reduce/build/lock) both recording the pid of a process dead for ~24 h and still in state Z. Selecting a different attention backend did not help — the hang happens at import time, before any device work.

The same probe is copied into two other places, and the same hang/failure mode reaches them:

  • aiter/jit/utils/jit_cache.py keeps a deliberately self-contained _pid_alive() ("kept self-contained rather than shared with file_baton"). A builder killed mid-codegen — after writing the incomplete marker but before flipping it to complete — still looks live, and every later build of that module fails with RuntimeError: blob code generation is already active from _marker_owner_is_active / stage_blob_sources.
  • aiter/utility/mp_tuner.py:_task_worker_exited() uses the same probe, so a GPU-faulted tuning worker that is still unreaped keeps its task waiting for the full timeout instead of being reported gone.

Reproduction (no GPU, no build, ~10 lines)

import importlib.util, os, socket, subprocess, time

spec = importlib.util.spec_from_file_location("fb", "aiter/jit/utils/file_baton.py")
fb = importlib.util.module_from_spec(spec); spec.loader.exec_module(fb)

p = subprocess.Popen(["sleep", "300"])
os.kill(p.pid, 9)            # do NOT wait(): the child must stay a zombie
time.sleep(0.5)
print("state =", open(f"/proc/{p.pid}/stat").read().rsplit(")", 1)[1].split()[0])  # Z
lock = "/tmp/baton_repro.lock"
open(lock, "w").write(f"{p.pid}\n{socket.gethostname()}\n")

print("alive? ", fb.FileBaton._pid_alive(p.pid))   # True  <- the bug
fb.FileBaton(lock).wait()                          # never returns

Run under timeout 8 python3 repro.py: prints Z, then True, then gets killed by the timeout (exit 124).

Changes

Read the state field of /proc/<pid>/stat on Linux and treat Z (and X) as dead. _pid_alive() keeps the existing kill(pid, 0) semantics and only subtracts the zombie case (also on the PermissionError path, since /proc reports the state of foreign processes too). Windows and non-Linux paths are unchanged.

@staticmethod
def _is_zombie(pid):
    if not sys.platform.startswith("linux"):
        return False
    try:
        with open(f"/proc/{pid}/stat", "rb") as f:
            data = f.read()
    except (FileNotFoundError, ProcessLookupError, PermissionError):
        return False
    rparen = data.rfind(b")")          # comm is parenthesised and may contain ')'
    if rparen < 0:
        return False
    rest = data[rparen + 1 :].split()
    return bool(rest) and rest[0] in (b"Z", b"X")
  • aiter/jit/utils/file_baton.py: new _is_zombie(), called from _pid_alive().
  • aiter/jit/utils/jit_cache.py: local _is_zombie() called from _pid_alive(); the docstring now states that this handling must stay in sync with FileBaton.
  • aiter/utility/mp_tuner.py: local _is_zombie(); _task_worker_exited() returns it once kill(pid, 0) succeeds (success only proves the pid is taken).
  • Three copies instead of one shared helper: the three load modes (package import, top-level import after core.py puts aiter/jit/utils on sys.path, and spec_from_file_location in the tests) leave no import path that works everywhere without sys.path/path-loading machinery. Happy to revisit if you would rather have the shared module.

Performance (if applicable)

Not applicable — pure Python JIT infrastructure, no kernel/op change, so no workload benchmark is relevant. The only hot-path effect is one extra /proc read per 0.2 s wait spin, taken only after kill(pid, 0) succeeds and never on the uncontended acquire path; the automated review measured _pid_alive on a live pid at 0.37 µs (base bca8bde1e) vs 7.41 µs (head f7d659c33), +7.04 µs ≈ 0.004% of one spin.

Testing

  • Unit tests added or updated
  • Performance benchmarks run — not applicable (pure Python JIT infrastructure), see above
  • Tested on MI250X — unavailable; validation needs no AMD GPU (see below)
  • Tested on MI300X — unavailable; validation needs no AMD GPU (see below)

New tests/test_file_baton.py (unittest, module loaded straight from source — no ROCm needed):

  • spawns a real zombie (SIGKILL, deliberately left unreaped), asserts _pid_alive() is False, _is_stale() is True, and _try_break_stale() removes the lock;
  • drives wait() in a daemon thread with a 5 s join, so a regression fails loudly instead of hanging the suite;
  • also covers a live holder, a reaped holder, and the missing-owner-info path.

On the platform where the bug bites (gfx1151 Linux host, Python 3.12, real killed-but-unreaped children):

suite base (bca8bde1e) head (f7d659c33)
tests/test_file_baton.py (5) 2 failed 5 passed
op_tests/test_jit_cache_transaction.py (TestJitCacheRecovery + TestJitCacheTransaction, 26) new test_zombie_codegen_owner_is_recovered failed at _pid_alive(zombie) is True 26 passed
test_mp_tuner_logic.TestTaskWorkerExit zombie cases (2) _task_worker_exited returned False 2 passed

The new jit_cache case also drives the end-to-end path: it writes an incomplete marker owned by the zombie pid, then asserts stage_blob_sources restores and completes the tree instead of raising.

Documentation

  • Docstrings updated — _is_zombie() docstrings, and the jit_cache copy now states it must stay in sync with FileBaton._pid_alive()
  • User guide updated
  • Performance guide updated
  • No documentation change is needed — this is an internal stale-lock recovery path with no user-facing API, flag or dependency change

Dependencies

  • No new third-party dependencies added
  • New dependencies are listed and justified below

Breaking Changes

None. Lock file format, public API and non-Linux behaviour are unchanged; only the zombie case stops being reported as "alive".

PR Self-Review

Reviewed revision

e1ecb5346c3b (rebased onto upstream/main 45e71e04b)

Behavior and intent

A lock/marker/worker owner that has exited but not been reaped (state Z, or X) is now treated as dead, so its hold on FileBaton.wait(), on a jit_cache codegen marker, and on mp_tuner's worker-exit check is released. The existing behaviour is insufficient because kill(pid, 0) succeeds for a zombie: FileBaton.wait() spins forever on a stale lock, the next build of an affected module dies with RuntimeError: blob code generation is already active, and a GPU-faulted tuning worker is only noticed after its task timeout. Intended behaviour (from the class docstring) is that a crashed builder's lock is detected and broken instead of blocking every later import aiter; this PR makes the three probes match that intent. Everything else is unchanged: live pids, reaped pids, missing owner info, foreign hosts, Windows/non-Linux.

Validation and unverified scope

Commands (run from the repo root):

  • python3 -m unittest tests.test_file_baton -v
  • python3 -m unittest op_tests.test_jit_cache_transaction.TestJitCacheRecovery op_tests.test_jit_cache_transaction.TestJitCacheTransaction
  • python3 -m unittest op_tests.tuning_tests.test_mp_tuner_logic.TestTaskWorkerExit -v
  • python3 -m ruff check aiter/jit/utils/file_baton.py aiter/jit/utils/jit_cache.py aiter/utility/mp_tuner.py tests/test_file_baton.py op_tests/test_jit_cache_transaction.py op_tests/tuning_tests/test_mp_tuner_logic.py → clean

Hardware/configuration: gfx1151 (Ryzen AI MAX 395, Strix Halo) Linux host, ROCm container, Python 3.12; results in the table above (base 2 failed / 1 of 26 failed / 2 failed → head 5 passed / 26 passed / 2 passed). No AMD GPU, no HIP build and no aiter JIT build is involved — the tests load the modules from source and use real child processes, so the absence of MI250X/MI300X in this environment is not a coverage gap.

Post-rebase re-check at e1ecb534 (macOS, no /proc, no ROCm): tests/test_file_baton.py → 3 passed, 2 skipped; op_tests/test_jit_cache_transaction.py → 26 tests, 1 skipped (/proc-only zombie case). The mp_tuner suite cannot be imported on macOS (needs a ROCm install). So the 3 /proc-only tests skipped in those two suites, and the mp_tuner zombie test, were not re-run on Linux at e1ecb534; the rebase was verified to be content-identical to the validated head f7d659c33 (the two patch files differ only in their index blob hashes).

Unverified: MI250X / MI300X / Windows runs (no access); behaviour with PID reuse (see below); a wait() timeout.

PR-specific question

What changes in dependency, cache or compilation behavior, and how did you verify both a clean build and an existing-cache path?

  • Dependency: none added — stdlib only (sys, existing os), no new requirement, no lock-file format change (still pid\nhost\n).
  • Compilation/cache behaviour: the change is confined to ownership detection of the JIT cache. A stale lock or an incomplete codegen marker whose owner is a zombie is now classified as abandoned, so the next build reclaims it and re-runs codegen instead of raising RuntimeError: blob code generation is already active. Nothing about what gets compiled, where artifacts are stored, or how they are published changed; a marker owned by a live pid still blocks a concurrent build exactly as before.
  • Clean build path (tests/test_file_baton.py, and TestJitCacheTransaction: test_successful_codegen_is_published_only_after_explicit_commit, test_header_only_codegen_is_accepted, test_codegen_that_produces_no_build_input_is_rejected): no marker / no lock present, codegen stages, publishes only on explicit commit, and a failed generator raises instead of publishing.
  • Existing-cache path (TestJitCacheTransaction: test_staging_path_and_unchanged_mtime_are_stable, test_failed_codegen_restores_last_complete_sources, test_snapshot_does_not_reuse_same_stat_file_with_changed_content; TestJitCacheRecovery: test_fresh_legacy_backup_formats_recover_without_age_delay, test_recovery_does_not_take_live_peer_or_remote_backups): a complete marker/published tree is reused without recompiling, a live peer's staging tree and backup are still left alone, and a failed run restores the last complete sources. The new test_zombie_codegen_owner_is_recovered adds the third case — an abandoned marker — and asserts the tree is restored, completed, and that the transaction artifacts are cleaned up.

Changed op tests

  • op_tests/test_jit_cache_transaction.py — adds TestJitCacheRecovery.test_zombie_codegen_owner_is_recovered. It covers the incomplete-marker recovery path when the marker's recorded owner is an unreaped zombie: asserts jit_cache._pid_alive(zombie) is False and _marker_owner_is_active(marker) is False, then asserts stage_blob_sources restores the sources, writes the complete marker and leaves no transaction artifacts, instead of failing with "blob code generation is already active". Not redundant: the existing recovery cases all use an owner that was reaped — test_dead_owner_is_reaped_without_waiting_for_legacy_grace calls child.wait(), test_abrupt_restore_owner_exit_is_recovered_and_reclaimed uses subprocess.run, and the live-peer cases keep the owner alive — so none of them keeps the child unreaped, which is exactly the state kill(pid, 0) misreports and the only state this PR changes. Without the fix the new test fails at _pid_alive(zombie) is True.
  • op_tests/tuning_tests/test_mp_tuner_logic.py — adds TestTaskWorkerExit.test_killed_unreaped_worker_is_detected. It SIGKILLs a child, waits until /proc/<pid>/stat reports Z without reaping it, and asserts mp_tuner._task_worker_exited([pid], 0) is True, i.e. a GPU-faulted worker is reported gone immediately instead of holding the task until its timeout. Not redundant: test_exited_worker_is_detected in the same class waits on its child first, so it passes even with the buggy probe; test_worker_pid_recorded_when_task_starts and the queued-slot cases do not exercise exit detection at all. Without the fix the new test fails because _task_worker_exited returns False for the zombie.
  • No other op_tests/ file is touched.

Notes / scope

  • Not addressed here (happy to do as a follow-up if wanted):
    • PID reuse: a recycled pid still reads as alive. The robust fix records the holder's start time (field 22 of /proc/<pid>/stat) in the lock file and compares it on read. That changes the lock file format, so it deserves its own discussion.
    • wait() has no timeout. Adding a bounded wait with an ERROR log (lock path + owner pid) would turn a silent hang into a diagnosable failure; left out to keep this PR behaviour-preserving apart from the bug.

@Woody-Hu
Woody-Hu requested a review from a team October 29, 2026 09:17
@github-actions

Copy link
Copy Markdown
Contributor

🏷️ CI Guide

Runs automatically on every PR:

  • ✅ Pre-checks (submodule verification, code formatting)
  • ✅ Aiter op tests (gfx942 + gfx950)
  • ✅ Triton tests on MI35X (only when aiter/ops/triton/** or related paths are changed)

Extended tests (opt-in via labels):

Label Tests
ci:gfx1250-ffm-triton Run the five-shard gfx1250 FFM Triton test suite
ci:triton-300x Run an additional Triton test job on MI300X in PRs (added automatically when gfx942 configs change); main branch always runs both MI35X and MI300X
ci:triton-355 Run the full Triton test suite on MI35X, not only the tests the change affects
ci:windows Windows JIT op smoke test on the gfx1201 ROCm runner
ci:multi-gpu Aiter multi-GPU tests on the 8-GPU runner
ci:sglang SGLang integration tests: DeepSeek-R1-MXFP4 accuracy, Qwen 3.5 accuracy
ci:atom ATOM benchmark: DeepSeek-R1-0528, GPT-OSS-120B
ci:atom_full ATOM accuracy suite for PR and main models from ATOM models_accuracy.json
ci:vllm vLLM benchmark: DeepSeek-V4-Pro, MiniMax-M3-MXFP4
ci:all All standard extended tests (excludes ci:atom_full)

Only add ci:atom_full for FlyDSL or Triton upgrades.
Add labels via the sidebar or gh pr edit 7148 --add-label <label>

One backend per PR:
A PR changes one kernel backend: [Triton/Gluon] (Triton and Gluon count as one), [HIP], [ASM], [CK], [OPUS] or [FlyDSL]. If the title ends up with two backend tags, split the PR -- as stacked pull requests when one part cannot merge without the other.

PR title tags & labels:
Component tags ([Triton/Gluon], [HIP], [CK], [ASM], ...) are added to the PR title and as PR labels automatically from the changed files and re-synced on every push — change-type tags like [fix]/[Perf], op tags like [MLA], and human labels (ci:*) are left untouched. Add the no-auto-title label to stop the title rewrites; labels stay in sync either way.

@github-actions github-actions Bot changed the title fix(jit): treat a zombie lock holder as dead in FileBaton [JIT] fix(jit): treat a zombie lock holder as dead in FileBaton Oct 29, 2026
@github-actions github-actions Bot added the JIT label Oct 29, 2026
@zufayu
zufayu requested a review from amd-ruitang3 October 30, 2026 01:26
@amd-ruitang3

Copy link
Copy Markdown
Contributor

@aiter-bot review

@aiter-bot

Copy link
Copy Markdown

aiter-bot — queued behind 1 review(s); expect to start in about 50 min. The box reviews one PR at a time.

@aiter-bot

Copy link
Copy Markdown

ROCm/aiter PR #7148 — [JIT] fix(jit): treat a zombie lock holder as dead in FileBaton

FileBaton's stale-lock detection now parses /proc//stat on Linux and treats a zombie (killed-but-unreaped) lock holder as dead, so a crashed builder's lock gets broken instead of hanging every later import aiter in an unbounded 0.2 s spin.

Review (advisory): ⚠️ NEEDS WORK
Validation (deterministic): NOT RUN — triage required runtime validation but no validator target exists (tests/test_file_baton.py is not a validator target); run by hand instead: 5/5 pass on head, the 2 zombie tests fail on base — the runtime path is test-covered, so the missing target is not a PR defect
Perf (advisory): MEASURED — _pid_alive on a live pid (the only changed hot path, probed once per 0.2 s wait spin), base 0.37 µs vs head 7.41 µs per call, +7.04 µs (5 samples × 20,000 calls, same box, back to back) — 0.004% of one 0.2 s spin, and never on the uncontended acquire path

⚠️ [verified] The zombie fix lands only in aiter/jit/utils/file_baton.py, but aiter/jit/utils/jit_cache.py:75 keeps a deliberate self-contained copy of the same os.kill(pid, 0) probe (its own comment: "kept self-contained rather than shared with file_baton"), so a builder killed mid-codegen — after writing the incomplete marker (jit_cache.py:314) but before it flips to complete (jit_cache.py:362) — still blocks every later build of that module with RuntimeError: blob code generation is already active from _marker_owner_is_active/stage_blob_sources (jit_cache.py:194, 302-305), reproduced end to end with a real zombie child; aiter/utility/mp_tuner.py:66 carries the same probe for GPU-faulted tuning workers. Author must apply the same zombie check to those two copies (or extract one shared helper) so the no-manual-cleanup recovery this PR promises survives past the first lock.

@aiter-bot

aiter-bot commented Nov 3, 2026 •

Copy link
Copy Markdown

WAITING ON AUTHOR

PR Self-Review

Revision 7a690964ef8e · mode shadow

Waiting for the PR author. The readiness report will appear after the self-review answers are complete for this revision.

Questions to answer in the PR description

  1. What behavior does this PR change, and why is the existing behavior insufficient?
  2. What did you validate, and what remains unverified? Include commands, hardware/configuration and results.
  3. What changes in dependency, cache or compilation behavior, and how did you verify both a clean build and an existing-cache path?
  4. For every changed op_tests/ file, what behavior does it cover and why is it not redundant? Write None if no op test changed.

Edit the PR Self-Review section in the PR description. Include the current revision SHA; this comment refreshes automatically.

Missing or invalid answers

  • FAIL — Reviewed revision must contain at least the first 7 characters of the current head SHA

Shadow mode reports what would block but keeps the status successful. Set AITER_PR_SELF_REVIEW_MODE=enforce only after reviewing real false positives.

@Woody-Hu

Woody-Hu commented Nov 3, 2026

Copy link
Copy Markdown
Author

Addressed in f7d659c — both sibling probes now subtract the zombie case.

  • aiter/jit/utils/jit_cache.py: _pid_alive consults a local _is_zombie (state Z/X from /proc/<pid>/stat), so a builder killed between the incomplete-marker write and the complete flip no longer blocks the next build of that module with RuntimeError: blob code generation is already active. The copy stays self-contained because the module is also loaded straight from its path; the docstring now states that its zombie handling must stay in sync with FileBaton._pid_alive.
  • aiter/utility/mp_tuner.py: _task_worker_exited gets the same check, so a GPU-faulted worker that is still an unreaped zombie is reported gone instead of waiting for the task timeout.
  • I did not extract a shared helper: the three load modes (package import, top-level import after core.py puts aiter/jit/utils on sys.path, and spec_from_file_location in the tests) leave no import path that works everywhere without sys.path/path-loading machinery. Happy to revisit if you'd rather have the shared module.

Runtime validation on a gfx1151 Linux host (Python 3.12), with real killed-but-unreaped children:

suite base (bca8bde1e) head (f7d659c33)
tests/test_file_baton.py (5) 2 failed 5 passed
op_tests/test_jit_cache_transaction.py (TestJitCacheRecovery + TestJitCacheTransaction, 26) new test_zombie_codegen_owner_is_recovered failed at _pid_alive(zombie) is True 26 passed
test_mp_tuner_logic.TestTaskWorkerExit zombie cases (2) _task_worker_exited returned False 2 passed

The new jit_cache case also drives the end-to-end path: it writes an incomplete marker owned by the zombie pid, then asserts stage_blob_sources restores and completes the tree instead of raising.

On the warm-path cost the review measured (+7.04 µs/call): unchanged in shape — /proc is read only after os.kill succeeds, i.e. once per 0.2 s wait spin, never on the uncontended acquire path.

@Woody-Hu

Copy link
Copy Markdown
Author

The PR Self-Review section in the description now carries Reviewed revision: e1ecb5346c3b, which matches the current head — the earlier "Missing or invalid answers" notice predates that edit (description updated 2026-11-09, bot comment 2026-11-03). Could the self-review re-run against the current revision?

For the sibling-probe finding: both copies now share the zombie check, landed in f7d659c — aiter/jit/utils/jit_cache.py (_pid_alive consults a local _is_zombie) and aiter/utility/mp_tuner.py (_task_worker_exited). Covered by tests/test_file_baton.py, op_tests/test_jit_cache_transaction.py and op_tests/tuning_tests/test_mp_tuner_logic.py.

A builder that is killed while holding the baton leaves its lock file behind.
FileBaton promises waiters can detect and break such a lock instead of
deadlocking forever, but `_pid_alive` only ran `os.kill(pid, 0)`, which keeps
returning success for a zombie (exited but not yet reaped by its parent).
The lock was therefore never considered stale and every later process that
imports aiter spun in `wait()` indefinitely, with a single INFO line and no
timeout -- a stale `jit/build/.../lock` (nested one level per module) bricked
all subsequent startups until the file was removed by hand.

Read the state field of /proc/<pid>/stat on Linux and treat Z/X as dead. Other
platforms keep the kill probe, since they do not expose the state.

Tests cover a real zombie child (killed and deliberately left unreaped): they
fail on the old code and pass with this change; no AMD GPU is required.
The zombie check landed only in FileBaton, but jit_cache and mp_tuner
keep their own kill(pid, 0) probes. A builder killed mid-codegen left an
incomplete marker that still looked owned by a live process, so the next
build failed with "blob code generation is already active"; a GPU-faulted
tuning worker likewise kept its task waiting for the timeout. Mirror
FileBaton's /proc state check in both copies and cover each with a real
zombie.
@Woody-Hu
Woody-Hu force-pushed the fix/file-baton-zombie-pid branch from e1ecb53 to 7a69096 Compare November 25, 2026 01:01
@Woody-Hu

Copy link
Copy Markdown
Author

Rebased onto the current ROCm/aiter main to clear the conflicts.

  • New head: 7a690964ef8ed487a9ec561c7597f2332a5344ae
  • Rebased onto: f3da4e779c07201c296015f84a4bcda4ad51ee24 (upstream main)

The change is semantically unchanged (same 6 files): _pid_alive keeps treating a zombie (/proc/<pid>/stat state Z/X) as dead, the self-contained copies in FileBaton, jit_cache and mp_tuner stay in sync, and the docstrings/tests are unchanged. The only conflict was the import block in op_tests/tuning_tests/test_mp_tuner_logic.py, resolved by keeping both (pickle from main, signal from this PR).

@aiter-bot please re-run the PR Self-Review on this revision — the previous "WAITING ON AUTHOR" result was on the pre-rebase commit.

This branch has not been deployed

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

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants