Skip to content

feat: retain finished tasks for N days (opt-in) - #457

Merged
uniqueg merged 7 commits into
devfrom
feat/task-retention
Nov 7, 2026
Merged

uniqueg merged 7 commits into
devfrom
feat/task-retention

Conversation

@uniqueg

@uniqueg uniqueg commented Nov 7, 2026 •

Copy link
Copy Markdown
Member

Summary

Opt-in retention of finished tasks (custom.retention), off by default:

  • finished_days (default null: keep all tasks): finished tasks (COMPLETE, CANCELED, EXECUTOR_ERROR, SYSTEM_ERROR, PREEMPTED) are deleted this many days after they finished: after the later of the end time of their last log (logs[].end_time, else creation_time) and their last poll (tracking.polled_at, when proTES stored their final state);
  • interval (default 3600): seconds between runs of the purge in each Celery worker;
  • batch_size (default 500): maximum tasks deleted per run, oldest first.

When finished_days is set, each Celery worker purges when it starts and then every interval seconds, from a daemon thread of its main process, like resume_tracking_periodically. For each expired task, the purge removes the owner roles of all subjects on the task and its cancellation, then replaces the document by a tombstone {task.id, deleted_at}, only while the task is still finished. The unique index on task.id and _write_doc_to_db stay unchanged, and identifiers are never used again. Delete only, no archive.

Core now filters tombstones out of get_task, list_tasks, get_task_provenance and _find_task (cancel). So tombstones are 404 Not Found, also for owners whose roles an instance still has, and are never listed.

The Celery worker doesn't register FOCA's access control, so the purge removes the roles through FOCA's casbin Adapter on the app's policy collection (remove_filtered_policy(..., keep_configured=True)). The adapter records the change, so the cached enforcers of all app instances drop the roles. Roles are removed before the conditional replace. A task whose roles were removed but which wasn't replaced (e.g., the worker stopped in between) is purged on the next run.

Closes #286

Containment and plugin hook points

The feature lives in pro_tes/retention/, which holds the config model Retention, purge.py and the Celery task and worker thread in tasks.py. Its tests are in tests/retention/ and its docs in Configuration, Retention of finished tasks. It doesn't import the task limits (pro_tes/limits, #285), nor they it. A plugin would need these hook points:

  1. Worker registration: pro_tes.retention.tasks in jobs.include of config.yaml. Its worker_ready handler starts the thread.
  2. A config field (CustomConfig.retention) and its defaults in config.yaml.
  3. The tombstone filter in core reads: DELETED_FIELD/NOT_DELETED in pro_tes/utils/db.py, used by the four task queries in task_runs.py. Tombstones are a core notion (identifiers are never reused), so the filter stays in core if the purge moves to a plugin.
  4. Access to the task collection and the policy rules (FOCA adapter), and the request path of tasks (DEFAULT_API_PATH of pro_tes.config_models).
  5. The time recovery ends a task (FINISHED_AT_FIELD in pro_tes/tasks/track_task_progress.py). Also the index {task.state, _id} in config.yaml.

A new index {task.state, _id} lets each run read finished tasks oldest first, without unfinished tasks or tombstones.

Core also records tracking.finished_at when recovery sets a task to SYSTEM_ERROR without a poll (creation cut off, cancel timed out, tracking ended), so that the retention counts from then: another small hook point (5.).

Deviation from the issue

The issue counts the age from the last logs[].end_time, else creation_time. In proTES' own log, end_time is the time the task was forwarded to a TES instance, not when it finished, so a task that ran longer than finished_days would be deleted right after it finished. The age therefore counts from the later of that time and tracking.polled_at, which is set at the poll that stored the final state (regression tests test_long_task_finished_recently and test_finished_recently_kept).

Docs

  • docs/configuration.md: new section Retention of finished tasks, covering the settings, tombstones, several workers, what is kept and the candidate filter.
  • docs/operations.md (Task owners): the queries of tasks without owner leave tombstones out, with a pointer to the retention and a warning not to delete tombstones.
  • docs/upgrading.md (To version 0.6.0): an opt-in note, tombstones in your own queries, jobs.include in overlays, and the rolling upgrade.
  • deployment/values.yaml: commented example.

Release notes are written in the release-prep PR (docs/releases/), as for earlier releases.

Verification

  • Test first: the tombstone tests in tests/retention/test_retention_endpoint.py failed (404 expected; KeyError in listings) with the core filter stashed, and pass with it.

  • coverage run -m pytest (mongomock; chart tests with helm dependency build): 1801 passed, 11 skipped; coverage report 100%.

  • Against MongoDB 7.0 locally (private mongod, MONGODB_TEST_URI): tests/retention, tests/limits, tests/tasks, test_server.py, test_access_control.py and test_provenance_api.py: 406 passed.

  • ruff check / ruff format --check (0.17.3), mypy, ast-grep scan, semgrep --config=.semgrep: clean. mkdocs build --strict: OK.

  • Review: adversarial-reviewer and quality-reviewer. Fixed:

    • operator queries that would match (and delete) tombstones;
    • the duplicated tasks path;
    • eager imports in the package;
    • tests for tasks stored long ago but finished recently, for the recorded rule change and for the rules collection;
    • docs on several workers;
    • (high) the age counted from the forwarding time (see Deviation from the issue);
    • the tasks path, now taken from DEFAULT_API_PATH;
    • a test module basename that clashed with tests/limits/test_endpoint.py after the rebase.
  • Review round 2 (adversarial-reviewer, quality-reviewer): no high or medium findings. Fixed the lows:

    • a stored tracking.polled_at that is NaN or out of range stopped every run at that task; such tasks are now kept;
    • documented that tasks tracked before 0.3.0 (no polled_at) count from when they were forwarded, and that concurrent runs repeat role removals;
    • split the long docs paragraph into bullets, shortened the config.yaml comment, moved the config tests to tests/retention/test_config.py.
  • Sourcery (one round): fixed the retention of tasks failed by recovery (tracking.finished_at), the periodic purge when the first one can't be published, and the index; declined the gap between the start of the final poll and the store of its state (one request, seconds, vs. days).

  • After the Sourcery fixes: coverage run -m pytest 1803 passed, 11 skipped, 100%; MongoDB 7.0: tests/retention, tests/limits, tests/tasks, test_server.py 350 passed; ruff, mypy, ast-grep, semgrep, mkdocs clean.

  • CI: all checks passed (CI passed).

Declined review findings

  • batch_size 500 exceeds FOCA's window of the last 100 rule changes, so an app instance that misses a whole run may reload its rules in full rather than apply the changes. Kept the decided default of 500 and documented it in Configuration (a batch_size of at most 50 stays within the window); a full reload is correct, only slower.

Open questions

None.

🤖 Generated with Claude Code

uniqueg and others added 6 commits November 7, 2026 16:04
Add `custom.retention` with `finished_days` (off by default),
`interval` and `batch_size`. When `finished_days` is set, each Celery
worker purges finished tasks on start and then every `interval`
seconds: tasks whose last log ended (or, without one, that were
created) more than `finished_days` days ago lose their owner roles
(via FOCA's adapter, which records the change for all app instances)
and are replaced by tombstones with `task.id` and `deleted_at` only,
so that their identifiers are never used again. The API treats
tombstones as not found and never lists them.

The feature lives in `pro_tes.retention`, with its own config model
and Celery task, registered via `jobs.include`; core only filters
tombstones out of its queries.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Describe `custom.retention` in the configuration reference (Retention
of finished tasks), with tombstones and what is kept, point to it in
Task owners, add the upgrade note for 0.6.0 and an example to the
chart's values.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The documented queries of tasks without owner now leave tombstones
out, so that operators don't delete them; the docs explain how often
the purge runs with several workers. The retention reuses the tasks
path of the gateway, its package imports only the config model (no
eager imports from the config models), and tests cover tasks stored
long ago but finished recently, the recorded change of the rules and
the collection of the rules.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
proTES sets logs[].end_time when it forwards a task, not when the task
finishes, so a long-running task could be purged right after it
finished. Count the age from the later of that time (or the creation
time) and tracking.polled_at, which is set when the final state is
stored.

Also take the task path from DEFAULT_API_PATH and document that each
purge batch must stay within FOCA's window of recent rule changes.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Split the paragraph on how workers delete tasks into bullets, shorten
the comment in config.yaml and move the config tests into a module of
their own.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
A stored tracking.polled_at that is NaN or out of range made every run
fail at that task. Keep such tasks instead, and document that tasks
tracked before 0.3.0 count from when they were forwarded and that
concurrent runs repeat role removals.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@uniqueg uniqueg added this to the v0.6.0 milestone Nov 7, 2026
@sourcery-ai

sourcery-ai Bot commented Nov 7, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

Schema and migrations

Define the persisted retention data: tombstones retain only a task identifier and deletion time, recovery records when it stores a final state, and the task-state/_id index supports oldest-first purge scans.

  • pro_tes/config.yaml L126-130
  • pro_tes/retention/purge.py L159-161
  • pro_tes/tasks/track_task_progress.py L61-64, L824-828 (+2 small edits)

Data structures

Add the retention settings model and expose it through the custom configuration structure, while defining shared tombstone field and filter constants.

  • pro_tes/config_models.py L19-563 (4 small edits)
  • pro_tes/retention/__init__.py L1-24
  • pro_tes/retention/config.py L1-31
  • pro_tes/utils/db.py L39-45

API

Make task retrieval, listing, provenance, and cancellation lookup ignore tombstones so deleted tasks are consistently unavailable through the API.

  • pro_tes/ga4gh/tes/task_runs.py L835-838 (+4 small edits)

Implementation

Implement expiration-time calculation, access-role removal, conditional tombstone replacement, and the Celery worker’s startup and periodic purge execution.

  • pro_tes/retention/purge.py L1-170
  • pro_tes/retention/tasks.py L1-114
  • pro_tes/tasks/track_task_progress.py L829, L878-883

Configuration

Register the retention worker, provide default settings and deployment examples, and ensure the Celery job include is enabled by the base configuration.

  • deployment/values.yaml L59-62
  • pro_tes/config.yaml L200-201, L385-391

Documentation

Document retention settings and behavior, operational handling of tombstones, and upgrade considerations.

  • docs/configuration.md L628-689
  • docs/operations.md L99-103, L120-132
  • docs/upgrading.md L123-138

Tests

Cover retention configuration, purge timing and concurrency-safe behavior, worker scheduling, recovery timestamps, and tombstone API semantics.

  • tests/retention/conftest.py L1-10
  • tests/retention/test_config.py L1-42
  • tests/retention/test_purge.py L1-332
  • tests/retention/test_retention_endpoint.py L1-169
  • tests/retention/test_tasks.py L1-144
  • tests/tasks/test_track_task_progress.py L1521-1531 (+5 small edits)

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

Copy link
Copy Markdown

Documentation build overview

📚 proTES | 🛠️ Build #35721387 | 📁 Comparing a8e880d against latest (53ce92b)

  🔍 Preview build  

4 files changed
± configuration/index.html
± operations/index.html
± reference/index.html
± upgrading/index.html

@codecov

codecov Bot commented Nov 7, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 100.00%. Comparing base (53ce92b) to head (a8e880d).

Additional details and impacted files
@@            Coverage Diff             @@
##               dev      #457    +/-   ##
==========================================
  Coverage   100.00%   100.00%            
==========================================
  Files           27        31     +4     
  Lines         2875      2998   +123     
==========================================
+ Hits          2875      2998   +123     

☔ 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 7, 2026 16:01

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

Prompt for AI Agents
Please address the comments from this code review:

## Individual Comments

### Comment 1
<location path="pro_tes/retention/purge.py" line_range="71" />
<code_context>
+    if started is None:
+        started = document["_id"].generation_time
+    polled_at = (document.get("tracking") or {}).get("polled_at")
+    if isinstance(polled_at, int | float) and not isinstance(polled_at, bool):
+        try:
+            polled = datetime.fromtimestamp(polled_at, UTC)
</code_context>
<issue_to_address>
**Tasks expire before retention elapses**

When the final poll starts before the retention cutoff but stores its finished state after the cutoff, `finished_at` uses `tracking.polled_at`, which `_claim` sets when the poll starts, as the finalization time, so the purge considers the task expired as soon as its finished state is stored and deletes it before the configured retention period after completion.

Record and use the time the final state is stored instead of the poll-claim time.

Also at `pro_tes/retention/purge.py:77`.
</issue_to_address>

### Comment 2
<location path="pro_tes/retention/purge.py" line_range="67-77" />
<code_context>
+    logs = task.get("logs")
+    last = logs[-1] if isinstance(logs, list) and logs else None
+    end_time = _parse_time(last.get("end_time")) if isinstance(last, dict) else None
+    started = end_time or _parse_time(task.get("creation_time"))
+    if started is None:
+        started = document["_id"].generation_time
+    polled_at = (document.get("tracking") or {}).get("polled_at")
+    if isinstance(polled_at, int | float) and not isinstance(polled_at, bool):
+        try:
+            polled = datetime.fromtimestamp(polled_at, UTC)
+        except (ValueError, OverflowError, OSError):
+            # not a valid time: keep the task, rather than stop the purge
+            return datetime.max.replace(tzinfo=UTC)
+        return max(started, polled)
+    return started
+
</code_context>
<issue_to_address>
**New failures are purged too soon**

When worker recovery changes an old unfinished task to `SYSTEM_ERROR` and its creation time or existing `tracking.polled_at` is older than the retention cutoff, `finished_at` falls back to the task's creation time or an older poll time when a task is newly marked `SYSTEM_ERROR` by recovery. If that time is already beyond the retention cutoff, the purge removes the task and its owner roles immediately, before it has been retained for `finished_days` after becoming finished.

Record the time when recovery stores a terminal state, and make retention count from that time.
</issue_to_address>

### Comment 3
<location path="pro_tes/retention/tasks.py" line_range="102" />
<code_context>
+    """
+    while not stop.wait(interval):
+        try:
+            task__purge_finished_tasks.delay()
+        except Exception:
+            logger.exception("Could not purge finished tasks")
</code_context>
<issue_to_address>
**Purges stop being scheduled**

When the broker is unavailable when the initial purge is published, `purge_on_start` lets the initial `.delay()` exception escape before it creates the periodic thread, so that worker schedules no further purges until it restarts.

Ensure the periodic thread is created even if publishing the initial purge fails.
</issue_to_address>

### Comment 4
<location path="pro_tes/retention/purge.py" line_range="134-143" />
<code_context>
+    candidates = {
+        "task.state": {"$in": States.FINISHED},
+        DELETED_FIELD: {"$exists": False},
+        "_id": {"$lt": ObjectId.from_datetime(cutoff)},
+    }
+    projection = [
+        "task.id",
+        "task.logs.end_time",
+        "task.creation_time",
+        "tracking.polled_at",
+    ]
+    deleted = 0
+    cursor = tasks.find(candidates, projection=projection).sort("_id", 1)
+    try:
+        for document in cursor:
</code_context>
<issue_to_address>
**Purge scans unrelated tasks**

When the collection has many old unfinished tasks or many finished tasks newer than the cutoff, the candidate filter and `_id` sort have no configured index that bounds both the finished-state and age predicates while providing the requested order: the existing index is `{task.state, tracking.polled_at}`. On a large collection, each purge therefore scans or sorts substantially more documents than the expired finished tasks it processes, adding recurring database load.

Add an index suited to the finished-state and `_id` range/sort query, or change the query and document the resulting scan cost.
</issue_to_address>

Linked issues

#286 feat: retain finished tasks for N days (opt-in) · 6 of 6 met

# Requirement Status Notes
1 Retention is configurable and off by default. ✅ Met custom.retention.finished_days defaults to null; the worker does not start purging unless it is set.
2 Only finished tasks are affected after N days since finishing, or since creation when there is no end time. ✅ Met The purge selects States.FINISHED and uses the last log end time or creation time, bounded by the final-state poll time; this accounts for proTES logs ending at forwarding rather than task completion.
3 Remove owner rules for deleted tasks and never reuse their identifiers. ✅ Met The purge removes owner roles for both task resources through FOCA's adapter and replaces the document with a tombstone retaining task.id; the existing identifier checks continue to include tombstones.
4 Decide whether to archive expired tasks or delete them. ✅ Met The change chooses deletion, documents that tasks are not archived, and leaves tombstones to reserve their identifiers.
5 Run periodically and make purging idempotent and safe with several instances. ✅ Met Each enabled worker purges on startup and periodically; replacement is conditional on the task still being finished, and tasks left after role removal can be retried.
6 Document retention in docs/configuration.md. ✅ Met The new configuration section describes the settings, deletion behavior, tombstones, and worker operation.

Sourcery assessment

Needs a human reviewer. 4 findings to address first, and once enabled, each worker repeatedly replaces eligible task records—including their provenance—with tombstones and removes their owner roles; a mistaken retention period or purge decision can therefore erase an unbounded number of tasks. Reverting stops future purges but cannot restore deleted records or roles; recovery requires a backup.

Blocking findings: pro_tes/retention/purge.py:71, pro_tes/retention/purge.py:77, pro_tes/retention/tasks.py:102, pro_tes/retention/purge.py:143


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

Comment thread pro_tes/retention/purge.py Resolved
Comment thread pro_tes/retention/purge.py Resolved
Comment thread pro_tes/retention/tasks.py Resolved
Comment thread pro_tes/retention/purge.py Resolved
Recovery sets old tasks to SYSTEM_ERROR without a poll (creation cut
off, cancel timed out, tracking ended), so their retention counted from
their creation and they could be deleted at once. Record the time in
tracking.finished_at and count from it too.

Also start the periodic purges when the first one can't be published,
and add an index on task.state and _id, so that runs read finished
tasks oldest first without tombstones.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@uniqueg
uniqueg merged commit 48d1965 into dev Nov 7, 2026
50 checks passed
@uniqueg
uniqueg deleted the feat/task-retention branch November 7, 2026 16: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: retain finished tasks for N days (opt-in)

1 participant