Skip to content

fix(db)!: make task identifiers unique - #258

Merged
uniqueg merged 6 commits into
devfrom
fix/unique-task-ids
Oct 23, 2026
Merged

uniqueg merged 6 commits into
devfrom
fix/unique-task-ids

Conversation

@uniqueg

@uniqueg uniqueg commented Oct 23, 2026 •

Copy link
Copy Markdown
Member

Summary

Task identifiers are unique in the database. The only unique index of the tasks was on task_id and worker_id, fields that don't identify tasks (identifiers are stored as task.id), so the retry on duplicate keys when creating tasks was dead code, and two concurrent requests drawing the same identifier could both store a task under it, giving both owners access to both tasks (#248, raised by Sourcery on #250).

  • Indexes (config.yaml, FOCA's DB index config): a unique index on task.id (not sparse), and an index on worker_id, which Celery workers look tasks up by.
  • Migration on startup: the index of earlier versions (task_id_1_worker_id_1) is dropped (idempotent, also with several instances starting at once). While stored tasks share identifiers, the index can't be created: the API and the Celery workers refuse to start, naming the shared identifiers (up to 10) and the number of tasks of each. No task is changed or dropped; other failing indexes keep FOCA's error.
  • Task creation: the task is stored before its owner gets the owner role (was: granted before storing, revoked on failure, per feat(access-control)!: own tasks per user #250). The unique index now reserves the identifier atomically, so a request losing the race for an identifier gets another one, and never has a role on the task of someone else, not even briefly. If the role can't be granted, the task is deleted, and roles granted partly are revoked. A crash between storing and granting leaves a task without owner, which nobody can access (see Task owners in the operations docs).
  • Docs: upgrading notes ("Task identifiers"): how operators find and resolve shared identifiers (back up, keep one task per identifier, delete or re-identify the others, fix the owner roles).

Breaking: proTES refuses to start while stored tasks share identifiers.

How it was verified

  • coverage run -m pytest: 554 passed, 76 skipped (chart tests, without the library chart locally), 100% coverage.
  • pytest against a real MongoDB 7.0 (MONGODB_TEST_URI): 554 passed, 76 skipped; real MongoDB raises DuplicateKeyError on index creation, as mongomock does.
  • pre-commit run --all-files (ruff, mypy, semgrep, ast-grep, gitleaks, …): passed.
  • mkdocs build --strict: passed.
  • The new tests fail without the fix: the concurrent-identifier tests with the old index, the same-owner case with the old revocation.
  • Reviews: adversarial and quality subagents, 2 rounds. Round 1 found no high findings; mediums and lows (concurrent legacy index drop, uniqueness of worker_id, the Celery worker not reporting duplicates, revocation if the owner check fails, docs steps) are fixed. Round 2 found only lows, fixed except as declined below.
  • Sourcery: 4 findings; 3 fixed (grant after storing, worker_id not unique, reporting identifiers that aren't strings), 1 declined (below).
  • CI: all checks passed, also after the Sourcery fixes (mongomock and MongoDB 7.0 tests, static analysis, docs, Helm chart, Compose smoke test, image scan, CodeQL, Codecov).

Declined review findings

  • Redundant None-guards in check_unique_task_ids (quality, medium): kept. FOCA's config models are optional at each level, and an AttributeError at startup would mask FOCA's original error.

  • Tests coupled to the wording of the error message, and fake FOCA configs (quality, low): acceptable; the real path is tested with the app, too.

  • Drop the index of earlier versions when Celery workers start, too (Sourcery, low): the index is harmless, and dropped when the API starts, which runs alongside the workers.

Open questions

None.

Closes #248

🤖 Generated with Claude Code

uniqueg and others added 5 commits October 23, 2026 16:50
The only unique index of the tasks was on `task_id` and `worker_id`,
fields that don't identify tasks, so the retry on duplicate keys when
creating tasks was dead code, and two concurrent requests drawing the
same identifier could both store a task under it (and both owners got
access to both tasks).

- Replace the index with a unique index on `task.id` (not sparse) and
  an index on `worker_id`, which Celery workers look tasks up by.
- Drop the index of earlier versions on startup.
- If stored tasks share identifiers, FOCA can't create the index:
  proTES refuses to start, naming the shared identifiers (up to 10)
  and the number of tasks of each, and changes no task.
- When the insert loses a race, the owner role on the lost identifier
  is revoked, unless the stored task has the same owner, whose role it
  then is (it was revoked before, orphaning that task).

BREAKING CHANGE: proTES refuses to start while stored tasks share
identifiers; resolve them as described in the upgrading notes.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Upgrading notes: the unique index on task identifiers, the startup
refusal while stored tasks share identifiers, and how operators find
and resolve the duplicates (back up, keep one task per identifier,
delete or rename the others, fix the owner roles).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
From the review of the branch:

- Keep worker identifiers unique (as the index of earlier versions
  did), as tasks are updated by worker identifier.
- Report shared task identifiers when Celery workers start, too.
- Don't fail if another instance drops the index of earlier versions
  at the same time.
- Revoke the owner role on a lost identifier if checking the owner of
  the stored task fails.
- Move the duplicate check to `pro_tes.utils.db`; make the upgrading
  steps copyable and complete, and name the database of the tasks.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Documents edited by hand may lack `worker_id`; with a sparse index,
they don't block the start, as the index of earlier versions didn't.
Name the task collection by constant everywhere, and clarify the
comment on lost identifiers.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@sourcery-ai

sourcery-ai Bot commented Oct 23, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

The PR enforces unique task identifiers at the MongoDB level, migrates legacy indexes safely, blocks startup with actionable duplicate-data diagnostics, and retries concurrent task creation while correctly managing owner roles; documentation and comprehensive tests cover upgrade and race scenarios.

Sequence diagram for unique task creation under concurrent requests

sequenceDiagram
    participant RequestA
    participant RequestB
    participant API
    participant MongoDB
    participant AccessControl

    RequestA->>API: _write_doc_to_db()
    RequestB->>API: _write_doc_to_db()
    API->>AccessControl: grant task owner role
    API->>MongoDB: insert task with task.id
    API->>AccessControl: grant task owner role
    API->>MongoDB: insert task with task.id
    MongoDB-->>API: insert succeeds
    MongoDB-->>API: DuplicateKeyError
    API->>MongoDB: count_documents(task.id, user_id)
    alt stored task has same owner
        MongoDB-->>API: owner match
    else owner differs or check fails
        API->>AccessControl: remove_task_owner()
    end
    API-->>RequestB: retry with another identifier
Loading

Entity relationship diagram for task identifier uniqueness

erDiagram
    TASK {
        string task_id PK
        string worker_id UK
        string user_id
    }
    TASK ||--o| TASK_IDENTIFIER : "unique task.id"
    TASK ||--o| WORKER_IDENTIFIER : "unique sparse worker_id"
Loading

File-Level Changes

Change Details Files
Replaced the ineffective legacy task index with database-enforced uniqueness for task identifiers and sparse uniqueness for Celery worker identifiers.
  • Configured unique task.id and unique sparse worker_id indexes.
  • Added shared database and collection constants used by task access paths.
  • Dropped the legacy task_id_1_worker_id_1 index idempotently, including concurrent startup handling.
pro_tes/config.yaml
pro_tes/utils/db.py
pro_tes/app.py
pro_tes/ga4gh/tes/task_runs.py
pro_tes/tasks/track_task_progress.py
Added startup validation and actionable migration failures when existing data prevents creation of the unique task identifier index.
  • Detects duplicate and missing task identifiers via aggregation and reports counts for up to ten identifiers.
  • Makes both the API and Celery worker refuse startup for task identifier collisions while preserving FOCA errors for unrelated index failures.
  • Documents backup, duplicate resolution, re-identification, deletion, and owner-role repair procedures.
pro_tes/utils/db.py
pro_tes/app.py
pro_tes/celery_worker.py
docs/upgrading.md
Made task creation safe against concurrent identifier allocation and corrected owner-role cleanup after duplicate-key races.
  • Retries with a new identifier after a unique-index collision.
  • Retains the role when the winning stored task belongs to the same owner.
  • Revokes the role when ownership differs or the ownership check fails.
pro_tes/ga4gh/tes/task_runs.py
Added coverage for index configuration, migration behavior, startup failures, concurrent races, role cleanup, and non-task index errors.
  • Tests duplicate discovery, capped error reporting, legacy-index removal, and concurrent index-drop behavior.
  • Verifies API and Celery startup handling and preservation of unrelated FOCA failures.
  • Exercises same-owner, different-owner, and failed-owner-check creation races.
tests/ga4gh/tes/test_server.py
tests/test_app.py
tests/utils/test_db.py

Assessment against linked issues

Issue Objective Addressed Explanation
#248 Enforce database-wide uniqueness for stored task identifiers using a unique, non-sparse index on task.id, so concurrent task creations with the same identifier cannot both be stored. ✅
#248 When a concurrent creation loses the uniqueness race, retry with another identifier while preserving or revoking owner roles appropriately. ✅
#248 Document how to find and resolve duplicate identifiers in existing data before the new index can be created. ✅

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

@read-the-docs-community

read-the-docs-community Bot commented Oct 23, 2026 •

Copy link
Copy Markdown

Documentation build overview

📚 proTES | 🛠️ Build #35360129 | 📁 Comparing a8a1fc9 against latest (7ca49bb)

  🔍 Preview build  

2 files changed
± reference/index.html
± upgrading/index.html

@codecov

codecov Bot commented Oct 23, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 100.00%. Comparing base (7ca49bb) to head (a8a1fc9).

Additional details and impacted files
@@            Coverage Diff            @@
##               dev      #258   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files           26        26           
  Lines         1517      1570   +53     
=========================================
+ Hits          1517      1570   +53     

☔ 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 October 23, 2026 16:36

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

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

## Individual Comments

### Comment 1
<location path="pro_tes/ga4gh/tes/task_runs.py" line_range="486-503" />
<code_context>
+                # Another request stored a task with the identifier first
</code_context>
<issue_to_address>
**Concurrent owner briefly accesses another task**

When two requests with different owners concurrently choose the same task identifier, the losing request grants its owner role before the insert detects the duplicate, so for the interval before `count_documents` and `remove_task_owner` run, both owners can access the stored task. A request in that interval reads or cancels another owner's task.

Prevent the losing request's role from becoming effective on the existing task, for example by making the identifier reservation and ownership update atomic.
</issue_to_address>

### Comment 2
<location path="pro_tes/config.yaml" line_range="108" />
<code_context>
-                task_id: 1
+                task.id: 1
+              options:
+                "unique": True
+            # Celery workers find tasks by worker identifier (sparse, as
+            # documents edited by hand may lack it)
</code_context>
<issue_to_address>
**Legacy worker collisions block startup**

When the collection contains repeated `worker_id` values paired with different `task_id` values, the earlier compound unique index permits the same `worker_id` when the documents have different `task_id` values. The new standalone unique index then fails during app creation for that stored data, so proTES refuses to start with FOCA’s generic index error and no migration guidance for the collisions.

Either detect and explain duplicate worker IDs before startup, with migration steps to repair them, or avoid claiming the legacy compound index guarantees standalone worker-ID uniqueness.
</issue_to_address>

### Comment 3
<location path="pro_tes/celery_worker.py" line_range="35" />
<code_context>
+        ValueError: A configured index conflicts with an existing index.
+    """
+    try:
+        return foca.create_celery_app()
+    except ValueError as exc:
+        check_unique_task_ids(foca=foca, exc=exc)
</code_context>
<issue_to_address>
**Legacy index survives worker startup**

When a Celery worker starts without the API entry point running, `create_celery_app` creates the configured indexes but never drops `task_id_1_worker_id_1`, so a Celery-only startup leaves the earlier-version index in the database.

Drop the legacy index from the Celery startup path as well, after the configured indexes are created.
</issue_to_address>

### Comment 4
<location path="pro_tes/utils/db.py" line_range="124-126" />
<code_context>
+        {"$group": {"_id": "$task.id", "count": {"$sum": 1}}},
+        {"$match": {"count": {"$gt": 1}}},
+    ]
+    duplicates = {
+        group["_id"]: group["count"] for group in collection.aggregate(pipeline)
+    }
+    return dict(sorted(duplicates.items(), key=lambda item: str(item[0])))
+
</code_context>
<issue_to_address>
**Duplicate diagnostics are lost**

When duplicate malformed `task.id` values have an array or object as their MongoDB aggregation group key, the comprehension uses the unhashable group key in a Python dictionary, raising `TypeError` before proTES can report the conflicting identifiers, so operators see a generic startup failure instead of the duplicate-identifier diagnostic and migration guidance.

Convert aggregation group keys to a hashable representation before using them as Python dictionary keys.
</issue_to_address>

Sourcery assessment

Needs a human reviewer. 3 findings to address first, and if stored tasks already share an identifier, the new unique index prevents the API and workers from starting until operators manually delete or rename tasks and adjust owner roles. Reverting the code does not undo those data and access-control changes.

Blocking findings: pro_tes/ga4gh/tes/task_runs.py:503, pro_tes/config.yaml:108, pro_tes/utils/db.py:126


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

Comment thread pro_tes/ga4gh/tes/task_runs.py Resolved
Comment thread pro_tes/config.yaml Resolved
Comment thread pro_tes/celery_worker.py Resolved
Comment thread pro_tes/utils/db.py Resolved
From the review by Sourcery:

- Store a task before granting its owner the owner role. The unique
  index on `task.id` now reserves the identifier atomically, so a
  request that loses the race for an identifier never has a role on
  the task of someone else, not even briefly. If the role can't be
  granted, the task is deleted, and roles granted partly are revoked.
- Don't make worker identifiers unique: stored tasks of earlier
  versions might share them, which would block the start with no
  guidance, and they are random Celery identifiers anyway.
- Report task identifiers that aren't strings (e.g., objects) by their
  representation, instead of failing to report them.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@uniqueg
uniqueg merged commit e38b4de into dev Oct 23, 2026
18 checks passed
@uniqueg
uniqueg deleted the fix/unique-task-ids branch October 23, 2026 16:55
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: make task identifiers unique in the database

1 participant