Skip to content

fix(python): reap managed servers when HTTP cleanup fails - #3011

Merged
inureyes merged 2 commits into
lablup:mainfrom
Jaeyeong-CHOI:fix/python-reap-server-on-http-close-failure
Nov 14, 2026
Merged

inureyes merged 2 commits into
lablup:mainfrom
Jaeyeong-CHOI:fix/python-reap-server-on-http-close-failure

Conversation

@Jaeyeong-CHOI

Copy link
Copy Markdown
Contributor

Summary

When closing the HTTP client failed, or the task awaiting AsyncLLM.close() was cancelled at that point, the Python client skipped the shutdown of the server it had started, and a second close() did nothing. Both close() methods now stop the server in a finally; the original error or cancellation still propagates.

Related issues

Closes #3010.

Type of change

  • fix — bug fix

Cause

LLM.close() (python/src/mlxcel/_client.py) and AsyncLLM.close() (python/src/mlxcel/_async_client.py) set _closed = True, closed the HTTP client, and then called self._server.close() in straight-line code. An exception from the middle step skipped the last one, and the _closed flag made every later close() return early.

Change

  • The HTTP close is wrapped in try and the server shutdown moved to finally, in both clients. Nothing is swallowed: an error or CancelledError from the HTTP close is raised after the server has been stopped.
  • Tests in python/tests/test_lifecycle.py, all with a real child process on loopback: test_http_close_error_still_reaps_the_managed_child, test_async_http_close_error_still_reaps_the_managed_child, test_cancelled_async_http_close_still_reaps_the_managed_child (each through a direct close() and through the context manager), and the control test_successful_http_close_reaps_the_managed_child (sync and async).

Before / after

Linux aarch64, Python 3.12.3.

main This PR
the eight new cases, openai 3.49.0 / httpx 0.28.1 6 failed (child still alive), 2 passed (normal close) 8 passed
the eight new cases, openai 1.40.0 / httpx 0.27.0 6 failed, 2 passed 8 passed
whole suite (-m "not e2e"), each of the two pairs 59 passed, 2 deselected

Test plan

Run on this PR's source (one commit on 955335a38, tree 6b256ed50cd4).

  • python -m pytest -m "not e2e" in python/: 59 passed, 2 deselected, with the declared lower bounds and with current releases
  • The new cases on main: 6 failed, 2 passed, with both pairs
  • ruff check python, ruff format --check python, mypy python/src: pass
  • Together with five other Python client fixes proposed separately, on Python 3.12.3 and 3.9.25 with the declared lower bounds (openai 1.40.0 / httpx 0.27.0) and with current releases: 101 passed, 2 deselected in each of the four environments. This PR on its own was run on 3.12 only
  • The two live-model e2e tests: not run
  • Rust gates: not applicable, no Rust file changes
  • Windows and macOS: not run

Notes for reviewers

  • How the failure is produced. The tests inject an error at the HTTP close, or cancel a task suspended in it. This PR does not claim a particular real-world httpx failure; it makes the server shutdown independent of that step.
  • Not changed. AsyncLLM.close() still calls the synchronous ManagedServer.close() on the event loop, as on main. Whether the HTTP pool itself is fully released after a cancelled aclose() is up to httpx.
  • Implemented and validated with AI assistance (Claude). Every number above comes from the logs of those runs.

Checklist

  • PR title uses a Conventional Commits prefix
  • One logical change per PR
  • Updated docs/: not needed
  • Updated // Used by: ... comments: not applicable (Python)
  • No secrets, credentials, or .env files committed

`LLM.close()` and `AsyncLLM.close()` marked the client closed, closed the
HTTP client and then stopped the managed server in straight-line code. An
error from the HTTP close, or a cancellation while awaiting it, skipped the
server shutdown, and the closed flag made every later `close()` return
early, so the child kept running.

Stop the server in a `finally` around the HTTP close in both clients. The
original error or cancellation still propagates.
@inureyes

Copy link
Copy Markdown
Member

Thanks for the fix and the careful before/after evidence. Reviewed against #3010: both close() paths now stop the managed child in a finally, the HTTP error or cancellation still propagates, and _closed keeps later calls idempotent. No security or performance concerns; the change only reorders cleanup.

I merged current main into the branch (no conflicts) and reran the suite locally on macOS with Python 3.11 and 3.9: 59 passed, 2 deselected. ruff check, ruff format --check, and mypy python/src pass. No further changes were needed.

@inureyes
inureyes merged commit bae87d7 into lablup:main Nov 14, 2026
34 of 35 checks passed
@inureyes inureyes added the status:done Completed label Nov 14, 2026
inureyes pushed a commit that referenced this pull request Nov 14, 2026
## Summary

`AsyncLLM.close()` stopped the managed server with a synchronous call on the event loop thread, freezing every other task until the server process had exited. The shutdown now runs in the loop's default executor and is awaited; cancellation is re-raised only after the server has been reaped.

## Related issues

Closes #3014.

Stacked on #3011 (the fix for #3010): the first commit of this branch is that PR, and only the second commit is new. Both change the same `finally` block of `AsyncLLM.close()`.

## Type of change

- [x] `fix`: bug fix

## Cause

`AsyncLLM.close()` (`python/src/mlxcel/_async_client.py`) called `self._server.close()`. `ManagedServer.close()` blocks in `proc.wait(timeout=self._shutdown_grace)`, possibly a second wait after `kill()`, and `self._log_thread.join(timeout=1.0)`.

## Change

- With a running asyncio loop, `ManagedServer.close` is submitted to the default executor and awaited through `asyncio.wait`, which neither cancels the worker nor raises its error. If the task is cancelled while waiting, once or repeatedly, the wait continues and the `CancelledError` is raised after the worker has finished, so the cleanup is never left running behind a cancelled task and the child is always reaped before `close()` returns.
- Without an asyncio loop (another async backend, such as Trio through `httpx`), or when the executor no longer accepts work (it was shut down, or the interpreter is exiting), the cleanup runs synchronously as it did before.
- An error from the HTTP close, or from the server shutdown, still propagates. A client in connect mode starts no worker.
- `python/tests/test_async_shutdown.py` (new, 15 cases), each with a real child process:
  - `test_async_close_yields_and_finishes_reaping` (8 modes): the child's SIGTERM handler waits for a file that only the event loop creates, so a `close()` that blocks the loop cannot finish gracefully. Modes: direct close, context manager, HTTP-close error, cancellation inside the HTTP close, one and two cancellations during the shutdown, a child that has to be killed, an error from the shutdown itself.
  - `test_async_connect_close_does_not_start_a_worker`.
  - `test_close_reaps_when_the_executor_takes_no_work` (4 cases): after `loop.shutdown_default_executor()`, and with a submission that raises, each with and without an HTTP-close error.
  - `test_close_without_asyncio_preserves_cleanup_and_http_error` (2 cases).

## Before / after

Linux aarch64, a child that takes 350 ms to exit on SIGTERM, a 10 ms heartbeat task, two runs each:

| | `main` | parent (#3011) | This PR |
|---|---|---|---|
| Python 3.12.3: heartbeats during `close()` / largest gap | 0 / 375 ms | 0 / 375 ms | 36 / 10.6 ms |
| Python 3.9.25: heartbeats during `close()` / largest gap | 0 / 376 ms | 0 / 375 ms | 36 / 10.9 ms |
| duration of `close()` | 365 ms | 365 ms | 365 ms |

`close()` takes as long as before; what changes is that the loop keeps running meanwhile.

New test file on the parent commit and on this PR, in both environments (Python 3.9.25 with openai 1.40.0 / httpx 0.27.0, and Python 3.12.3 with openai 3.49.0 / httpx 0.28.1):

| | parent (#3011) | This PR |
|---|---|---|
| the 15 new cases | 8 failed (the eight `yields_and_finishes_reaping` modes), 7 passed | 15 passed |
| whole suite (`-m "not e2e"`) | | 74 passed, 2 deselected |

## Test plan

Run on this PR's source (the second commit of the branch; tree `6031da5bcf5a`).

- [x] `python -m pytest -m "not e2e"` in `python/`: 74 passed, 2 deselected, on Python 3.9.25 with the declared lower bounds and on Python 3.12.3 with current releases
- [x] The new file on the parent commit: 8 failed, 7 passed, both environments
- [x] The heartbeat measurement above on `main`, the parent and this PR, both environments
- [x] `ruff check python`, `ruff format --check python`: pass; `mypy python/src` (Python 3.9 target): pass
- [x] Two probes outside the suite, not repeated on the final commit: a Trio 0.35 run on Python 3.12, on the revision before the executor fallback was added (`close()` succeeds and the child is reaped); and, on the final source, a `close()` called from a non-daemon thread's loop after the main thread had ended (child reaped, exit -15, on 3.9.25 and 3.12.3). The suite's no-asyncio and executor-refusal cases exercise the same branches
- [ ] macOS and Windows: not run (the process tests skip on Windows)
- [ ] The two live-model e2e tests: not run
- [ ] Rust gates: not applicable, no Rust file changes

## Notes for reviewers

- **Cancellation is delayed, on purpose.** A task cancelled during shutdown sees its `CancelledError` only after the child has exited, which is bounded by the existing grace period (twice, if the child has to be killed). The alternative, returning at once, would leave a worker thread and possibly a child process behind a client that already reports itself closed.
- **Fallback is synchronous.** In the no-asyncio and refused-executor cases the loop is blocked for the shutdown, exactly as on `main`. This PR does not make shutdown non-blocking on Trio.
- The default executor is used, not a private one, so no thread outlives the loop's own shutdown.
- **Maintainer follow-up (f2d554a).** The first revision awaited the worker through `asyncio.shield`, so when the task was cancelled and the worker then raised, the worker's error replaced the pending `CancelledError`. The wait now uses `asyncio.wait`, a pending cancellation wins over a worker error, and a ninth mode (`cancel-worker-error`) covers it. Suite after merging `main`: 75 passed, 2 deselected on Python 3.11 and 3.9 (macOS).

## Checklist

- [x] PR title uses a Conventional Commits prefix
- [x] One logical change per PR
- [ ] Updated `docs/`: not needed
- [ ] Updated `// Used by: ...` comments: not applicable (Python)
- [x] No secrets, credentials, or `.env` files committed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

status:done Completed

Projects

None yet

Development

Successfully merging this pull request may close these issues.

fix(python): a failed or cancelled HTTP close leaves the managed server running

2 participants