Skip to content

fix(threadx): drain accepted work and reject submissions after shutdown (#3927) - #3958

Merged
Qubitium merged 1 commit into
mainfrom
fix/issue-3927
Nov 14, 2026
Merged

Qubitium merged 1 commit into
mainfrom
fix/issue-3927

Conversation

@Qubitium

Copy link
Copy Markdown
Collaborator

Fixes #3927

TL;DR

DeviceThreadPool now has one shutdown contract: tasks accepted before
shutdown() are drained and their futures resolved, in-flight counters reach
zero, and every later submit / submit_serial raises RuntimeError.
gptqmodel/utils/threadx.py (+81/−46), plus a regression suite and a reference
page (docs/device-thread-pool-shutdown.md).

1. The problem

The worker exited on _stop instead of on its sentinel, so shutdown() could
stop a busy worker before it consumed queued tasks. Submission had no
shutdown check, so work could be enqueued behind the sentinel (never run) or
lazily start a fresh worker after close.

flowchart TD
    S["submit(device, fn)"] --> P["_pick_worker(key)"]
    P --> M["_mark_scheduled(key)"]
    M --> E["worker.submit(...)"]
    E --> Q["queued behind a running task"]
    H["shutdown(wait=True)"] --> B["_stop_event.set()"]
    B --> C["snapshot groups under _dispatch_lock"]
    C --> D["w.stop() outside the lock<br/>set _stop, enqueue sentinel"]
    D --> W{"worker loop checks _stop"}
    W -- "set -> exits after current task" --> A["queued futures abandoned<br/>_inflight never drains"]
    style A fill:#fdd,stroke:#c00
Loading

Mechanisms removed, with origin/main at d1d3da04:

Old mechanism Location
while not self._stop.is_set(): gptqmodel/utils/threadx.py:518
submit() picks/enqueues with no shutdown check gptqmodel/utils/threadx.py:1146
submit_serial() enqueues after releasing the lock gptqmodel/utils/threadx.py:1175
_pick_worker() can lazily spawn during/after shutdown gptqmodel/utils/threadx.py:1465
shutdown() issues w.stop() outside the lock gptqmodel/utils/threadx.py:1233, :1257
plain threading.Lock() gptqmodel/utils/threadx.py:725

2. The new flow

Submission: accept or reject atomically

flowchart TD
    S["submit(device, fn) / submit_serial(device, fn)"] --> L["acquire _dispatch_lock (RLock)"]
    L --> Q{"_stop_event set?"}
    Q -- "Yes (shutdown started)" --> R["raise RuntimeError<br/>no new work accepted"]
    Q -- "No" --> P["_pick_worker_locked / _refresh_serial_worker_locked"]
    P --> M["_mark_scheduled(key)<br/>inflight += 1"]
    M --> E["worker.submit(...)<br/>enqueue task ahead of sentinels"]
    E --> U["release _dispatch_lock"]
    U --> D["worker _run loop: execute queued tasks in FIFO order"]
    D --> T{"sentinel reached?"}
    T -- "No" --> D
    T -- "Yes (queue drained)" --> X["break; _on_worker_exit removes worker"]
    R --> Z["caller sees RuntimeError"]
    style R fill:#fdd,stroke:#c00
    style Z fill:#fdd,stroke:#c00
    style X fill:#dfd,stroke:#060
Loading

Shutdown: stop accepting, then drain

flowchart TD
    H["shutdown(wait=True)"] --> A["acquire _dispatch_lock"]
    A --> B["_stop_event.set()"]
    B --> C["snapshot _worker_groups"]
    C --> D["for each worker: w.stop()<br/>set _stop, enqueue sentinel"]
    D --> E["release _dispatch_lock"]
    E --> F["_gc_event.set(); join janitor"]
    F --> G{"wait?"}
    G -- "Yes" --> I["join every worker thread"]
    G -- "No" --> J["return"]
    I --> K["workers drained every accepted task<br/>then exited on the sentinel"]
    style B fill:#ffd,stroke:#a60
    style K fill:#dfd,stroke:#060
Loading

stop() enqueues its sentinel after every task the pool already accepted, so
reaching the sentinel proves the queue is drained. _dispatch_lock is now an
RLock because _SyncWorker.stop() re-enters _on_worker_exit, which takes
the same lock, from the shutting-down thread.

3. Failure and ambiguity contract

stateDiagram-v2
    state "Accepting" as A
    state "Draining" as D
    state "Stopped" as S
    [*] --> A
    A --> A: submit accepted, task queued
    A --> D: shutdown() sets _stop_event
    A --> A: submit after shutdown observed -> RuntimeError
    D --> D: workers drain queued tasks
    D --> S: every worker joined
    S --> S: submit -> RuntimeError
    style S fill:#dfd,stroke:#060
Loading
Situation Before After
Task queued when shutdown() starts abandoned; future pending, _inflight stuck, wait() can hang drained FIFO, future resolved, _inflight reaches 0
submit racing shutdown() could enqueue behind the sentinel serialized: enqueued ahead of every sentinel (drained) or rejected
submit after shutdown() accepted, never resolves RuntimeError("DeviceThreadPool is shutting down; ...")
submit_serial after shutdown() spawned a worker, enqueued same RuntimeError
Empty group after shutdown lazy selection repopulated it rejected before selection; no thread started
_SyncWorker stop during shutdown n/a (stops issued outside the lock) RLock prevents self-deadlock

No silent fallback: rejection raises, and an accepted task always runs.

4. Change inventory

Area File ± Purpose
Worker loop, dispatch, shutdown gptqmodel/utils/threadx.py +81/−46 exit on sentinel, atomic accept/reject, RLock, stops issued under the lock
Tests tests/test_threadx_shutdown.py +161 7 time-bounded regressions
Docs docs/device-thread-pool-shutdown.md +116 reference page + diagrams
README README.md +5 link to the page

5. Tests / guarantees

Test Invariant
test_shutdown_drains_a_queued_task issue repro: queued future resolves, _inflight == 0, wait() returns
test_shutdown_drains_every_queued_task draining is not limited to one item
test_submit_after_shutdown_is_rejected RuntimeError on late submit
test_submit_serial_after_shutdown_is_rejected RuntimeError on late submit_serial
test_lazy_worker_selection_does_not_spawn_after_shutdown no thread after close
test_a_shutdown_pool_rejects_work_promptly rejection does not depend on a worker
test_sync_worker_stop_does_not_self_deadlock RLock re-entry is safe

6. Validation

GPU: CUDA_VISIBLE_DEVICES=GPU-1892aea4-cc09-827c-b9a5-93d4eef7f5ae, HIP_VISIBLE_DEVICES=0.

Before the fix (source stashed, tests kept):

PYTHONPATH=$PWD timeout 300 /opt/venvs/cu130t/bin/python -m pytest tests/test_threadx_shutdown.py -q
=> 6 failed, 1 passed

After the fix:

PYTHONPATH=$PWD /opt/venvs/cu130t/bin/python -m pytest tests/test_threadx_shutdown.py -q
=> 7 passed

PYTHONPATH=$PWD /opt/venvs/cu130t/bin/python -m pytest tests/test_threadx.py tests/test_threadx_cpu.py tests/test_threadx_cpu_locks.py tests/test_threadx_warmup_accounting.py -q
=> 23 passed, 29 skipped (all skips: requires >= 2 CUDA devices)

HIP_VISIBLE_DEVICES=0 /opt/venvs/rocm101t/bin/python -m pytest tests/test_threadx_shutdown.py tests/test_threadx_cpu.py tests/test_threadx_cpu_locks.py tests/test_threadx_warmup_accounting.py -q
=> 14 passed, 5 skipped

ruff check gptqmodel docs/eora tests setup.py
=> All checks passed!

Issue reproducer, after the fix: thread alive: False, f1 done: True,
f2 done: True -> second, inflight: {'cpu': 0} (before: f2 done: False,
inflight: {'cpu': 1}).

7. Reviewer notes

  • No new PyTorch API is introduced (only threading primitives are reordered),
    so pytorch_gil_0_compat.md is unchanged.
  • No GPTQMODEL_* switch is added; the contract is unconditional.
  • The change deliberately drains accepted work rather than cancelling futures:
    cancellation would race with a task that is already executing, while draining
    keeps in-flight accounting exact.
  • docs/device-thread-pool-shutdown.md is the committed reference page and is
    linked from README.md beside the CPU pool lock scopes entry.

@Qubitium
Qubitium merged commit 0f2964c into main Nov 14, 2026
6 checks passed
@Qubitium
Qubitium deleted the fix/issue-3927 branch November 14, 2026 10:12
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.

DeviceThreadPool shutdown leaves queued futures pending and permits work after close

1 participant