Repository navigation
feat: keep expired invitations for a set time - #335
Conversation
People who never accepted dropped out of sight at once. Keep expired invitations that weren't accepted, list them with a status, allow DELETE on them, and remove them automatically after `keep_expired_days` (default 30, 0 to 365). Accepted ones are hidden by default and removed on expiry, as before; the limit still counts them, and its error now says so. As the days can change and MongoDB refuses a changed TTL on the same key, the app sets that index on startup, which also replaces the old one. A partial TTL index in the config removes accepted invitations on expiry. Closes #332 Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_011FSoqMUX3EU35poH13xMgG
Dropping and creating the index let workers starting together abort each other's index builds. Use `collMod`, which is atomic and needs no rebuild. Log changes as warnings, as the last instance to start sets the value, and correct docs and log lines for removing expired invitations. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_011FSoqMUX3EU35poH13xMgG
The role `readWrite`, the only one the chart gives the app, doesn't allow `collMod`, so every authenticated deployment would have crashed on upgrade. Drop and create the index, as that role allows, and try again when concurrent starts interfere with each other. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_011FSoqMUX3EU35poH13xMgG
Reviewer's GuideThe PR changes invitation persistence from immediate deletion to configurable retention for unaccepted expired invitations, updates the API and documentation to expose lifecycle status safely, and manages the corresponding MongoDB TTL indexes at startup with upgrade and concurrency safeguards. Sequence diagram for invitation listing and lifecyclesequenceDiagram
actor Owner
participant API
participant MongoDB
Owner->>API: GET /services/{serviceId}/invitations
API->>MongoDB: Find unaccepted invitations
MongoDB-->>API: Open and expired invitations
API->>API: _status(invitation)
API-->>Owner: Invitations with status and no token
Owner->>API: GET /services/{serviceId}/invitations?include_accepted=true
API->>MongoDB: Find unaccepted or unexpired accepted invitations
MongoDB-->>API: Matching invitations
API->>API: _serve(invitation)
API-->>Owner: Invitations including accepted status
Owner->>API: DELETE /services/{serviceId}/invitations/{invitationId}
API->>MongoDB: find_one_and_delete(unaccepted invitation)
MongoDB-->>API: Deleted open or expired invitation
API-->>Owner: Revoked or removed invitation
Sequence diagram for invitation acceptance after expirysequenceDiagram
actor User
participant API
participant MongoDB
User->>API: POST /invitations/accept
API->>MongoDB: Find invitation matching token and _unexpired()
MongoDB-->>API: No matching unexpired invitation
API-->>User: 404 Not Found
Note over MongoDB: Expired unaccepted invitation remains stored until TTL removal
File-Level Changes
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 #335 +/- ##
=========================================
Coverage 100.00% 100.00%
=========================================
Files 22 22
Lines 2375 2418 +43
=========================================
+ Hits 2375 2418 +43 ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
There was a problem hiding this comment.
Hey - I've found 3 issues
Prompt for AI Agents
Please address the comments from this code review:
## Individual Comments
### Comment 1
<location path="cloud_registry/utils.py" line_range="83-84" />
<code_context>
+ return
+ try:
+ if index is not None:
+ collection.drop_index(name)
+ collection.create_index([(field, 1)], expireAfterSeconds=seconds)
+ except OperationFailure as exc:
+ if exc.code not in TTL_INDEX_RACES or attempt == TTL_INDEX_ATTEMPTS:
</code_context>
<issue_to_address>
**Retention index can disappear**
When the process stops or index creation fails after the old index has been dropped, `set_ttl_index()` drops the existing TTL index before creating its replacement, so a crash or failed create leaves no general retention index. Surviving app instances then retain expired unaccepted invitations beyond the configured period until a later successful startup repairs the index.
Make index replacement recoverable after a failed create, or ensure a later-running instance detects and repairs a missing retention index.
</issue_to_address>
### Comment 2
<location path="cloud_registry/ga4gh/registry/invitations.py" line_range="245" />
<code_context>
"id": invitation["_id"],
"service_id": invitation["service_id"],
"role": invitation["role"],
+ "status": _status(invitation),
"created_by": invitation["created_by"],
"created_at": format_time(invitation["created_at"]),
</code_context>
<issue_to_address>
**Unusable invitations shown as open**
When the creator of an unaccepted invitation loses permission to grant its role before the invitation expires, `_status()` checks only acceptance and expiry, while `_creator_may_grant()` is checked only during acceptance. An invitation whose creator has lost permission to grant its role is therefore listed as `open` even though accepting it returns 404, so owners see a misleading status.
Ensure invitations whose creators can no longer grant their roles are not served with `open` status, or revise the status contract to account for that state.
</issue_to_address>
### Comment 3
<location path="tests/test_invitations.py" line_range="517-518" />
<code_context>
+ for _ in range(5):
+ created = invite(client, service_id).get_json()
+ with ThreadPoolExecutor(max_workers=2) as pool:
+ accepting = pool.submit(accept, client, created["token"])
+ revoking = pool.submit(revoke_invitation, client, service_id, created["id"])
+ outcome = (accepting.result().status_code, revoking.result().status_code)
+ assert outcome in ((200, 409), (404, 200))
</code_context>
<issue_to_address>
**Concurrent race goes undetected**
When the worker requests are scheduled serially, `test_concurrent_accept_and_revoke` submits both requests without coordinating their overlap (lines 516–519), and its accepted outcomes at line 520 are also the serial outcomes. A non-atomic implementation that fails only when the operations overlap therefore passes when the requests run one after the other.
Coordinate both workers at a barrier immediately before the operations whose atomicity the test is intended to verify.
</issue_to_address>Linked issues
#332 feat: keep expired invitations for a set time · 6 of 6 met
| # | Requirement | Status | Notes |
|---|---|---|---|
| 1 | List expired invitations with a status; keep accepted invitations out of the default view. | ✅ Met | getServiceInvitations() lists unaccepted invitations, including expired ones, and lists unexpired accepted invitations only when include_accepted=true. |
| 2 | Allow DELETE on expired invitations; continue refusing expired links with 404. | ✅ Met | deleteServiceInvitation() removes unaccepted invitations whether open or expired; acceptance filters for open, unexpired invitations. Tests cover both behaviors. |
| 3 | Add keep_expired_days with default 30 and bounds 0–365; apply changes without manual database work. |
✅ Met | The config validates the range, and apply_keep_expired_days() sets the TTL index at app startup. Tests cover changed values. |
| 4 | Keep the single-use guarantee, including under concurrent requests, with tests. | ✅ Met | acceptInvitation() atomically claims only open invitations; the tests cover concurrent acceptance and concurrent accept/revoke. |
| 5 | Test the TTL-index upgrade and describe it in the upgrade notes. | ✅ Met | test_upgrade_from_old_index covers replacement of the old TTL index, and docs/upgrading.md describes the index changes and upgrade behavior. |
| 6 | Update the API and access control docs. | ✅ Met | The OpenAPI spec and docs/access-control.md document listing, statuses, accepted-invitation visibility, and removal. |
Sourcery assessment
Needs a human reviewer. 3 findings to address first, and expired, unaccepted invitations and their labels are now retained and listed to service owners for up to the configured period, 30 days by default. Changing the setting can purge retained records, but it cannot undo any access to invitation metadata during that period.
Blocking findings: cloud_registry/utils.py:84, cloud_registry/ga4gh/registry/invitations.py:245, tests/test_invitations.py:518
Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_011FSoqMUX3EU35poH13xMgG
Summary
Expired invitations used to disappear at once, so nobody could tell who needed a nudge. Now they stay for a set time.
GET /services/{id}/invitationslists invitations that weren't accepted, with a newstatus(open,expired,accepted). Accepted ones are hidden unless asked for (?include_accepted=true). No token or token hash is ever listed.DELETEalso removes expired invitations. An expired link is still refused on accept with404.custom.access_control.invitations.keep_expired_days: default 30, minimum 0 (removed on expiry), maximum 365; no value for keeping them forever.max_per_serviceis unchanged (unexpired, open or accepted). Its409detail now says that accepted invitations count until they expire, and how to see them, as lists hide them.docs/reference.mdrenders the docstrings.Closes #332
Index design
expires_atdo the work:accepted_expires_at(inconfig.yaml): partial onaccepted, TTL 0, removes accepted invitations on expiry. It coexists with the old index, so FOCA can create it during the upgrade.expires_at_1(byset_ttl_index()on startup): TTL ofkeep_expired_days, removes everything else. It's the name of the old index, so an upgrade and a later change of the value are the same code path.set_ttl_index()incloud_registry/utils.pydrops and creates the index when the value differs. It has no registry-specific dependencies, so TRS-Filer could reuse it.collMod, the obvious choice, because the rolereadWrite, the only one the chart gives the app, doesn't allow it: every authenticated deployment would have crashed on upgrade (confirmed on a real MongoDB with--auth). Concurrent starts that interfere with each other try again, up to 5 times.Verification
Pre-commit, all hooks (ruff, semgrep, gitleaks, actionlint, ast-grep, mypy): passed.
Tests in the repo, also run in CI against MongoDB 7.0: upgrade from the old index (
test_upgrade_from_old_index), later changes of the value (test_keep_expired_days_changed), what MongoDB actually removes, with the TTL monitor set to 1 second (test_ttl_removal), concurrent starts (test_set_ttl_index_concurrent), single use under concurrent accepts, accept against revoke, and accepts of an expired link.tests/conftest.pymakes mongomock skip partial TTL indexes, as it would otherwise ignore their filter and delete every expired invitation.Upgrade with the real old code (
origin/devbefore this PR), then the new code, on one real MongoDB 7.0, inchecks/cr-332-upgrade/upgrade_run.shin the work folder (not in the repo, as the test suite can't run two versions):checks/cr-332-upgrade/ttl_auth_race.py, on MongoDB 7.0 with--auth, as a user with onlyreadWrite, 20000 documents: the upgrade from the old index works; 40 rounds of 4 processes starting at once gave no errors and the right value each time.Full suite locally on MongoDB 7.0: 1933 passed;
mkdocs build --strict: clean. CI on the same commit: all checks passed, including Test (mongomock), Test (MongoDB 7.0), Chart, Docs, Smoke test, Scan image and codecov (project and patch).Sourcery reviewed: three threads, one fixed (the race test now uses a barrier), two declined below, all resolved. Copilot posted no review within 15 minutes; it hasn't reviewed recent PRs in this repo.
Declined review findings
collModisn't allowed forreadWrite.openis documented as depending on the creator still being able to grant the role; computing that per listed invitation isn't worth it.expiry_days: 1, keep_expired_days: 365allows about 7300 stored invitations per service. The limit is as decided, pagination is out of scope here, and the bound is documented indocs/configuration.md.tests/conftest.py(quality, low): kept simple, as it applies to all tests that use mongomock and only skips partial TTL indexes.The reviewer rounds are used up (2 of 2). The last fix, moving from
collModto dropping and creating the index, came out of round 2 and got no further reviewer round; it's covered by the checks above.Open questions
None.
🤖 Generated with Claude Code
https://claude.ai/code/session_011FSoqMUX3EU35poH13xMgG