← Back to Pull requests

Add initializer and worker exit timeouts #459

Closed
cjrh closed this pull request without merging on Nov 30, 2026 23:13 UTC
View on GitHub
cjrh cjrh commented on Nov 30, 2026 22:06 UTC
Author

A hung initializer can occupy a worker before its first task timer starts. A hung finalizer or atexit handler can block pool shutdown. This PR adds two optional timeouts, both unlimited by default.

with Deadpool(initializer=open_connection, initializer_timeout=15,
              finalizer=flush_metrics, worker_exit_timeout=5) as pool:
    ...

The five-second exit budget starts when the worker enters cleanup. If the finalizer takes four seconds, all exit handlers share the last second. The same budget applies when a task registered an exit handler in a pool with no finalizer. A task timeout keeps its existing behavior of skipping the finalizer and uses the exit budget for its handlers. A worker configured with an exit timeout that detects parent loss skips the handlers and kills its process tree immediately.

The parent enforces the deadlines even if a callback holds the worker’s GIL. On expiry it attempts to kill descendants and sends SIGKILL to the worker. A future already dispatched to a worker whose initializer times out can raise ProcessError. Subsequent work can use a replacement.

Comparison with #458

#458 starts timing when the pool requests retirement. Here the worker reports when initialization or cleanup begins. This covers initializers, explicit shutdown, clearing, recycling, idle retirement, and cleanup after task timeout. A stall between a stop request and entry into cleanup is outside the exit budget.

Each monitored worker uses one parent thread and one extra pipe. An initializer-only monitor ends after initialization. Recycling stays asynchronous, so every worker still retiring can retain its own thread and pipe alongside the replacements. The monitor count can temporarily exceed max_workers.

Regression coverage

Tests exercise a finalizer and handler that each fit the budget individually and exceed it together, handlers with no finalizer, parent loss, and initializer deadlines with all three Linux start methods. Additional tests cover partial pool startup, a transient SIGKILL failure, and redispatch after an idle initializer times out.

Diff: 622 lines (+559 / -63) across 4 files Reviewer: cjrh Review duration: 66m
All Vouch review confidence checks passed
Residual risk 0.18 = Change Risk (0.60) × (1 − Review Confidence (0.70)). Review depth and reviewer attention state are adequate.
Model 1 · Change Risk (XGBoost)
Score: 0.60 · 622 lines diff across 4 files
0.60
Model 2 · Review Depth (DistilBERT)
Depth Score: 0.41 · 1 substantive comment(s)
0.41
Model 3 · Review Timing & Attention
Session adequacy: 100% · Reviewer familiarity: 35%
69%
Bedrock Claude 3 · Risk Narration
(disconnected)
Groq
Groq Risk Narration
AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
Model 1 · Change Risk Attribution
SHAP Weights
Diff Size diff_size
0.385
Self Review self_review
0.140
Real PR Conversation Timeline
3 items
cjrh cjrh commented on Nov 30, 2026 23:09 UTC
Reviewer

Review decision: Request changes on ee7ce42. Sharing one exit budget between the finalizer and all atexit handlers works on the normal cleanup path. The reasons to leave this implementation unmerged concern what happens when a worker takes a different exit path, a signal fails, or the pool has already replaced the worker. We’re pursuing the narrower parent-side retirement timeout in #458.

1. An initializer that raises SystemExit can leave shutdown waiting indefinitely. The initializer call catches Exception, so SystemExit leaves the worker entry point before finish_worker() announces cleanup. Python then runs its own exit handlers. With a 150 ms exit budget, a one-second handler finished normally under all three Linux start methods (forkserver, spawn, and fork). An exceptional exit needs to arm the budget before control returns to Python’s teardown, while preserving the initializer’s exit semantics. Initializer call · Cleanup entry

2. Cancellation can still signal a dead worker’s PID. I retained the failed future after an initializer timed out, waited for the worker to die, then called shutdown(wait=False, cancel_futures=True). A mocked signal sender recorded a SIGKILL request for the dead PID. If the OS has reused it, an unrelated process can receive that signal. This cancellation bug predates the PR. The broken-pipe fix protects dispatch retries, but shutdown still walks retained futures and cancellation uses their numeric PIDs. A hard cancellation needs to verify the original process identity and that the job still owns that worker. Shutdown · Future cancellation

3. A job that raises deadpool.TimeoutError can strand its worker and monitor. The parent interprets the returned exception as evidence that the worker’s task timer fired and the worker is already exiting. It starts a replacement without sending the original a stop request. Under fork, the replacement ran a job and pool shutdown returned while the original worker and its monitor were still alive. I confirmed the process leak on main too. This PR adds a monitor that can stay alive with it. The worker protocol needs a distinct indication that the task timer fired so an ordinary application exception can be handled as a job result. Result handling · Worker replacement

4. Application logging can prevent deadline enforcement. The monitor logs before signalling. With a slow warning handler, a one-second finalizer completed despite a 150 ms limit. A handler that raises can terminate the monitor before it sends SIGKILL. Signal first and keep logging failures out of the retry path, including the warning after a failed signal attempt. Monitor exception handlers · Retry logging

5. A persistently denied SIGKILL can monopolize a pool slot. On a broken pipe, dispatch calls worker.abort() before releasing the busy worker. The signal loop retries permission errors forever. In a one-worker pool, later jobs and shutdown can therefore wait indefinitely. This follows from the control flow. The regression test demonstrates recovery from a transient denial on the monitor thread. The synchronous dispatch path also needs a bounded way to report failure and release the slot while keeping the failed worker out of circulation. Dispatch retry · Abort · Signal loop

6. Forked siblings inherit monitor descriptors. In an eight-worker pool using fork, enabling the exit timeout added one socket descriptor in the first worker, two in the second, and so on through eight in the last. Under forkserver, each worker gained one. This happens at startup, before any worker retires, in addition to the documented cost of asynchronous recycling. Each child should retain only the monitor endpoint it needs. Pipe creation and worker startup

7. A readable sentinel can disarm a live worker’s deadline. Under fork and spawn, the sentinel is a pipe whose write end lives in the worker. Cleanup can close that descriptor while the process still has work to do. The monitor treats readability as death before checking the captured process identity. I verified that decision with a pipe fixture representing a still-live process. Once a deadline is armed, the monitor should confirm that the original process exited before dropping the deadline. Sentinel and identity checks

All 118 existing lifecycle, callback-timeout, and idle-worker tests passed in the re-review on CPython 3.14. For future regression coverage, the first three findings can be exercised through ordinary initializer and task callbacks, retained futures, replacement submissions, and shutdown(). The cancellation check can record the requested signal safely with a mock.

harness=Codex,model=GPT-6,reasoning=unspecified

cjrh cjrh commented on Nov 30, 2026 23:13 UTC
Author

Closing this PR. It's a good example of how trying to plug just one or two extra holes quickly gets out of control.

Reviewers
Assignees
cjrh cjrh
Labels
risk: low confidence: 69.9% reviewed
Vouch Risk Breakdown
AI-powered review risk analysis
Change Risk
Change Risk · Model 1 (XGBoost)
Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
Score: 59.9% (MEDIUM) · Higher = larger blast radius
59.9%
Review Confidence
Review Confidence · Models 2 & 3
Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
Score: 69.9% · Lower = rushed or shallow review
69.9%
Residual Risk
Residual Risk · Core Equation
Residual = Change × (1 − Confidence)
Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
Score: 18% · Safe to merge
18%
Repository