Skip to content

feat: add worker jobs, index errors, key hints - #688

Merged
uniqueg merged 5 commits into
devfrom
feat/622-worker-index-keys
Nov 4, 2026
Merged

uniqueg merged 5 commits into
devfrom
feat/622-worker-index-keys

Conversation

@uniqueg

@uniqueg uniqueg commented Nov 4, 2026 •

Copy link
Copy Markdown
Member

Summary

Closes #622. Small gaps, as grouped in the issue:

  • Periodic jobs: jobs.periodic sets the schedule of Celery beat, by name, with every or cron, args, kwargs and options. FOCA doesn't start a beat process, and the chart doesn't deploy one yet: docs say to run exactly one.
  • Startup checks in the worker: 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 of runtime_fields may need what the app registers or other services. The static part is validated with the configuration anyway.
  • Typed index errors: IndexConflictError, a ValueError, for conflicts (codes 68, 85, 86) and stored documents violating a unique index (11000), with the cause chained, which proTES's check_unique_task_ids relies on. Other OperationFailures stay errors of PyMongo.
  • Removed keys: keys removed from the configuration in 0.14 fail with a hint. Listed in docs/configuration/index.md.
  • Verify: MongoClient before forks (proWES Create a boiler plate Dockerfile #34): the client created by _create_base_app is closed and replaced at worker_init, and again in each process at worker_process_init (fix: open MongoDB clients after the Celery fork #663). The review ran a real prefork worker with --beat and --max-tasks-per-child=1: no opened before fork output.

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

  • Local checks on Python 3.13 with own MongoDB: ruff, mypy, docs, pytest, 100% coverage.
  • The adversarial review ran a real celery beat and worker (75 task runs), the proTES worker against this branch, and index errors on MongoDB 7.0 (codes 85, 86, 11000, 197, 67).
  • Reviewers: both, two rounds. Round 1 found: duplicates escaping proTES's except ValueError, workers failing on runtime_fields, a cron that never occurs killing beat; all fixed. Round 2 clean.
  • Code 68 wasn't seen on the server used: covered by a test with a mocked error.
  • CI: CI passed on the head before the last fixes; rerun on push.

Declined review findings

  • A helper shared by create_app and _check_worker_config: the calls differ in order and context; check_access_control_config already keeps the main group together.
  • Validating cron fields at config load: they're checked by Celery's own parser in create_celery_app, which also runs in create_app-less workers, naming the job.
  • The mongomock fallback in _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:

  • Add configuration for Celery periodic jobs with interval or cron schedules, task arguments, and execution options.
  • Run applicable access-control validation checks when creating Celery workers.
  • Provide actionable hints when configurations contain keys removed by FOCA.

Bug Fixes:

  • Distinguish MongoDB index conflicts and unique-index violations from unrelated index-creation failures while preserving the original PyMongo cause.
  • Ensure MongoDB clients are reopened safely across worker initialization and process forks.

Documentation:

  • Document periodic jobs, worker startup checks, typed index errors, removed configuration keys, and related migration guidance.

Tests:

  • Add coverage for periodic schedules, invalid cron expressions, worker configuration checks, removed-key hints, and MongoDB index error classification.

uniqueg and others added 3 commits November 4, 2026 09:38
- 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
@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

Expands 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 setup

sequenceDiagram
    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
Loading

Sequence diagram for worker startup configuration checks

sequenceDiagram
    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
Loading

Flow diagram for MongoDB index error classification

flowchart 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]
Loading

Flow diagram for removed configuration key diagnostics

flowchart 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]
Loading

File-Level Changes

Change Details Files
Adds configuration-driven Celery beat schedules with startup validation.
  • Introduces typed periodic job and cron configuration with exactly-one schedule enforcement.
  • Maps interval and cron jobs, task arguments, and execution options into Celery beat_schedule.
  • Rejects invalid or never-occurring cron schedules with job-specific errors.
  • Documents beat deployment expectations and worker startup behavior.
foca/models/config.py
foca/factories/celery_app.py
docs/configuration/jobs.md
tests/factories/test_celery_app.py
Runs configuration-only access-control checks when creating workers.
  • Extracts shared access-control validation used by both applications and workers.
  • Checks access-control groups, admin requirements, required roles, and opt-in roles without computing app-only runtime service information.
  • Adds worker validation coverage and migration guidance.
foca/foca.py
foca/security/access_control/register_access_control.py
docs/configuration/jobs.md
docs/migration-0.21.md
tests/test_foca.py
Introduces typed classification for MongoDB index creation failures.
  • Adds IndexConflictError as a ValueError for index conflicts and duplicate-key violations, preserving the PyMongo exception as the cause.
  • Leaves unrelated OperationFailure cases unchanged.
  • Updates public reference documentation and tests for MongoDB error codes.
foca/database/register_mongodb.py
docs/configuration/db.md
docs/migration-0.21.md
docs/reference.md
tests/database/test_register_mongodb.py
Provides migration hints for configuration keys removed in version 0.14.
  • Detects removed keys before normal model validation and reports replacement guidance or explicit lack of replacement.
  • Documents the supported removed-key mappings and verifies unknown/custom keys remain unaffected.
foca/models/config.py
docs/configuration/index.md
tests/models/test_config.py

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

@uniqueg
uniqueg marked this pull request as ready for review November 4, 2026 09:07

@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 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


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/models/config.py Resolved
@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 (359ae43) to head (815bfe2).

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     
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.

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]>

@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.

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.

Comment thread foca/foca.py Resolved
@uniqueg
uniqueg merged commit 8a64e44 into dev Nov 4, 2026
82 of 84 checks passed
uniqueg added a commit that referenced this pull request Nov 4, 2026
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]>
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.

feat: worker jobs, index errors, removed-key hints

1 participant