Skip to content

Add subinterpreter worker pool (Python 3.14+) - #11103

Open
RemiDesgrange wants to merge 4 commits into
celery:mainfrom
RemiDesgrange:feat-subinterpreter
Open

RemiDesgrange wants to merge 4 commits into
celery:mainfrom
RemiDesgrange:feat-subinterpreter

Conversation

@RemiDesgrange

Copy link
Copy Markdown

Note: Before submitting this pull request, please review our contributing
guidelines
.

Description

Adds a subinterpreter worker pool (celery worker -P subinterpreter, Python 3.14+). It runs tasks in parallel in isolated interpreters of the worker process (PEP 734, concurrent.interpreters), each with its own GIL. CPU-bound tasks get parallelism like prefork, with the lower memory and startup cost of threads.

Design

  • A ThreadPoolExecutor in the main interpreter drives a fixed set of subinterpreters, one per concurrency slot.
  • Only the trace function (fast_trace_task / trace_task_ret) and the message data cross into a subinterpreter. The accept, success and failure callbacks (acks, events, result handling) run in the main interpreter, which owns the broker connection.
  • Each subinterpreter is set up at worker start like a prefork child started with spawn: it registers tasks on the unpickled app, imports the task modules, sets up logging, rebuilds the tracers and sends worker_process_init. It also copies the main interpreter's sys.path, which subinterpreters don't inherit (e.g. the current directory added by celery -A).
  • Subinterpreters are created up front, so a task module that can't load in one stops the worker at startup with a hint, not on the first task.
  • If a task can't run at all (unregistered task, or an argument or result that can't be pickled), the request gets a WorkerLostError.

Stopping running tasks

A running subinterpreter can't be interrupted. So on revoke(terminate=True), cold shutdown or a soft time limit, the pool asks the task to stop through a per-interpreter queue. Task code checks it with celery.concurrency.subinterpreter.stop_requested():

from celery.concurrency.subinterpreter import stop_requested
from celery.exceptions import Ignore

@app.task
def process(items):
    for item in items:
        if stop_requested():
            raise Ignore()  # keeps REVOKED after a revoke
        handle(item)

A task that doesn't check runs to completion, and the worker waits for it, even on cold shutdown. Returning normally after a stop request records a success; raising Ignore keeps the state the worker set. Hard time limits aren't supported and are ignored with a warning at startup.

Recycling

--max-tasks-per-child replaces a subinterpreter after N tasks; worker_process_shutdown is sent in it before it closes. --max-memory-per-child isn't supported, because memory is only measured for the whole process.

Limitations

  • Extension modules must support loading in subinterpreters. Many don't yet, for example pydantic-core, gevent and psutil. A task module importing one stops the worker at startup. This is documented.
  • Module-level state is separate in each subinterpreter, as in each prefork child.

Tests

  • Unit tests: t/unit/concurrency/test_subinterpreter.py, skipped below 3.14.
  • Smoke tests: t/smoke/tests/test_subinterpreter_pool.py runs a worker with --pool=subinterpreter in Docker, with Redis and RabbitMQ brokers. It covers pool stats, tasks running in subinterpreters, a canvas, failures, warm and cold shutdown, stop requests on revoke, cold shutdown and soft time limit, and --max-tasks-per-child.
    • The dev worker Dockerfile takes a new PYTHON_VERSION build arg (default unchanged, 3.13); this test builds it on 3.14.
    • The test worker loads only t/smoke/subinterpreter_tasks.py, because t.integration.tasks imports pydantic and pytest-celery's tasks import psutil.
  • Local runs: unit tests pass on 3.14 and 3.15, and the 20 smoke tests pass.

Docs

  • New page docs/userguide/concurrency/subinterpreter.rst, an entry in the concurrency overview, an API reference page and a changelog entry.
  • concurrent.interpreters is added to autodoc_mock_imports, since docs are built on Python < 3.14.

Noticed, not changed here

  • The threads pool has the same cold-shutdown problem fixed here: BasePool.terminate_job raises NotImplementedError from the cold-shutdown handler, and Request only keeps a weak reference to its ApplyResult, which also lacks terminate().
  • chain(...).set(queue=...) doesn't route the tasks published later in the chain to that queue, with any pool.

🤖 Generated with Claude Code

RemiDesgrange and others added 4 commits October 3, 2026 20:58
…in interpreter

Rework the subinterpreter pool so only the trace function and message
data cross into a subinterpreter, while the accept/result callbacks run
in the main interpreter that owns the broker connection.

- Create one subinterpreter per pool slot at start and set each up like
  a spawned prefork child (task registration, logging, tracers,
  worker_process_init), copying the main interpreter's sys.path first.
- Report failures to run a task at all as WorkerLostError.
- Warn that time limits are unsupported; terminate_job raises.
- Fix the pool alias typo and only register it when
  concurrent.interpreters is available (Python 3.14+).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
- terminate_job() now warns instead of raising: it is called on cold
  shutdown and for revoke(terminate=True), where raising aborted the
  shutdown handler. The task runs to completion; a job still waiting
  for an interpreter is cancelled through ApplyResult.terminate().
- Log a hint when a subinterpreter cannot be set up, typically because
  a task module imports an extension module that does not support
  subinterpreters (pydantic-core, gevent, psutil, ...).
- Smoke tests run a worker with --pool=subinterpreter on the dev image
  built for Python 3.14 (new PYTHON_VERSION build arg), with a task
  module that only depends on Celery.
- Document the pool, its limitations, and add it to the API reference.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
- A running subinterpreter cannot be interrupted, so on revoke with
  terminate=True, cold shutdown or soft time limit the pool now asks the
  task to stop through a per-interpreter queue, which task code checks
  with celery.concurrency.subinterpreter.stop_requested().
- Keep ApplyResult objects alive until their job is done: requests only
  hold a weak reference, so terminate() never reached the job.
- Support worker_max_tasks_per_child: replace a subinterpreter after N
  tasks, sending worker_process_shutdown in it before closing it.
- On startup failure, wait for every subinterpreter set up and close
  those created, instead of leaking them.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@auvipy
auvipy self-requested a review November 14, 2026 02:17
@auvipy auvipy added this to the 5.8.0 milestone Nov 14, 2026

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

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants