Repository navigation
fix: open MongoDB clients after the Celery fork - #663
Conversation
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]>
Reviewer's GuideThe 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 forkssequenceDiagram
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
File-Level Changes
Possibly linked issues
Tips and commandsInteracting with Sourcery
Customizing Your ExperienceAccess your dashboard to:
Getting Help
|
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Codecov Report✅ All modified and coverable lines are covered by tests. 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
Flags with carried forward coverage won't be shown. Click here to find out more. ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
There was a problem hiding this comment.
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
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Closes #659
Summary
Celery prefork children used the
MongoClientthatcreate_celery_app()opened to create indexes; PyMongo warnedMongoClient opened before forkon 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 onworker_init, before the worker forks, so that it forks without the client's threads (the actual hang risk), and onworker_process_initin each pool process, as the main process may have used the client since, and replaces pool processes that end.InvalidOperation;docs/migration-0.21.mdsays what to do. proTES keeps none (checked:get_collection()at call time).docs/configuration/jobs.md, the migration guide, reference entry.No release prep:
docs/releases/0.21.0.mdshould list this under breaking changes.How it was verified
Failing test first:
tests/factories/test_celery_worker_fork.pyruns 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 withworker_process_initremoved. A second test forks, and checks that the child's replacement leaves the parent's client working.Locally (Python 3.13, MongoDB 7.0):
pytestwith coverage: 3385 passed, 1 skipped, 100% (before the last review fixes; afterwardstests/factoriesandtests/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.20of proTES, withfoca-pluginsleft out, as tasks don't load plugins; RabbitMQ 4.3 and MongoDB 7.0), runningtask__resume_tracking: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
start_workerin 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.connectkeyword-only, or creating the client directly inreopen_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:
Bug Fixes:
MongoClient opened before forkwarnings and potential fork-related hangs in prefork workers.Enhancements:
CI:
Documentation:
Tests: