Repository navigation
feat: retain finished tasks for N days (opt-in) - #457
Conversation
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]>
Reviewer's GuideSchema and migrationsDefine 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.
Data structuresAdd the retention settings model and expose it through the custom configuration structure, while defining shared tombstone field and filter constants.
APIMake task retrieval, listing, provenance, and cancellation lookup ignore tombstones so deleted tasks are consistently unavailable through the API.
ImplementationImplement expiration-time calculation, access-role removal, conditional tombstone replacement, and the Celery worker’s startup and periodic purge execution.
ConfigurationRegister the retention worker, provide default settings and deployment examples, and ensure the Celery job include is enabled by the base configuration.
DocumentationDocument retention settings and behavior, operational handling of tombstones, and upgrade considerations.
TestsCover retention configuration, purge timing and concurrency-safe behavior, worker scheduling, recovery timestamps, and tombstone API semantics.
Tips and commandsInteracting with Sourcery
Customizing Your ExperienceAccess your dashboard to:
Getting Help
|
Documentation build overview
4 files changed± configuration/index.html± operations/index.html± reference/index.html± upgrading/index.html |
Codecov Report✅ All modified and coverable lines are covered by tests. 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. 🚀 New features to boost your workflow:
|
There was a problem hiding this comment.
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
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]>
Summary
Opt-in retention of finished tasks (
custom.retention), off by default:finished_days(defaultnull: 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, elsecreation_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_daysis set, each Celery worker purges when it starts and then everyintervalseconds, from a daemon thread of its main process, likeresume_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 ontask.idand_write_doc_to_dbstay unchanged, and identifiers are never used again. Delete only, no archive.Core now filters tombstones out of
get_task,list_tasks,get_task_provenanceand_find_task(cancel). So tombstones are404 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
Adapteron 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 modelRetention,purge.pyand the Celery task and worker thread intasks.py. Its tests are intests/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:pro_tes.retention.tasksinjobs.includeofconfig.yaml. Itsworker_readyhandler starts the thread.CustomConfig.retention) and its defaults inconfig.yaml.DELETED_FIELD/NOT_DELETEDinpro_tes/utils/db.py, used by the four task queries intask_runs.py. Tombstones are a core notion (identifiers are never reused), so the filter stays in core if the purge moves to a plugin.DEFAULT_API_PATHofpro_tes.config_models).FINISHED_AT_FIELDinpro_tes/tasks/track_task_progress.py). Also the index{task.state, _id}inconfig.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_atwhen recovery sets a task toSYSTEM_ERRORwithout 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, elsecreation_time. In proTES' own log,end_timeis the time the task was forwarded to a TES instance, not when it finished, so a task that ran longer thanfinished_dayswould be deleted right after it finished. The age therefore counts from the later of that time andtracking.polled_at, which is set at the poll that stored the final state (regression teststest_long_task_finished_recentlyandtest_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.includein 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.pyfailed (404 expected;KeyErrorin listings) with the core filter stashed, and pass with it.coverage run -m pytest(mongomock; chart tests withhelm dependency build): 1801 passed, 11 skipped;coverage report100%.Against MongoDB 7.0 locally (private
mongod,MONGODB_TEST_URI):tests/retention,tests/limits,tests/tasks,test_server.py,test_access_control.pyandtest_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-reviewerandquality-reviewer. Fixed:DEFAULT_API_PATH;tests/limits/test_endpoint.pyafter the rebase.Review round 2 (
adversarial-reviewer,quality-reviewer): no high or medium findings. Fixed the lows:tracking.polled_atthat is NaN or out of range stopped every run at that task; such tasks are now kept;polled_at) count from when they were forwarded, and that concurrent runs repeat role removals;config.yamlcomment, moved the config tests totests/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 pytest1803 passed, 11 skipped, 100%; MongoDB 7.0:tests/retention,tests/limits,tests/tasks,test_server.py350 passed; ruff, mypy, ast-grep, semgrep, mkdocs clean.CI: all checks passed (
CI passed).Declined review findings
batch_size500 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 (abatch_sizeof at most 50 stays within the window); a full reload is correct, only slower.Open questions
None.
🤖 Generated with Claude Code