Repository navigation
feat: account resource usage per user - #490
Conversation
Add opt-in accounting (custom.accounting.enabled, off by default). The Celery workers record each task that finished at its TES instance, right before its final state is stored, in the collection usage: the owner (user_id), task id, TES instance, final state, run time from the TES instance's logs, and the requested CPU cores, RAM and disk times the run time. Records outlive the retention of finished tasks; the operations guide says how to delete them or add a TTL index. Admins get the totals per user at GET /usage (rule admins-get-usage), optionally for one user and a time range (since, until). Closes #459 Co-Authored-By: Claude Opus 5.5 <[email protected]>
Log writes of usage records that MongoDB refuses (OperationFailure) instead of retrying the poll forever, so that tasks still finish. Reject since/until values that are out of range in UTC (400 instead of 500). Add the upgrade note of the accounting. Refs #459 Co-Authored-By: Claude Opus 5.5 <[email protected]>
Handle errors of usage records in one branch, and say in the docs that errors MongoDB reports (e.g., refused writes, timeouts) are logged, while polls are retried only if MongoDB can't be reached. Note that the collection usage is created also while accounting is off. Refs #459 Co-Authored-By: Claude Opus 5.5 <[email protected]>
Reviewer's GuideSchema and migrationsDefine the usage collection and its indexes, which support task-keyed records and time-range queries.
Data structuresAdd the accounting settings model that the configuration and worker logic depend on.
APISpecify the admin usage endpoint, its filters, responses, and per-user totals shape.
Uses of the APIConnect task polling to usage recording before the final task state is stored, with connection-loss retries and logging for other errors.
ImplementationBuild idempotent task usage records from TES logs and requested resources, and aggregate them into per-user totals.
Implement the usage controller and strict RFC 3339 query-time parsing, with the corresponding bad-request error.
ConfigurationWire accounting into custom configuration and document its opt-in defaults and admin access policy.
DocumentationDocument the usage endpoint, configuration, permissions, record lifecycle, operator cleanup, and upgrade implications.
TestsCover record construction, aggregation, endpoint authorization and filtering, and task-poll recording and error handling.
Other changesFiles not grouped.
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 #490 +/- ##
==========================================
Coverage 100.00% 100.00%
==========================================
Files 31 35 +4
Lines 3105 3239 +134
==========================================
+ Hits 3105 3239 +134 ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
Linked issuesChecked at commit 3e35cfb #459 feat: account resource usage per user · 3 of 3 met
|
There was a problem hiding this comment.
Hey - I've found 5 issues
Prompt for AI Agents
Please address the comments from this code review:
## Individual Comments
### Comment 1
<location path="pro_tes/tasks/track_task_progress.py" line_range="558-559" />
<code_context>
+ # errors that MongoDB reports (e.g., missing rights, a validator)
+ # may recur on every retry, which would keep the task from finishing
+ if isinstance(exc, INFRASTRUCTURE_ERRORS) and not isinstance(
+ exc, OperationFailure
+ ):
+ raise
+ logger.exception("[%s] Usage of the task not recorded", worker_id)
</code_context>
<issue_to_address>
**Nonconnection database errors stall tasks**
When recording usage raises a `PyMongoError` that is not an `OperationFailure` and does not indicate loss of MongoDB connectivity, `INFRASTRUCTURE_ERRORS` includes every `PyMongoError`, so a non-`OperationFailure` error such as a client-side document-size error is re-raised; `task__track_task_progress` retries that error indefinitely, leaving the task unfinished instead of logging the accounting failure and storing its final state.
Retry only connection-related MongoDB errors and log other accounting errors before storing the task's final state.
</issue_to_address>
### Comment 2
<location path="pro_tes/tasks/track_task_progress.py" line_range="658" />
<code_context>
basic=response,
)
+ if get_custom_config(CustomConfig).accounting.enabled:
+ _record_usage(collection=collection, kwargs=kwargs, response=response)
try:
_store_final(db_client=db_client, worker_id=worker_id, response=response)
</code_context>
<issue_to_address>
**Redelivery erases recorded run time**
When a worker is lost after successfully recording usage but before storing the final task state, `_poll` skips `_full_task` for a redelivered message, so `record_usage` receives the basic response without logs and upserts an untimed record over the accurate one written before the worker was lost; admins then see zero usage for that task.
On redelivery, preserve an existing usage record with known timing, or retrieve the full logs before replacing it.
Also at `pro_tes/accounting/record.py:166`.
</issue_to_address>
### Comment 3
<location path="pro_tes/tasks/track_task_progress.py" line_range="658" />
<code_context>
basic=response,
)
+ if get_custom_config(CustomConfig).accounting.enabled:
+ _record_usage(collection=collection, kwargs=kwargs, response=response)
try:
_store_final(db_client=db_client, worker_id=worker_id, response=response)
</code_context>
<issue_to_address>
**Accounting loses task runtimes**
When accounting is enabled while `custom.controllers.post_task.max_log_size` is zero, `_full_task` returns the basic response when `max_log_size` is zero, so `_record_usage` receives no logs and `usage_record` marks every task untimed with zero resource-seconds, even when the TES instance has timing data. Admins see no useful usage totals.
Make the interaction explicit and ensure accounting can obtain or otherwise report task timing without silently treating all such tasks as untimed.
</issue_to_address>
### Comment 4
<location path="pro_tes/ga4gh/tes/server.py" line_range="164" />
<code_context>
+ if value is None:
+ return None
+ try:
+ parsed = datetime.fromisoformat(value)
+ # in UTC, as MongoDB stores times; out of its range (e.g., year 10000
+ # in UTC) is invalid
</code_context>
<issue_to_address>
**Non-RFC times are accepted**
When a caller supplies a parseable ISO 8601 value that is not RFC 3339, such as a date without a time, `datetime.fromisoformat` accepts values such as `2026-11-01` that are not RFC 3339 timestamps, so `_parse_time` treats them as UTC midnight instead of returning the documented 400 error; callers get a filtered report for an input the API says is invalid.
Validate the RFC 3339 timestamp syntax before parsing the value.
</issue_to_address>
### Comment 5
<location path="pro_tes/accounting/record.py" line_range="72" />
<code_context>
+ """
+ if isinstance(value, bool) or not isinstance(value, int | float):
+ return None
+ return float(value) if value >= 0 else None
+
+
</code_context>
<issue_to_address>
**Non-finite totals break JSON**
When a task accepted by a TES backend has an infinite or sufficiently large finite RAM or disk request and a timed log, `_amount` accepts positive infinity, and multiplying a large finite amount by run time can also overflow to infinity. MongoDB then aggregates non-finite totals, which the usage endpoint returns as non-standard JSON.
Reject non-finite resource amounts and non-finite products before storing the record.
Also at `pro_tes/accounting/record.py:123`.
</issue_to_address>Sourcery assessment
Needs a human reviewer. 5 findings to address first, and the feature stores user identifiers alongside task usage and serves per-user totals through a new admin-only endpoint. If the access rule is wrong and those records are exposed, reverting removes the endpoint but cannot undo data already read; recording is opt-in, and stored records can be deleted.
Blocking findings: pro_tes/tasks/track_task_progress.py:559, pro_tes/tasks/track_task_progress.py:658, pro_tes/tasks/track_task_progress.py:658, pro_tes/ga4gh/tes/server.py:164, pro_tes/accounting/record.py:72
- Retry the poll only if MongoDB can't be reached (ConnectionFailure); log all other errors, also client-side errors of PyMongo, so that the task still finishes. - Don't replace a timed usage record with an untimed one, e.g. from a poll delivered again, which skips the view FULL. - Accept only RFC 3339 date-times for since/until (time zone may be left out; lowercase t/z accepted), not other ISO 8601 forms. - Don't account non-finite amounts or products, and cap totals that overflow at the largest float, so the report stays valid JSON. - Test that with max_log_size 0 the times of the view BASIC count. - Update the configuration and API docs and the OpenAPI descriptions. Co-Authored-By: Claude Opus 5.5 <[email protected]>
- Move the cap of overflowed totals into _cap, and test it for every summed field. - Document the cap in the API docs. - Reject offsets outside RFC 3339 (e.g., +05:60) in since/until. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Summary
Opt-in accounting of the resources that tasks used, per user (#459): "Admins can see resource usage per user" and "Documented".
custom.accounting.enabled, off by default (pro_tes/accounting/config.py,pro_tes/config.yaml, chart example indeployment/values.yaml).pro_tes/tasks/track_task_progress.py,pro_tes/accounting/record.py). Each record goes into the new collectionusage, keyed by task ID and upserted, so retries and redeliveries don't count a task twice. A record holds:user_id, the subject identifier the task document already stores)logs[].start_time/end_time, or else the span of its executors), summed over attemptsGET /ga4gh/tes/v1/usageis admin-only (new ruleadmins-get-usage). It returns totals per user, can be filtered byuser_idand asince/untilrange, and includes arecordingflag. Spec:pro_tes/api/additions.openapi.yaml; controller:pro_tes/ga4gh/tes/server.py; aggregation:pro_tes/accounting/report.py.docs/configuration.md, section "Accounting of resource usage"docs/api.md, section "Usage" and the endpoint tabledocs/operations.md, section "Usage records"docs/access-control.md, the roles table and the rule namesdocs/upgrading.md, notes for 0.7.0Design decisions
user_id, which tasks already store. On current FOCA (0.22) this is issuer-namespaced with several issuers. Nothing here depends on unreleased FOCA changes (foca#631)./tasks/{id}/provenanceand/plugins. Records are kept in their own collection, so the retention of finished tasks doesn't remove the accounting.Verification
coverage run -m pytest -W ignore::DeprecationWarning --ignore=tests/test_chart.py(mongomock): 1744 passed, 11 skipped, coverage 100%.tests/test_config_examples.py::test_chart_examples_valid[...]. They andtests/test_chart.pyneed the Helm library chart (helm dependency build), and Helm isn't installed on this machine. CI runs them.pytest tests/accounting tests/taskspassed (144 tests).mypy: no issues.pre-commit run --all-files(ruff, ruff-format, semgrep, gitleaks, actionlint, ast-grep, mypy): passed.mkdocs build --strict: passed.Declined review findings
pro_tes/accountingandpro_tes/retentionare documented as self-contained modules.datetimeobjects, while the controller parses query strings.usage_recordin__all__(quality, low). Kept public: it is the pure function that builds a record. The tests use it to seed realistic records, which keeps the test data in step with the record shape.tests/accounting/conftest.py, module-levelDOCUMENT(quality, low). Left as is. Each test file's fixtures are used only in that file, andDOCUMENTis only read.OperationFailure) is logged, and only connection loss retries the poll. The docs say so. A wrong guess about which codes are transient could stall tracking, while a missed record only costs one task's accounting.Fixed after review:
OperationFailure) are logged instead of retrying the poll forever.since/untilvalues that are out of range in UTC give 400, not 500.Sourcery review (5 threads)
Fixed in
a68e144and the commit after it; each thread answered and resolved:ConnectionFailure) retries the poll; all other errors, including client-side PyMongo errors, are logged and the task finishes.timed != true), so a redelivered poll can't erase the run time.since/untilmust be RFC 3339 date-times (time zone optional, lowercaset/zaccepted); dates, week dates, leap seconds and offsets like+05:60give 400.max_log_size: 0the times come from theBASICview, which keeps the task log times (TES spec).Local checks after these fixes:
pre-commit run --all-filespassed;coverage run -m pytest --ignore=tests/test_chart.py: 1765 passed, 11 skipped, coverage 100%. The 2test_chart_examples_validtests need Helm (not installed here; CI runs them).mkdocs build --strictpassed. Two reviewer rounds (adversarial + quality) on the delta; all findings fixed.Open questions
None.
Closes #459
🤖 Generated with Claude Code