Repository navigation
feat(accounting): export tool execution reports - #503
Conversation
Usage records now also hold what execution reports need: the tool of the task (name, version and identifiers from the image of its first executor and its tags `biotools_id` and `rrid`), the start, end and total output size of each attempt (task log), and the proTES version. No commands, environment variables, URLs, paths or other tags are stored. Refs #502 Co-Authored-By: Claude Opus 5.5 <[email protected]>
Admins get the usage records of a time range as execution reports of the Tool Execution Report format of ELIXIR Compute, version 0.0.2 (`GET /usage/reports`, rule `admins-get-usage-reports`): one report per attempt of a task, with the tool, the providers (configured ones, the TES instance and proTES), the configured location, the requested CPU cores, the times and the rounded total output size. Reports hold no user identifiers or other details of tasks. `custom.accounting.reports` names the providers and locations, and limits the records per request (`max_records`). The tests validate the reports against the vendored schema (MIT, REUSE sidecar file). Closes #502 Co-Authored-By: Claude Opus 5.5 <[email protected]>
Image names and tags in personal namespaces (e.g., ghcr.io/<user>) may name users, so only tasks of images in trusted namespaces are reported (`custom.accounting.reports.images`; by default Docker Hub's official images and BioContainers). Output sizes beyond 64-bit integers no longer drop the whole usage record. The time range filter is shared with the usage totals, and the docs link the vendored schema commit. Refs #502 Co-Authored-By: Claude Opus 5.5 <[email protected]>
Report only tasks that completed, whose images exist, so that names and tags of images that don't exist (e.g., ubuntu:<user name>) are never reported. Image repositories and trusted namespaces are compared in canonical form (registry included, Docker Hub aliases and `library`), so that Docker Hub paths can't pass as other registries and namespaces given with `docker.io/` match; a registry alone is rejected. Refs #502 Co-Authored-By: Claude Opus 5.5 <[email protected]>
Reviewer's GuideSchema and migrationsExtend usage records with tool metadata, attempt timing and output totals, and the recording proTES version needed to build reports.
Data structuresDefine the report configuration and its validated provider, location, backend, URL and trusted-image namespace structures.
Specify the stored tool representation and extract image and task-tag identifiers without retaining other task details.
APIExpose the admin-only usage-reports endpoint and define its query parameters, responses and report shape in the OpenAPI additions.
Uses of the APIConnect the reports endpoint to accounting, time parsing and the configured report settings, translating record-limit errors into an API error.
Share finished-time range filtering between usage totals and report queries.
Export eligible usage records as one report per attempt, applying trusted-image and completion filters, configured infrastructure details, formatting and record limits.
ImplementationPublish the new accounting configuration and report-export functions and update the module contract to describe the record and controller responsibilities.
ConfigurationAdd the admin policy for report exports and provide default report settings in the base configuration.
Map oversized report requests to a Bad Request problem response.
DocumentationDocument the execution-report endpoint, report fields and privacy constraints for API users.
Describe report configuration, provider and location settings, image trust boundaries and request limits.
Explain how operators export time-bounded reports, handle record limits and preserve reports before deleting usage records.
Update role permissions and rule-name documentation for administrator report access.
Describe the accounting upgrade, new report endpoint and required access-control rule for deployments.
TestsCheck stored tool and attempt data, including time fallbacks, output-size validation and task projection.
Validate report generation, privacy filtering, configuration, ordering, limits and endpoint access against the vendored format schema.
Check image-reference parsing and the inclusion of only valid tool identifiers from task tags.
Lock files and vendored codeVendor the Tool Execution Report schema and its MIT licensing metadata for report validation.
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 #503 +/- ##
==========================================
Coverage 100.00% 100.00%
==========================================
Files 35 37 +2
Lines 3239 3475 +236
==========================================
+ Hits 3239 3475 +236 ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
Linked issuesChecked at commit 9364f5e #502 feat: export tool execution reports · 4 of 6 met
|
There was a problem hiding this comment.
Hey - I've found 11 issues
Prompt for AI Agents
Please address the comments from this code review:
## Individual Comments
### Comment 1
<location path="pro_tes/accounting/tool.py" line_range="33" />
<code_context>
+MAX_REPOSITORY_LENGTH = 255
+# Identifiers of tools in tags of tasks: patterns of the values, and the
+# IRIs they give
+BIOTOOLS_ID = re.compile(r"[A-Za-z0-9_~-][A-Za-z0-9._~-]{0,99}", re.ASCII)
+RRID = re.compile(r"(?:RRID:)?(?P<id>SCR_[0-9]{1,12})", re.ASCII)
+BIOTOOLS_IRI = "https://bio.tools/{}"
</code_context>
<issue_to_address>
**Personal identifiers appear in reports**
When a task supplies a syntactically valid `biotools_id` containing a person’s name or other personal information, `_tag_identifiers` accepts the arbitrary tag value and `task_tool` publishes it as a bio.tools URL, so personal information appears in exported reports.
Only publish a bio.tools identifier after verifying that the value identifies a real tool.
Also at `pro_tes/accounting/reports.py:177`, `pro_tes/accounting/tool.py:85-86`.
</issue_to_address>
### Comment 2
<location path="pro_tes/accounting/record.py" line_range="191" />
<code_context>
record[name] = amount
record[field] = product
+ # for execution reports (cf. :py:mod:`pro_tes.accounting.reports`)
+ record["tool"] = task_tool(task)
+ record["attempts"] = [_attempt(log) for log in logs]
+ record["protes_version"] = version("pro-tes")
</code_context>
<issue_to_address>
**Retries discard fuller usage records**
When a full usage record has been written and a redelivered response contains fewer logs or output details, including when its logs lack a complete time span, `record_usage` treats an incomplete retry as authoritative or preserves only records marked `timed`, replacing the fuller record; reports then omit attempts or output sizes.
Retain or merge the fuller existing usage record instead of replacing it with an incomplete retry.
Also at `pro_tes/accounting/record.py:192`.
</issue_to_address>
### Comment 3
<location path="pro_tes/accounting/record.py" line_range="121" />
<code_context>
+ Its start and end (`None` if either is unknown, cf. :py:func:`_span`)
+ and the total size of its outputs (`outputs_bytes`), if logged.
+ """
+ start, end = _span(log) or (None, None)
+ return {"start_time": start, "end_time": end, "outputs_bytes": _outputs_bytes(log)}
+
</code_context>
<issue_to_address>
**Known attempt times disappear**
When a task or executor log provides only a start time or only an end time, `_span` returns `None` when either endpoint is missing, so `_attempt` stores both endpoints as `None` and reports omit the known timestamp.
Read and store each endpoint independently so a missing start or end does not erase the other.
</issue_to_address>
### Comment 4
<location path="pro_tes/accounting/record.py" line_range="106-109" />
<code_context>
+ return None
+ size = int(size)
+ if isinstance(size, int) and not isinstance(size, bool) and size >= 0:
+ sizes.append(size)
+ total = sum(sizes)
+ return total if sizes and total <= MAX_SIZE else None
+
+
+def _attempt(log: Any) -> dict[str, Any]:
</code_context>
<issue_to_address>
**Output totals undercount attempts**
When an attempt has at least one output with a valid size and another with a missing or invalid size, `_outputs_bytes` sums valid sizes while silently skipping outputs with missing or invalid sizes, so reports present a partial sum as `final_outputs_size`. Consumers see an incorrect total for the attempt.
Leave the total unknown if any output size is unknown or invalid, unless the report contract explicitly defines totals as sums of only known sizes.
</issue_to_address>
### Comment 5
<location path="pro_tes/accounting/reports.py" line_range="239-253" />
<code_context>
+ TooManyRecords: More than `config.max_records` records are in the
+ time range.
+ """
+ match: dict[str, Any] = {
+ "tool": {"$type": "object"},
+ "attempts.0": {"$exists": True},
+ # tasks that completed ran their image, which therefore exists (in
+ # the trusted namespace): names and tags of images that don't exist
+ # (e.g., `ubuntu:<name of a user>`) are not reported
+ "state": COMPLETE,
+ **finished_range(since, until),
+ }
+ records = list(
+ usage.find(
+ match,
+ projection={"_id": False, **dict.fromkeys(FIELDS, True)},
+ sort=[("finished_at", 1), ("_id", 1)],
+ limit=config.max_records + 1,
+ )
+ )
</code_context>
<issue_to_address>
**Untrusted tasks trigger export limit**
When more than `max_records` completed records have a tool and attempts, but at most `max_records` have trusted images, `execution_reports` counts these records before `_reports` applies `trusted_image`, so it raises `TooManyRecords` and admins get `400` even though the reportable tasks fit in one request.
Apply the trusted-image eligibility check before enforcing the report-count limit, or explicitly define and document the limit as applying to candidate records before image filtering.
</issue_to_address>
### Comment 6
<location path="pro_tes/accounting/reports.py" line_range="252" />
<code_context>
+ usage.find(
+ match,
+ projection={"_id": False, **dict.fromkeys(FIELDS, True)},
+ sort=[("finished_at", 1), ("_id", 1)],
+ limit=config.max_records + 1,
+ )
</code_context>
<issue_to_address>
**Exports require blocking sorts**
When the usage collection grows large and an export covers a broad time range, mongoDB has an index on `finished_at` but not the requested `(finished_at, _id)` sort; for large time ranges it scans matching records and performs a blocking sort before applying the limit, making even requests that return at most `max_records` expensive.
Add a compound index on `finished_at` and `_id` for the report query, and verify MongoDB uses it for the filter and sort.
</issue_to_address>
### Comment 7
<location path="pro_tes/accounting/tool.py" line_range="68" />
<code_context>
+ "repository": match["repository"],
+ "version": version,
+ "package_version": package_version,
+ "identifiers": [f"docker://{match['repository']}"],
+ }
+
</code_context>
<issue_to_address>
**Always adding image identifier**
The issue asks to omit tool_identifier when the task carries no identifier. The change always adds the image repository identifier, even when neither task tag supplies one.
</issue_to_address>
### Comment 8
<location path="pro_tes/accounting/reports.py" line_range="194-195" />
<code_context>
+ if location:
+ common["location"] = location
+ cores = _cores(record.get("cpu_cores"))
+ if cores is not None:
+ common["cpu_cores_assigned"] = cores
+ reports = []
+ for attempt in record["attempts"]:
</code_context>
<issue_to_address>
**Requested memory omitted**
The issue asks for requested memory as well as CPU cores, and says these are allocations rather than measurements. The report includes requested CPU cores but omits requested memory.
</issue_to_address>
### Comment 9
<location path="tests/accounting/test_record.py" line_range="129-147" />
<code_context>
+ ],
+ document=document,
+ )
+ assert usage["tool"] == {
+ "name": "bwa",
+ "repository": "quay.io/biocontainers/bwa",
+ "version": "0.7.18",
+ "package_version": "0.7.18--he4a0461_1",
+ "identifiers": [
+ "https://bio.tools/bwa",
+ "docker://quay.io/biocontainers/bwa",
+ ],
+ }
+ assert usage["attempts"] == [
+ {"start_time": None, "end_time": None, "outputs_bytes": None},
+ {
+ "start_time": START + timedelta(hours=1),
+ "end_time": START + timedelta(hours=2),
+ "outputs_bytes": 123,
+ },
+ ]
+
+
[email protected](
</code_context>
<issue_to_address>
**Sensitive fields can persist unnoticed**
When the record-writing code starts persisting task details that are present in the test document, `test_record_for_reports` checks only the tool and attempts at lines 129 and 139, so it still passes if commands, environment variables, inputs, or other task details are copied into the stored record. The report-privacy test checks exported reports, not the stored record.
Assert that the returned record omits the command, env, input/output URLs and paths, and unrelated tags.
</issue_to_address>
### Comment 10
<location path="tests/accounting/test_reports.py" line_range="400-404" />
<code_context>
+ for day in (2, 0, 1):
+ add(usage, task_id=f"T{day}", day=day)
+ reports = execution_reports(usage, ExecutionReports())
+ assert [report["start_time"][:10] for report in reports] == [
+ "2026-11-01",
+ "2026-11-02",
+ "2026-11-03",
+ ]
+ reports = execution_reports(
+ usage,
</code_context>
<issue_to_address>
**Incorrect report ordering passes**
When tasks have different runtimes and finish in an order different from their start order, `test_reports_in_time_range` checks only the reports' start-date order at line 400. Its helper gives every task a one-hour attempt, so sorting by start time instead of finish time still passes even when tasks with different runtimes would finish in a different order.
Give the test tasks different attempt durations and assert that their reports follow finish order.
</issue_to_address>
### Comment 11
<location path="tests/accounting/test_reports.py" line_range="416-420" />
<code_context>
+
+def test_too_many_records(usage: Collection[dict[str, Any]]) -> None:
+ """Requests for more records than `max_records` are rejected."""
+ for day in range(3):
+ add(usage, task_id=f"T{day}", day=day)
+ config = ExecutionReports(max_records=2)
+ with pytest.raises(TooManyRecords):
+ execution_reports(usage, config)
+ assert len(execution_reports(usage, config, since=START + timedelta(days=1))) == 2
+
</code_context>
<issue_to_address>
**Attempt count can trigger record limit**
When a task within the record limit has multiple attempts, `test_too_many_records` (lines 416–420) and `test_get_reports_too_many` (lines 621–629) use default one-attempt tasks, so a limit mistakenly applied to flattened reports still passes both tests. It would reject one task with two attempts at `max_records=1`, although the request covers only one record.
Add a max-records case with one task and multiple attempts that must succeed when `max_records` is one.
Also at `tests/accounting/test_reports.py:621-629`.
</issue_to_address>Sourcery assessment
Needs a human reviewer. 11 findings to address first, and the new admin-only endpoint exposes tool identifiers, image names and tags, attempt times, and output sizes; an overly broad access rule or faulty report filtering could disclose operational data. Reverting removes the endpoint and stops future capture, but data already exposed cannot be taken back.
Blocking findings: pro_tes/accounting/tool.py:33, pro_tes/accounting/record.py:191, pro_tes/accounting/record.py:121, pro_tes/accounting/record.py:109, pro_tes/accounting/reports.py:253, and 6 more
Keep a known start or end of an attempt without the other, leave the output total unknown when any output size is missing or invalid, sort reports by the indexed `finished_at` only (no blocking sort), and say what `max_records` counts. Tests now check that records hold no task details, that reports follow the finish order, and that the limit counts tasks, not attempts. Refs #502 Co-Authored-By: Claude Opus 5.5 <[email protected]>
Summary
Admins can export the usage records (#490) as execution reports of the ELIXIR Compute Tool Execution Report format, version 0.0.2 (
GET /ga4gh/tes/v1/usage/reports?since=…&until=…, new ruleadmins-get-usage-reports). The response is a JSON array with one report per attempt of a task at its TES instance (task log).pro_tes/accounting/record.py,tool.py) now also hold the tool (from the image of the first executor: name, repository, tag as version, BioContainers<version>--<build>split into version and package version; identifiers from the tagsbiotools_idandrridplusdocker://<repository>), per attempt the start, end and total output size, and the proTES version. Commands, env, inputs/outputs, URLs, paths and other tags are not stored.pro_tes/accounting/reports.py):tool_*,infra(configured providers, the TES instance, proTES),location(configured),cpu_cores_assigned(requested, an allocation),start_time/end_time, andfinal_outputs_size(total, rounded to two significant digits). Fields TES can't fill are left out and documented (affiliation,input_size,cpu_identifier,cpu_mods,memory_used,cpu_cores_used,gpu_cores_used,duration).custom.accounting.reports.images, default: Docker Hub official images and BioContainers on Docker Hub and Quay; compared in canonical form; a bare registry is rejected). OnlyCOMPLETEtasks are reported, so that the image existed and no made-up names or tags (e.g.ubuntu:<user name>) get through. Sizes are totals per attempt, rounded.custom.accounting.reports:infra,location,backends(by normalized URL),images, andmax_records(default 10000; more records in a range give400).tests/accounting/data/from compute_wp5@76b2a13 with a REUSE.licensesidecar (MIT) andLICENSES/MIT.txt. The tests validate every report against it, withirianddate-timeformat checks.docs/api.md(Execution reports: field mapping, unfilled fields, privacy),docs/configuration.md(Execution reports settings),docs/operations.md(how to export and hand reports over),docs/access-control.md,docs/upgrading.md(0.7.0).Decisions made here:
tool_identifieris required by the schema. The issue said to leave it out when the task carries none, so instead the image repository (docker://…) is always added.memory_used, a measured peak, and the requested RAM is an allocation, so it's left out rather than adding a non-standard field.COMPLETEtasks are reported (privacy over completeness); failed attempts within a completed task still get their own reports.Closes #502
Verification
Local, in the clone (Python 3.13,
uv sync --locked --extra dev --extra docs):coverage run -m pytest --deselect tests/test_chart.py --deselect tests/test_config_examples.py::test_chart_examples_valid: 1895 passed, 11 skipped. The changed modules (pro_tes/accounting/*) are 100% covered; the tests validate every report against the vendored schema.tests/test_chart.pyand the two chart example tests intests/test_config_examples.py, because the Helm library chart isn't built locally (helm dependency build deployment). The chart is unchanged; CI runs them.pre-commit run --all-files: all hooks passed (ruff, ruff-format, mypy, semgrep and its rule tests, ast-grep and its rule tests, yaml/whitespace checks). gitleaks and actionlint were skipped locally (their Go toolchain download failed in the sandbox); CI runs both.mkdocs build --strict: passed.After the Sourcery fixes (9364f5e):
pytest tests/accounting182 passed, the changed modules 100% covered, pre-commit andmkdocs build --strictpassed.CI: all checks passed again on 9364f5e (incl. Test on MongoDB 7.0, Codecov patch/project, Sourcery review); earlier also on 457a95f (
CI passed; Test on mongomock and on MongoDB 7.0, Chart, Docs, Lint incl. gitleaks and actionlint, Smoke test, Integration, Scan image, CodeQL, Codecov patch/project, Read the Docs).Declined review findings
Split
tests/accounting/test_reports.pyinto config/endpoint files (quality, low): the module tests, config and endpoint of one feature stay together;tests/accounting/test_usage_endpoint.pydoes the same for/usage.Use an independent IRI checker such as
rfc3987in the tests (quality, low): it's not a dependency; the test checker is an explicit approximation of RFC 3987, and the schema's other constraints are checked by jsonschema.Cache
version("pro-tes")at import (quality, low):gateway.pycalls it the same way, and the adversarial review confirmed it adds no new failure mode.Split the review-fix commit into four (quality round 2, low): the commit body lists the parts; the PR is squash-merged.
Hoist the default image namespaces into a constant / test config.yaml against the model (quality round 2):
test_config_of_appalready compares the base config'scustom.accounting.reportswithExecutionReports(), images included.Drop non-version-like tags (adversarial round 2, optional): with trusted namespaces and
COMPLETEonly, tags are those of published images.Sourcery: verify
biotools_idagainst bio.tools: no network calls from the export; the tag is a dedicated tool ID tag, and its handling is documented.Sourcery: merge records when a redelivered BASIC-view poll replaces a FULL-view record: the replacement logic is unchanged from feat: account resource usage per user #490, and only the optional output sizes can be lost, in a rare worker-loss case.
Sourcery: omit
tool_identifier/ add requested memory as the issue says: the schema requirestool_identifier(minItems: 1) and has no field for allocated memory (see Decisions).Sourcery: apply the trusted namespaces before
max_records: the limit bounds the records one request reads; documented.Open questions
None.
🤖 Generated with Claude Code