Skip to content

feat: account resource usage per user - #490

Merged
uniqueg merged 5 commits into
devfrom
feat/459-usage-accounting
Nov 13, 2026
Merged

uniqueg merged 5 commits into
devfrom
feat/459-usage-accounting

Conversation

@uniqueg

@uniqueg uniqueg commented Nov 13, 2026 •

Copy link
Copy Markdown
Member

Summary

Opt-in accounting of the resources that tasks used, per user (#459): "Admins can see resource usage per user" and "Documented".

  • Config: custom.accounting.enabled, off by default (pro_tes/accounting/config.py, pro_tes/config.yaml, chart example in deployment/values.yaml).
  • Recording: when a task finishes at its TES instance, the Celery worker records it before it stores the final state (pro_tes/tasks/track_task_progress.py, pro_tes/accounting/record.py). Each record goes into the new collection usage, keyed by task ID and upserted, so retries and redeliveries don't count a task twice. A record holds:
    • the owner (user_id, the subject identifier the task document already stores)
    • the task ID, the TES instance URL and the final state
    • the run time, taken from the TES instance's task logs (logs[].start_time/end_time, or else the span of its executors), summed over attempts
    • the requested CPU cores, RAM and disk, and each of them multiplied by the run time
  • Error handling: if MongoDB is unavailable, the poll is retried, as for the other writes. Any other error, including writes MongoDB refuses, is only logged, so tracking a task never stops because of accounting.
  • API: GET /ga4gh/tes/v1/usage is admin-only (new rule admins-get-usage). It returns totals per user, can be filtered by user_id and a since/until range, and includes a recording flag. Spec: pro_tes/api/additions.openapi.yaml; controller: pro_tes/ga4gh/tes/server.py; aggregation: pro_tes/accounting/report.py.
  • Privacy and retention: records hold nothing of the task beyond the fields above. They outlive the retention of finished tasks and are kept until operators delete them. The operations guide shows how to delete them (by date or by user) and how to add a TTL index.
  • Docs:
    • docs/configuration.md, section "Accounting of resource usage"
    • docs/api.md, section "Usage" and the endpoint table
    • docs/operations.md, section "Usage records"
    • docs/access-control.md, the roles table and the rule names
    • docs/upgrading.md, notes for 0.7.0

Design decisions

  • Allocations, not measurements. TES instances don't report the CPU, RAM or disk a task consumed, so the only portable measure is requested resources × run time. The docs say this.
  • User identity. Usage is counted per 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).
  • Where it lives. The endpoint sits under the TES base path, like the existing extensions /tasks/{id}/provenance and /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%.
    • 2 tests failed locally: tests/test_config_examples.py::test_chart_examples_valid[...]. They and tests/test_chart.py need the Helm library chart (helm dependency build), and Helm isn't installed on this machine. CI runs them.
    • After the review fixes, pytest tests/accounting tests/tasks passed (144 tests).
  • mypy: no issues. pre-commit run --all-files (ruff, ruff-format, semgrep, gitleaks, actionlint, ast-grep, mypy): passed.
  • mkdocs build --strict: passed.
  • CI passed on the PR: Test (mongomock), Test (MongoDB 7.0), Chart, Lint, Docs, Smoke test, Integration, Scan image, CodeQL, codecov patch/project, and the Read the Docs build.

Declined review findings

  • Shared time helper (quality, low). The reviewer suggested one helper for "naive means UTC", used by retention, the controller and the records. Declined:
    • pro_tes/accounting and pro_tes/retention are documented as self-contained modules.
    • The record helper handles py-tes datetime objects, while the controller parses query strings.
    • The shared logic is two lines.
  • usage_record in __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.
  • No tests/accounting/conftest.py, module-level DOCUMENT (quality, low). Left as is. Each test file's fixtures are used only in that file, and DOCUMENT is only read.
  • Retry transient server-reported errors (adversarial round 2, low). These are write-concern errors, timeouts, and mongos host errors. The fix the reviewer offered as an alternative was taken instead: every error that MongoDB reports (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:

  • The upgrade note is added.
  • Refused writes (OperationFailure) are logged instead of retrying the poll forever.
  • since/until values that are out of range in UTC give 400, not 500.
  • The two error branches are merged into one.
  • The upgrading notes now say the collection is created even while accounting is off.

Sourcery review (5 threads)

Fixed in a68e144 and the commit after it; each thread answered and resolved:

  • Only a lost MongoDB connection (ConnectionFailure) retries the poll; all other errors, including client-side PyMongo errors, are logged and the task finishes.
  • An untimed usage record never replaces a timed one (insert, else replace only where timed != true), so a redelivered poll can't erase the run time.
  • since/until must be RFC 3339 date-times (time zone optional, lowercase t/z accepted); dates, week dates, leap seconds and offsets like +05:60 give 400.
  • Amounts that aren't finite, and products that would overflow, aren't accounted; totals that overflow when summed are capped at the largest float.
  • Not a bug, test added: with max_log_size: 0 the times come from the BASIC view, which keeps the task log times (TES spec).

Local checks after these fixes: pre-commit run --all-files passed; coverage run -m pytest --ignore=tests/test_chart.py: 1765 passed, 11 skipped, coverage 100%. The 2 test_chart_examples_valid tests need Helm (not installed here; CI runs them). mkdocs build --strict passed. Two reviewer rounds (adversarial + quality) on the delta; all findings fixed.

Open questions

None.

Closes #459

🤖 Generated with Claude Code

uniqueg and others added 3 commits November 13, 2026 15:52
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]>
@sourcery-ai

sourcery-ai Bot commented Nov 13, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

Schema and migrations

Define the usage collection and its indexes, which support task-keyed records and time-range queries.

  • pro_tes/config.yaml L148-157
  • pro_tes/utils/db.py L35-37

Data structures

Add the accounting settings model that the configuration and worker logic depend on.

  • pro_tes/accounting/config.py L1-22

API

Specify the admin usage endpoint, its filters, responses, and per-user totals shape.

  • pro_tes/api/additions.openapi.yaml L88-203

Uses of the API

Connect task polling to usage recording before the final task state is stored, with connection-loss retries and logging for other errors.

  • pro_tes/tasks/track_task_progress.py L38-41, L47-52, L528-562 (+1 small edits)

Implementation

Build idempotent task usage records from TES logs and requested resources, and aggregate them into per-user totals.

  • pro_tes/accounting/record.py L1-184
  • pro_tes/accounting/report.py L1-79

Implement the usage controller and strict RFC 3339 query-time parsing, with the corresponding bad-request error.

  • pro_tes/exceptions.py L158-164, L230-234
  • pro_tes/ga4gh/tes/server.py L20-31, L126-189 (+2 small edits)

Configuration

Wire accounting into custom configuration and document its opt-in defaults and admin access policy.

  • deployment/values.yaml L64-68
  • pro_tes/config.yaml L61-63, L91-92, L411-416
  • pro_tes/config_models.py L17-660 (4 small edits)

Documentation

Document the usage endpoint, configuration, permissions, record lifecycle, operator cleanup, and upgrade implications.

  • docs/access-control.md L46, L60-62
  • docs/api.md L19, L172-209
  • docs/configuration.md L730-782
  • docs/operations.md L164-209
  • docs/upgrading.md L180-192

Tests

Cover record construction, aggregation, endpoint authorization and filtering, and task-poll recording and error handling.

  • tests/accounting/test_record.py L1-247
  • tests/accounting/test_report.py L1-126
  • tests/accounting/test_usage_endpoint.py L1-135
  • tests/tasks/test_track_task_progress.py L1987-2146 (+6 small edits)

Other changes

Files not grouped.

  • pro_tes/accounting/__init__.py L1-32

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 Nov 13, 2026 •

Copy link
Copy Markdown

Documentation build overview

📚 proTES | 🛠️ Build #35879242 | 📁 Comparing 3e35cfb against latest (4d610a8)

  🔍 Preview build  

6 files changed · ± 6 modified

± Modified

@codecov

codecov Bot commented Nov 13, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 100.00%. Comparing base (4d610a8) to head (3e35cfb).

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.
📢 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 November 13, 2026 16:25
@sourcery-ai

sourcery-ai Bot commented Nov 13, 2026 •

Copy link
Copy Markdown

Linked issues

Checked at commit 3e35cfb

#459 feat: account resource usage per user · 3 of 3 met

# Requirement Status Notes
1 Record each task's resource usage with its owner. ✅ Met The worker records finished tasks in the usage collection with their owner, requested resources, and runtime derived from the TES task or executor logs.
2 Expose resource usage totals per user to admins. ✅ Met GET /usage aggregates totals per user and is protected by the admins-get-usage rule.
3 Document the feature. ✅ Met The change documents accounting configuration, the API, access control, record retention and deletion, and upgrading.

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


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

Comment thread pro_tes/tasks/track_task_progress.py Resolved
Comment thread pro_tes/tasks/track_task_progress.py Resolved
Comment thread pro_tes/tasks/track_task_progress.py Resolved
Comment thread pro_tes/ga4gh/tes/server.py Resolved
Comment thread pro_tes/accounting/record.py Resolved
uniqueg and others added 2 commits November 13, 2026 22:10
- 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]>
@uniqueg
uniqueg merged commit 2bb6347 into dev Nov 13, 2026
53 checks passed
@uniqueg
uniqueg deleted the feat/459-usage-accounting branch November 13, 2026 21:40
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: account resource usage per user

1 participant