Repository navigation
fix(db)!: make task identifiers unique - #258
Conversation
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]>
Reviewer's GuideThe 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 requestssequenceDiagram
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
Entity relationship diagram for task identifier uniquenesserDiagram
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"
File-Level Changes
Assessment against linked issues
Possibly linked issues
Tips and commandsInteracting with Sourcery
Customizing Your ExperienceAccess your dashboard to:
Getting Help
|
Codecov Report✅ All modified and coverable lines are covered by tests. 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. 🚀 New features to boost your workflow:
|
There was a problem hiding this comment.
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
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]>
Summary
Task identifiers are unique in the database. The only unique index of the tasks was on
task_idandworker_id, fields that don't identify tasks (identifiers are stored astask.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).config.yaml, FOCA's DB index config): a unique index ontask.id(not sparse), and an index onworker_id, which Celery workers look tasks up by.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.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.pytestagainst a real MongoDB 7.0 (MONGODB_TEST_URI): 554 passed, 76 skipped; real MongoDB raisesDuplicateKeyErroron index creation, as mongomock does.pre-commit run --all-files(ruff, mypy, semgrep, ast-grep, gitleaks, …): passed.mkdocs build --strict: passed.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.worker_idnot unique, reporting identifiers that aren't strings), 1 declined (below).Declined review findings
Redundant None-guards in
check_unique_task_ids(quality, medium): kept. FOCA's config models are optional at each level, and anAttributeErrorat 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