Skip to content

fix: open MongoDB clients after the Celery fork - #663

Merged
uniqueg merged 5 commits into
devfrom
fix/mongo-after-celery-fork
Nov 4, 2026
Merged

uniqueg merged 5 commits into
devfrom
fix/mongo-after-celery-fork

Conversation

@uniqueg

@uniqueg uniqueg commented Nov 4, 2026 •

Copy link
Copy Markdown
Member

Closes #659

Summary

Celery prefork children used the MongoClient that create_celery_app() opened to create indexes; PyMongo warned MongoClient opened before fork on their first operation.

  • reopen_mongodb() replaces an app's client and the handles of its databases and collections, and closes the previous client. New clients connect on first use, so that this doesn't block (Celery kills pool processes whose start takes over 4 seconds).
  • create_celery_app() calls it on worker_init, before the worker forks, so that it forks without the client's threads (the actual hang risk), and on worker_process_init in each pool process, as the main process may have used the client since, and replaces pool processes that end.
  • Breaking for apps that keep handles: clients, databases and collections kept from before raise InvalidOperation; docs/migration-0.21.md says what to do. proTES keeps none (checked: get_collection() at call time).
  • Docs: "MongoDB in workers" in docs/configuration/jobs.md, the migration guide, reference entry.

No release prep: docs/releases/0.21.0.md should list this under breaking changes.

How it was verified

Failing test first: tests/factories/test_celery_worker_fork.py runs a real prefork worker (real MongoDB, broker on the file system, --max-tasks-per-child=1, main process uses its client). It failed before the fix with the warning, and fails with worker_process_init removed. A second test forks, and checks that the child's replacement leaves the parent's client working.

Locally (Python 3.13, MongoDB 7.0):

  • Full pytest with coverage: 3385 passed, 1 skipped, 100% (before the last review fixes; afterwards tests/factories and tests/database: 100 passed).
  • ruff check, ruff format --check, mypy, ast-grep scan, semgrep: pass. mkdocs build --strict: passes.

Real proTES worker (branch build/foca-0.20 of proTES, with foca-plugins left out, as tasks don't load plugins; RabbitMQ 4.3 and MongoDB 7.0), running task__resume_tracking:

FOCA     pool                               tasks ok  hangs  warnings
0.20.0   prefork --concurrency=2               21/21      0         2
0.20.0   prefork + --max-tasks-per-child=1   401/401      0       401
branch   prefork --concurrency=2               21/21      0         0
branch   prefork + --max-tasks-per-child=1   401/401      0         0
branch   solo                                  21/21      0         0
branch   threads                               21/21      0         0

New CI check: the integration job fails if the gateway example's worker logs the warning.

CI: all checks pass, on Python 3.11 to 3.15, with the lowest dependencies, and the integration job with the new check (Python 3.13 and 3.15).

Declined review findings

  • Not closing the previous client, so that kept handles keep working with the warning (adversarial, medium): the parent's monitor threads at the fork are the risk that PyMongo warns of. Handled with the migration guide instead.
  • Refreshing kept handles of workers started in an app's process, e.g., start_worker in downstream tests (adversarial, low): documented; such a worker has no fork to protect against, but fixing it would need another path for the Casbin adapter.
  • Making connect keyword-only, or creating the client directly in reopen_mongodb() (quality, low): matches the signatures around it.

🤖 Generated with Claude Code

Summary by Sourcery

Reopen MongoDB clients around Celery worker forks to make prefork workers safe with PyMongo.

New Features:

  • Add MongoDB client reopening around Celery worker forks to ensure each worker process uses a post-fork client.

Bug Fixes:

  • Prevent PyMongo MongoClient opened before fork warnings and potential fork-related hangs in prefork workers.

Enhancements:

  • Expose MongoDB client reopening as a documented database utility and recreate database and collection handles when clients are replaced.

CI:

  • Fail gateway integration checks when worker logs indicate a MongoDB client was opened before fork.

Documentation:

  • Document MongoDB client lifecycle requirements in workers and provide 0.21.0 migration guidance for applications retaining database handles.

Tests:

  • Add unit and integration coverage for client replacement, Celery signal handling, parent-client continuity, and real prefork workers.

uniqueg and others added 2 commits November 4, 2026 03:24
Celery prefork children inherited the client that create_celery_app()
opened to create indexes, and PyMongo warned "MongoClient opened before
fork" on their first operation. A worker now replaces the client just
before it forks its pool (worker_init), so that it forks without the
client's threads, and each pool process replaces it again on start
(worker_process_init), as the worker may have used it since. New clients
connect on first use, so that the handlers don't block.

Closes #659

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Add the upgrade note for kept handles, list reopen_mongodb in the
reference, connect the worker's handlers once per configuration, and
make the tests and the CI check of the worker log more telling.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@uniqueg uniqueg added this to the v0.21.0 milestone Nov 4, 2026
@sourcery-ai

sourcery-ai Bot commented Nov 4, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

The PR prevents MongoDB clients from being inherited across Celery prefork boundaries by lazily replacing the app client and registered handles before worker forking and again in each pool process, while adding real-worker regression coverage, CI warning detection, and migration documentation for the resulting invalidation of retained MongoDB handles.

Sequence diagram for MongoDB client replacement around Celery forks

sequenceDiagram
    participant App as Flask app
    participant Celery as Celery worker
    participant Mongo as MongoDB client
    participant Pool as Pool process

    App->>Celery: create_celery_app()
    App->>Mongo: get_mongo_client()
    Celery->>Celery: worker_init
    Celery->>Mongo: reopen_mongodb()
    Mongo-->>Celery: Replace client, databases, and collections
    Celery->>Mongo: previous.close()
    Celery->>Pool: Fork pool process
    Pool->>Pool: worker_process_init
    Pool->>Mongo: reopen_mongodb()
    Mongo-->>Pool: Replace client and registered handles
    Pool->>Mongo: Connect on first use
Loading

File-Level Changes

Change Details Files
Reopen MongoDB clients around Celery worker forks to prevent PyMongo pre-fork warnings and inherited client threads.
  • Added lazy client recreation that updates registered database and collection handles and closes the old client.
  • Hooked client reopening into Celery worker initialization and pool-process initialization, with duplicate signal registration avoided.
  • Extended client factory APIs with a connect flag so replacement clients do not connect or start threads before use.
foca/database/register_mongodb.py
foca/factories/celery_app.py
Added coverage for client replacement behavior and real Celery prefork execution.
  • Unit-tested handle replacement, closure, lazy connection, unregistered handles, and signal behavior.
  • Added integration tests using a real MongoDB and prefork worker, including process recycling and parent-client continuity.
  • Updated test mocks and fixtures for the new client factory signature.
tests/database/test_register_mongodb.py
tests/factories/test_celery_app.py
tests/factories/test_celery_worker_fork.py
tests/conftest.py
tests/security/access_control/test_register_casbin_enforcer.py
Documented the worker behavior as a breaking change and added CI protection against regressions.
  • Documented that retained clients, databases, and collections become invalid after replacement and provided migration guidance.
  • Added the new migration guide and linked it from the README, documentation index, changelog, navigation, and API reference.
  • Added an integration-log check that fails CI when workers emit the pre-fork MongoDB warning.
docs/configuration/jobs.md
docs/migration-0.21.md
docs/changelog.md
docs/index.md
docs/reference.md
mkdocs.yml
README.md
.github/workflows/ci.yml

Possibly linked issues


Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@codecov

codecov Bot commented Nov 4, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 100.00%. Comparing base (2b383e1) to head (8352c06).

Additional details and impacted files
@@            Coverage Diff            @@
##               dev      #663   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files           56        56           
  Lines         7198      7223   +25     
=========================================
+ Hits          7198      7223   +25     
Flag Coverage Δ
test_unit 100.00% <100.00%> (ø)

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@uniqueg
uniqueg marked this pull request as ready for review November 4, 2026 03:14

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey - I've found 7 issues

Prompt for AI Agents
Please address the comments from this code review:

## Individual Comments

### Comment 1
<location path="foca/database/register_mongodb.py" line_range="66-69" />
<code_context>
+        if db_conf.client is None:
+            continue
+        db_conf.client = client[db_conf.client.name]
+        for coll_conf in (db_conf.collections or {}).values():
+            if coll_conf.client is not None:
+                coll_conf.client = db_conf.client[coll_conf.client.name]
+    previous.close()
+    logger.debug("Reopened MongoDB client.")
+
</code_context>
<issue_to_address>
**Worker access control uses closed client**

When a prefork worker task uses FOCA’s access-control adapter after `worker_process_init`, `reopen_mongodb()` replaces the configured database and collection handles and closes the previous client, but the app’s `casbin_adapter` still holds its original collection. A task that uses FOCA access control then queries or writes through that closed client and raises `pymongo.errors.InvalidOperation`.

Rebuild or rebind the access-control adapter to the replacement client when reopening MongoDB handles.
</issue_to_address>

### Comment 2
<location path="foca/database/register_mongodb.py" line_range="65-68" />
<code_context>
+    for db_conf in (conf.dbs or {}).values():
+        if db_conf.client is None:
+            continue
+        db_conf.client = client[db_conf.client.name]
+        for coll_conf in (db_conf.collections or {}).values():
+            if coll_conf.client is not None:
+                coll_conf.client = db_conf.client[coll_conf.client.name]
+    previous.close()
+    logger.debug("Reopened MongoDB client.")
</code_context>
<issue_to_address>
**Plugin stores retain closed collections**

When the app creates a Mongo-backed plugin store before the Celery worker reopens its MongoDB client, and a task uses that store, when a Celery task uses a Mongo-backed plugin store created with the app, `PluginHost`'s `MongoStoreBackend` still holds the pre-reopen collection. Its operations raise `pymongo.errors.InvalidOperation`, so plugin store access in the worker fails.

Refresh or recreate the plugin store backend when the worker's MongoDB handles are reopened, or resolve its collection at use time.
</issue_to_address>

### Comment 3
<location path="foca/factories/celery_app.py" line_range="107-108" />
<code_context>
+        # of them, as the worker may have used the client since (it replaces
+        # processes that end, while it runs)
+        uid = f"foca-reopen-mongodb-{id(db)}"
+        worker_init.connect(reopen_client, weak=False, dispatch_uid=uid)
+        worker_process_init.connect(reopen_client, weak=False, dispatch_uid=uid)
+        logger.debug("MongoDB client set to be reopened around worker forks.")
+
</code_context>
<issue_to_address>
**Other apps lose usable handles**

When multiple FOCA Celery apps have registered handlers in one process and a worker for one app starts, each process-wide signal invokes every registered `reopen_client`, and the callbacks ignore the sender, so `reopen_mongodb` closes and replaces clients belonging to other apps. Callers retaining those apps’ old handles then get `InvalidOperation`.

Ensure each callback reopens only the MongoDB client belonging to the Celery app whose worker is starting.
</issue_to_address>

### Comment 4
<location path="foca/factories/celery_app.py" line_range="107" />
<code_context>
+        # of them, as the worker may have used the client since (it replaces
+        # processes that end, while it runs)
+        uid = f"foca-reopen-mongodb-{id(db)}"
+        worker_init.connect(reopen_client, weak=False, dispatch_uid=uid)
+        worker_process_init.connect(reopen_client, weak=False, dispatch_uid=uid)
+        logger.debug("MongoDB client set to be reopened around worker forks.")
</code_context>
<issue_to_address>
**Fork inherits a reopened client**

When an application has a `worker_init` receiver registered after FOCA's that accesses MongoDB, a later `worker_init` receiver can use the replacement client and start its monitoring threads before Celery forks; the child then inherits a client opened before that fork, so the fork-safety problem remains.

Reopen the client at a pre-fork hook that runs after worker initialization handlers, or otherwise ensure no later handler can use it before the fork.
</issue_to_address>

### Comment 5
<location path=".github/workflows/ci.yml" line_range="395" />
<code_context>
+      - name: Check worker for MongoDB clients opened before fork
+        working-directory: examples/gateway
+        run: |
+          if docker compose logs worker | grep 'opened before fork'; then
+            echo "A MongoDB client is used across forks of the worker" >&2
+            exit 1
</code_context>
<issue_to_address>
**CI skips failed log checks**

When `docker compose logs worker` exits unsuccessfully without output matching `opened before fork`, the conditional treats the pipeline’s nonzero status as “no warning,” so the check passes without verifying the worker logs and CI reports success.

Make the check fail when `docker compose logs worker` fails, separately from checking whether its output contains the warning.
</issue_to_address>

### Comment 6
<location path="foca/factories/celery_app.py" line_range="106-108" />
<code_context>
+        # forks without the client's threads; `worker_process_init`: in each
+        # of them, as the worker may have used the client since (it replaces
+        # processes that end, while it runs)
+        uid = f"foca-reopen-mongodb-{id(db)}"
+        worker_init.connect(reopen_client, weak=False, dispatch_uid=uid)
+        worker_process_init.connect(reopen_client, weak=False, dispatch_uid=uid)
+        logger.debug("MongoDB client set to be reopened around worker forks.")
+
</code_context>
<issue_to_address>
**Discarded apps retain MongoDB resources**

When a long-lived process repeatedly creates and discards Celery apps with distinct database configurations, the process-wide signals retain each `reopen_client` closure and its `db`, keeping discarded configurations and MongoDB clients alive and consuming memory and client resources for the process lifetime.

Disconnect each app’s signal receivers when that app is discarded so its closure and database configuration can be released.
</issue_to_address>

### Comment 7
<location path="docs/changelog.md" line_range="14" />
<code_context>
 - [0.18.0](releases/0.18.0.md)

 Breaking changes and how to adapt apps to them are described in
+[Migrating to 0.21.0](migration-0.21.md),
 [Migrating to 0.20.0](migration-0.20.md),
 [Migrating to 0.18.0](migration-0.18.md),
</code_context>
<issue_to_address>
**Breaking change absent from release notes**

When FOCA 0.21.0 is released without adding the noted release entry, the changelog links the migration guide, but without a curated 0.21.0 release note the MongoDB client-breaking change is not listed in the release notes where users look for release-specific changes.

Add the MongoDB client change to `docs/releases/0.21.0.md` under breaking changes.
</issue_to_address>

Linked issues

#659 fix: open MongoDB clients after the Celery fork · 2 of 2 met

# Requirement Status Notes
1 Worker children open their own MongoDB client after the fork, or the client is not opened before the fork. ✅ Met Celery's worker_init and worker_process_init handlers replace the client, and the real prefork-worker test exercises tasks in forked processes.
2 No warning from PyMongo in a worker. ✅ Met The real-worker test asserts its log contains no “opened before fork” warning; CI also checks the gateway worker log.

Sourcery assessment

Approval pending. 6 findings to address first.

Blocking findings: foca/database/register_mongodb.py:69, foca/database/register_mongodb.py:68, foca/factories/celery_app.py:108, foca/factories/celery_app.py:107, .github/workflows/ci.yml:395, and 1 more


Sourcery is free for open source - if you like our reviews please consider sharing them ✨

Comment thread foca/database/register_mongodb.py Resolved
Comment thread foca/database/register_mongodb.py Resolved
Comment thread foca/factories/celery_app.py Resolved
Comment thread foca/factories/celery_app.py Resolved
Comment thread .github/workflows/ci.yml Resolved
Comment thread foca/factories/celery_app.py Resolved
Comment thread docs/changelog.md Resolved
@uniqueg
uniqueg merged commit 4ab71dd into dev Nov 4, 2026
56 checks passed
@uniqueg
uniqueg deleted the fix/mongo-after-celery-fork branch November 4, 2026 03:36
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.

fix: open MongoDB clients after the Celery fork

1 participant