Repository navigation
feat: add worker jobs, index errors, key hints - #688
Conversation
- jobs.periodic sets the schedule of Celery beat. - Workers run the checks of the configuration that apps run. - IndexConflictError tells conflicts of indexes from other failures, which stay errors of PyMongo. - Keys of the configuration that FOCA removed fail with a hint. Co-Authored-By: Claude Opus 5.5 <[email protected]>
From review: stored documents violating a unique index stay ValueErrors, as proTES relies on, now IndexConflictError. Workers don't compute the service info, which can need what apps register. Crons that never occur or fail to parse stop the worker naming the job, and every is bounded. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…keys # Conflicts: # foca/security/access_control/register_access_control.py
Reviewer's GuideExpands Celery worker configuration with validated periodic jobs and configuration-only startup checks, adds precise MongoDB index conflict errors, and improves removed-configuration-key migration diagnostics with corresponding documentation and tests. Sequence diagram for periodic Celery job setupsequenceDiagram
participant Config as Configuration
participant Foca
participant Celery
participant Beat as Celery Beat
participant Task as Task Worker
Config->>Foca: create_celery_app()
Foca->>Celery: _get_beat_entry(name, job)
Celery->>Celery: crontab(...)
Foca->>Celery: set beat_schedule
Beat->>Celery: read beat_schedule
Beat->>Task: dispatch configured task with args, kwargs, options
Sequence diagram for worker startup configuration checkssequenceDiagram
participant Worker as Celery Worker
participant Foca
participant Access as Access Control Checks
participant Celery
Worker->>Foca: create_celery_app()
Foca->>Access: check_access_control_config(access_control, auth)
Foca->>Access: check_opt_in_roles(access_control, cors)
Foca->>Celery: create_celery_app()
Celery-->>Worker: configured worker
Flow diagram for MongoDB index error classificationflowchart TD
A[create_index] --> B{OperationFailure code}
B -->|85, 86, or 11000| C[IndexConflictError]
C --> D[ValueError with PyMongo cause]
B -->|Other code| E[Re-raise original PyMongo error]
Flow diagram for removed configuration key diagnosticsflowchart TD
A[Load configuration] --> B[_find_removed_keys]
B --> C{Removed keys found?}
C -->|Yes| D[Raise ValueError with migration hint]
C -->|No| E[Continue normal configuration validation]
File-Level Changes
Possibly linked issues
Tips and commandsInteracting with Sourcery
Customizing Your ExperienceAccess your dashboard to:
Getting Help
|
There was a problem hiding this comment.
Hey - I've found 2 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="19" />
<code_context>
logger = logging.getLogger(__name__)
+# `IndexOptionsConflict`, `IndexKeySpecsConflict`
+_INDEX_CONFLICT_CODES = (85, 86)
+_DUPLICATE_KEY_CODE = 11000
+
</code_context>
<issue_to_address>
**Legacy index conflicts escape typed handling**
When mongoDB returns error code 68 while creating a configured index that conflicts with an existing index, `_is_index_conflict` treats code 68 (`IndexAlreadyExists`) as an unrelated PyMongo failure, so `_register_database` re-raises `OperationFailure` instead of `IndexConflictError`; callers relying on the documented `ValueError` contract do not recognize the conflict.
Include code 68 in the conflict classification and add a test for it.
</issue_to_address>
### Comment 2
<location path="foca/models/config.py" line_range="171-173" />
<code_context>
+ # Sections given as models are valid already
+ section = data
+ for key in path[:-1]:
+ section = section.get(key) if isinstance(section, dict) else None
+ if isinstance(section, dict) and path[-1] in section:
+ found.append(f"'{'.'.join(path)}': {hint}")
+ return found
+
</code_context>
<issue_to_address>
**Hint for path_out**
The issue asks for removed keys to fail with a hint, but the removed api.specs[].path_out key is omitted. Since the checker only descends through dictionaries, this key inside the api.specs list still gets an ordinary unknown-key error; the migration docs note that modified specifications were never written.
</issue_to_address>Linked issues
#622 feat: worker jobs, index errors, removed-key hints · 6 of 7 met
| # | Requirement | Status | Notes |
|---|---|---|---|
| 1 | Provide configuration-driven periodic Celery jobs using every or cron, with args, kwargs, and options. | ✅ Met | Jobs are modeled in the configuration and registered in Celery's beat_schedule; tests cover interval and cron entries. |
| 2 | Run worker startup configuration checks. | ✅ Met | Worker startup runs the applicable access-control and opt-in-role checks without computing runtime service info. |
| 3 | Use a typed index error to distinguish conflicts from other index-creation failures. | ✅ Met | Index conflicts and duplicate-key violations raise IndexConflictError with the PyMongo error chained; other OperationFailures are re-raised. |
| 4 | Give removed configuration keys a hint instead of a plain unknown-key error. | 🟡 Partly met | The checker covers the listed removed keys, but omits the removed api.specs[].path_out key. |
| 5 | Verify MongoClient handling around worker forks. | ✅ Met | The prefork worker test checks task execution across child processes and asserts there is no “opened before fork” warning. |
| 6 | Add tests for each item and achieve 100% coverage. | ✅ Met | The change includes tests for the features, and the PR reports 100% coverage in its local checks. |
| 7 | Document jobs and configuration changes. | ✅ Met | The jobs and configuration documentation pages cover periodic jobs, startup checks, index errors, and removed-key hints. |
Sourcery assessment
Needs a human reviewer. 2 findings to address first, and when a beat process uses this schedule, it repeatedly invokes the configured task with its configured arguments; if a schedule or task choice is wrong, runs may already have deleted data or triggered other external effects before the schedule is reverted. Reverting stops future runs but cannot undo effects from runs that already happened.
Blocking findings: foca/database/register_mongodb.py:19, foca/models/config.py:173
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## dev #688 +/- ##
=========================================
Coverage 100.00% 100.00%
=========================================
Files 63 63
Lines 8197 8270 +73
=========================================
+ Hits 8197 8270 +73
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:
|
Resolve the migration guide, keeping both sections. Treat the code IndexAlreadyExists as an index conflict, and give the removed key `api.specs[].path_out` a hint too, as a list and as named specs. Co-Authored-By: Claude Opus 5.5 <[email protected]>
There was a problem hiding this comment.
Linked issues
#622 feat: worker jobs, index errors, removed-key hints · 6 of 7 met
| # | Requirement | Status | Notes |
|---|---|---|---|
| 1 | Configure periodic Celery jobs by name. | ✅ Met | Adds jobs.periodic with interval or cron schedules, arguments, keyword arguments, and task options, and assigns it to Celery beat's schedule. |
| 2 | Run the same configuration checks in the worker as in the app. | 🟡 Partly met | Workers run access-control and opt-in-role checks, but do not run other app startup checks, including OpenAPI registration and service-info checks. |
| 3 | Raise a dedicated index-creation exception so apps can distinguish conflicts from connection failures. | ✅ Met | Adds IndexConflictError for recognized index conflicts and duplicate-key violations; other OperationFailures remain PyMongo errors. |
| 4 | Fail on removed configuration keys with a hint about what replaces them. | ✅ Met | Adds removed-key hints, including for api.specs[].path_out in list and named-spec configurations. |
| 5 | Verify that MongoDB clients are safe across worker forks. | ✅ Met | The worker replaces the client around forks, and a real prefork-worker test checks that tasks use post-fork clients without an opened before fork warning. |
| 6 | Add tests for each item and achieve 100% coverage. | ✅ Met | Adds tests for periodic scheduling and validation, worker checks, index-error classification, removed keys, and worker-fork behavior; the PR reports 100% coverage. |
| 7 | Document jobs and configuration. | ✅ Met | Documents periodic jobs and worker checks, as well as removed-key and MongoDB index-error guidance in the configuration and migration pages. |
…keys # Conflicts: # docs/migration-0.21.md
Updates of mongomock aren't atomic: a read can see the new version of the recorded changes before its change, so that the cache misses one. MongoDB's single-document updates are atomic, and the test still runs against it. Failed CI on PR #688. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Summary
Closes #622. Small gaps, as grouped in the issue:
jobs.periodicsets the schedule of Celery beat, by name, witheveryorcron,args,kwargsandoptions. FOCA doesn't start a beat process, and the chart doesn't deploy one yet: docs say to run exactly one.Foca.create_celery_app()runs the checks of the configuration of access control that apps run (check_access_control_config). It doesn't compute the service info: workers don't serve it, and functions ofruntime_fieldsmay need what the app registers or other services. The static part is validated with the configuration anyway.IndexConflictError, aValueError, for conflicts (codes 68, 85, 86) and stored documents violating a unique index (11000), with the cause chained, which proTES'scheck_unique_task_idsrelies on. OtherOperationFailures stay errors of PyMongo.docs/configuration/index.md.MongoClientbefore forks (proWES Create a boiler plate Dockerfile #34): the client created by_create_base_appis closed and replaced atworker_init, and again in each process atworker_process_init(fix: open MongoDB clients after the Celery fork #663). The review ran a real prefork worker with--beatand--max-tasks-per-child=1: noopened before forkoutput.Docs:
docs/configuration/jobs.md,docs/configuration/index.md,docs/configuration/db.md,docs/migration-0.21.md,docs/reference.md.How it was verified
celery beatand worker (75 task runs), the proTES worker against this branch, and index errors on MongoDB 7.0 (codes 85, 86, 11000, 197, 67).except ValueError, workers failing onruntime_fields, a cron that never occurs killing beat; all fixed. Round 2 clean.CI passedon the head before the last fixes; rerun on push.Declined review findings
create_appand_check_worker_config: the calls differ in order and context;check_access_control_configalready keeps the main group together.create_celery_app, which also runs increate_app-less workers, naming the job._is_index_conflict(quality round 2, low): it only applies to errors without a code, and the docstring says what it's for.Open questions
None.
🤖 Generated with Claude Code
Summary by Sourcery
Add worker job scheduling and startup validation while improving index error reporting, migration guidance, and fork-safe MongoDB client handling.
New Features:
Bug Fixes:
Documentation:
Tests: