Skip to content

feat(retention): cap soft-delete purge and version-history prune per run - #45029

Merged
aminghadersohi merged 20 commits into
apache:masterfrom
mikebridge:sc-124086-retention-per-run-cap
Oct 10, 2026
Merged

aminghadersohi merged 20 commits into
apache:masterfrom
mikebridge:sc-124086-retention-per-run-cap

Conversation

@mikebridge

@mikebridge mikebridge commented Oct 6, 2026 •

Copy link
Copy Markdown
Member

SUMMARY

The scheduled soft-delete purge and version-history prune remove everything eligible in a single run. After cleanup has been paused, or the first time retention is enabled on an existing deployment, that can be a large backlog deleted at once.

This adds a per-run cap to both scheduled tasks:

  • SOFT_DELETE_PURGE_MAX_PER_RUN (default 1000): soft-deleted root objects purged per run. A chart, dashboard or dataset together with its cascade counts as one; a cascade is never split.
  • VERSION_HISTORY_PRUNE_MAX_TRANSACTIONS_PER_RUN (default 1000): whole version-history transactions pruned per run; a transaction is never split.
  • 0 or None means no cap. Invalid values fail closed before any destructive work.

A capped run reports cap_reached and how much remains, and the rest drains on later runs. Counting happens only after commit. The cap only ever reduces what a run deletes: eligibility, blocked-by-reference, restore and live-anchor protections are unchanged.

Dry-run (including the new VERSION_HISTORY_PRUNE_DRY_RUN) counts the whole eligible backlog and reports estimated_capped_runs, so operators can size the first live run.

This is a behaviour change: the cap is on by default. UPDATING.md and the version-history and recently-archived docs describe it.

TESTING INSTRUCTIONS

  • pytest tests/unit_tests/tasks/test_deletion_retention.py tests/unit_tests/tasks/test_version_history_retention.py (142 pass)
  • Integration: test_cap_preserves_whole_transactions_across_runs
  • Covered: backlogs spanning batches and models, exact cap and remainder across repeated runs, 0/None and invalid values, dry-run with no writes, retry accounting and the cap-reached signal.
  • Not run locally: PostgreSQL and MySQL behaviour.

ADDITIONAL INFORMATION

  • Has associated issue:
  • Required feature flags:
  • Changes UI
  • Includes DB Migration
  • Introduces new feature or API
  • Removes existing feature or API

The cap bounds committed deletions, not candidate evaluations: objects blocked by references are re-evaluated each run. Dry-run counts run without serializable isolation, since they only estimate. The manual superset deletion-retention CLI has no bulk purge entry point, so it is unaffected.

🤖 Generated with Claude Code

@github-actions github-actions Bot added the doc Namespace | Anything related to documentation label Oct 6, 2026
@netlify

netlify Bot commented Oct 6, 2026 •

Copy link
Copy Markdown

✅ Deploy Preview for superset-docs-preview ready!

Name Link
🔨 Latest commit 8bf86da
🔍 Latest deploy log https://app.netlify.com/projects/superset-docs-preview/deploys/6ac8091d0533f2000847a229
😎 Deploy Preview https://deploy-preview-45029--superset-docs-preview.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.
🤖 Make changes Run an agent on this branch

To edit notification comments on pull requests, go to your Netlify project configuration.

@codecov

codecov Bot commented Oct 6, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 98.14815% with 5 lines in your changes missing coverage. Please review.
✅ Project coverage is 82.76%. Comparing base (34b3d65) to head (b7ee915).
⚠️ Report is 48 commits behind head on master.

Files with missing lines Patch % Lines
superset/tasks/version_history_retention.py 97.05% 2 Missing and 1 partial ⚠️
superset/tasks/deletion_retention.py 98.72% 1 Missing and 1 partial ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##           master   #45029      +/-   ##
==========================================
+ Coverage   82.64%   82.76%   +0.11%     
==========================================
  Files        3007     3013       +6     
  Lines      187318   192233    +4915     
  Branches    43399    44524    +1125     
==========================================
+ Hits       154811   159098    +4287     
- Misses      29742    30097     +355     
- Partials     2765     3038     +273     
Flag Coverage Δ
hive 35.25% <11.48%> (-0.93%) ⬇️
mysql 53.71% <62.96%> (-1.40%) ⬇️
postgres 53.72% <62.96%> (-1.41%) ⬇️
presto 37.08% <11.48%> (-0.97%) ⬇️
python 86.52% <98.14%> (+0.07%) ⬆️
sqlite 53.46% <62.96%> (-1.39%) ⬇️
unit 80.21% <97.40%> (+0.49%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ 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.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@mikebridge
mikebridge marked this pull request as ready for review October 6, 2026 19:11
@codeant-ai-for-open-source

codeant-ai-for-open-source Bot commented Oct 6, 2026 •

Copy link
Copy Markdown
Contributor

CodeAnt PR Risk: Low Risk

  • The PR appears safe to merge based on the supplied code and tests.
  • The new per-run caps preserve whole version transactions and root purges, and stop processing when a commit outcome is uncertain.
  • The dry-run backlog scan closes each read connection between windows, addressing the concern about holding a snapshot for the full scan.

Assessed commit: b7ee9156476a

Slice,
Dashboard,
]
assert [entry.kwargs["max_per_run"] for entry in purge.call_args_list] == [

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This only asserts allowances of 2 for every call, and the first model either uses the whole budget or none of it. If _scan_purge_models passed the original cap to each model instead of the remaining budget, this test would still pass, and a run with cap 2 could purge three roots. Could you add a case where the first model purges one root (cap 2) and the second has two eligible roots, asserting the second gets max_per_run=1 and only one more root is purged?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks, that was a real gap in the test. I added a case where the first model purges one root under a cap of two and the second model has two eligible roots (afb0591).

The test runs the real _purge_model with the cascade stubbed, so the second model's budget of one shows up as exactly one purge and a remaining budget of zero. It fails if the original cap is passed to each model. The budget code itself was already right; only the test changed.

@aminghadersohi
aminghadersohi self-requested a review October 6, 2026 20:21

@EnxDev EnxDev left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Read through this one and the cap logic holds up. The cascade and transaction boundaries are respected, the shared budget across models is right (and the new test pins it), and invalid caps fail closed before any deletes.

Left two notes inline, both on the version-history side: the remainder probe starting from id 0, and the dry-run type check landing in the failure path.

conn: sa.engine.Connection
with db.engine.connect() as conn:
window: _PruneWindow = _resolve_prune_window(
conn, cutoff, _live_bearing_tables(tables), 0, _MAX_PRUNE_BATCH

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The probe always starts at id 0, but after a capped run everything below the last window is either already pruned or a live anchor. On an instance with a lot of charts and dashboards nobody has touched in 30+ days, the first 1000 aged candidates end up being all anchors, so this reports remaining_eligible=0 with remaining_count_complete=False on every run and the gauge never moves.

Could _add_prune_cap_stats take the after_id the loop stopped at and probe from there? The remainder would then land on the real backlog. A unit test with a window of preserved ids ahead of the prunable ones would cover it.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed. The bounded remainder probe now starts at the scan cursor from the last live pass, which keeps the partially processed last window in view while skipping earlier preserved-anchor windows. I added a regression with a full preserved window followed by a capped prune and a remaining eligible transaction; it fails with the old zero result and passes with the cursor fix. Fixed in 4ae5201.

return {"skipped_invalid_cap": 1}
dry_run: bool = current_app.config.get("VERSION_HISTORY_PRUNE_DRY_RUN", False)
if type(dry_run) is not bool:
raise ValueError("VERSION_HISTORY_PRUNE_DRY_RUN must be a bool")

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A non-bool here raises into the broad except below, so it logs a full "task failed" traceback, bumps .failed, and returns {"error": 1}. That looks like a broken prune to whoever is on call, while a bad cap just above gets a clean skipped_invalid_cap.

Worth handling it the same way, with a warning, a skipped_invalid_dry_run counter, and an early return?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed. A non-boolean dry-run value now logs a warning, increments skipped_invalid_dry_run once, and returns without invoking the prune implementation. Six invalid types are covered; they previously returned {"error": 1} and incremented the failure counter, while boolean values continue through the existing path. Fixed in 4ae5201.

engine: MagicMock = MagicMock()
full_window: version_history_retention._PruneWindow = (
version_history_retention._PruneWindow(
prunable=[],

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Both windows here have prunable=[] and the mocked _resolve_prune_window ignores its after_id argument, so this only proves the connection is closed between windows. If _count_prunable reset total on each window, or stopped advancing after_id to max_candidate_id, the test would still pass, and eligible_backlog / estimated_capped_runs in dry-run would silently undercount a multi-window backlog. Could you give the first window a couple of prunable IDs and the final window one more, then assert the total is their sum and that the second _resolve_prune_window call receives the first window's max_candidate_id?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed. The test now uses two prunable transactions in the first full window and one in the final window, asserts the total is three, and verifies the second resolver call starts after the first window's maximum candidate ID. I confirmed it fails both when the count resets per window and when the cursor stops advancing, while retaining the connection-closure check. Fixed in 844caa4.

the cap. It bounds committed deletions, not candidate evaluations: blocked roots
are re-evaluated every run, so a blocked-heavy backlog can still require
substantial work. A negative, boolean, string, or fractional value stops the
scheduled task without purging. A live run reports `cap_reached` and `remaining_eligible`

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This says a live run reports cap_reached and remaining_eligible, right after telling operators they can set 0 or None to remove the cap. In unlimited mode _add_purge_cap_stats returns early, so none of cap_reached, remaining_eligible, remaining_count_complete (or the matching gauges) are emitted. An operator who switches to unlimited and keeps alerting on those fields would see them vanish and may read that as a measurement failure. Should this sentence say the fields appear only when a positive cap is configured?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed. The guide now says the cap and remainder fields and gauges appear only for a positive-cap live run. Unlimited mode omits them, so monitoring should not treat their absence after disabling the cap as a measurement failure. Fixed in 844caa4.

@github-actions github-actions Bot added the requires:rebase Requires rebasing on top of current master label Oct 7, 2026
Preserve the per-run purge budget and rotation while carrying forward per-root scan failure isolation and outage reporting.
Preserve shared per-run budgets and cursor behavior while integrating per-root scan-failure isolation. Keep remainder counts incomplete after scan failures and reset the session after count errors.
)


def test_purge_cap_counts_committed_roots_across_batches(app_context: None) -> None:

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The docstring says a failed or blocked root doesn't consume the budget, but the fixture only returns a plain purged=False result: no blocked_reason, and _purge_one never raises. If the guard were changed to count purged + blocked + failures against max_per_run, this test would still pass, and a persistent blocked root at the lowest ID would starve every eligible root behind it on each run. Could you drive _purge_model with a blocked result, an exception, then two successes under cap 2 and assert (2, 0, 1, 1)?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added a cap-2 regression test that drives _purge_model with one blocked root, one root that raises, then two successful roots. It asserts the counts are (2, 0, 1, 1) and that all four IDs were attempted, so blocked and failed attempts do not consume the purge budget. The test is in a54556a.



@pytest.mark.parametrize("invalid", [None, 0, 1, "false", [], {}])
def test_scheduled_prune_skips_invalid_dry_run_before_work(

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The scheduled-entrypoint tests cover the defaults (max_per_run=1000, dry_run=False) and invalid values, but no test sets a valid VERSION_HISTORY_PRUNE_DRY_RUN=True or a non-default cap through prune_old_versions(). If the wrapper hardcoded either argument, every test here would still pass, and an operator's preview run would delete data. Could you add one case with dry_run=True and cap 2 that asserts both values reach _prune_old_versions_impl?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added a scheduled-task test that sets VERSION_HISTORY_PRUNE_DRY_RUN=True and a cap of 2 and calls prune_old_versions(). It asserts _prune_old_versions_impl receives both dry_run=True and max_per_run=2, so a wrapper that hardcodes either value now fails. The test is in a54556a.

@EnxDev EnxDev left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Follow-up to my earlier pass on afb0591.

Both of those points are fixed, each with a test that would catch them coming back: the remainder probe now starts from the scan cursor, and a non-bool dry-run value gets its own clean skip instead of landing in the failure path. The new commit-uncertain handling is careful on both tasks. A lost ack stops the run instead of retrying past the cap, and a commit the database actually rejects is still retried.

One note inline: the UPDATING.md paragraph still describes the old retry behaviour.

Comment thread UPDATING.md Outdated

Entity version history (the `version_transaction` / `*_version` shadow tables that back version capture) is aged out by a nightly Celery beat task, `version_history.prune_old_versions` (`superset.tasks.version_history_retention`).

**Scheduled-run cap (behavior change):** `VERSION_HISTORY_PRUNE_MAX_TRANSACTIONS_PER_RUN` defaults to 1000 whole prunable transactions per invocation; associated shadow and change rows remain atomic. `0` or `None` restores unlimited runs. Invalid values skip the task before deletion. Capped results report `cap_reached`, `remaining_eligible`, and `remaining_count_complete`; the remainder is a lower bound from one candidate window after the live scan's stopping point when the probe does not cover the backlog, and `None` if the probe fails after committed deletion. Physical shadow-row counts remain separate. `VERSION_HISTORY_PRUNE_DRY_RUN=True` scans the entire prunable backlog without writes and reports the exact `eligible_backlog` and `estimated_capped_runs`; non-boolean values skip the scheduled task without deleting history. A large backlog now drains over successive scheduled runs rather than in one invocation. The cap is per task invocation, not a quota shared across concurrent workers. If the database commits a window but the client loses its acknowledgement, retries can prune additional windows beyond the cap (up to two extra windows per retried pass with the three-attempt policy); all pruned transactions still meet the retention policy.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The last sentence here still says a lost commit ack lets retries prune up to two extra windows past the cap. That's no longer true: _run_prune_pass raises _PruneCommitUncertainError on an uncertain commit, _run_pass_with_retry doesn't retry it, and version-history.mdx already describes it that way.

Operators read UPDATING.md first, so could we bring it in line? Something like: "If the database commits a window but the client loses its acknowledgement, the task stops without retrying that window and reports an error, so it never prunes past the cap."

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks, the old sentence was stale. In 7868f04f16, UPDATING.md now says that when a commit outcome is classified as uncertain, the task reports an error and stops without retrying that window, so that outcome cannot prune past the cap. I scoped the wording to the classification the code can establish; the retry path and task error handling support it.

@github-actions github-actions Bot removed the requires:rebase Requires rebasing on top of current master label Oct 7, 2026
version_history_retention, "_resolve_prune_window", return_value=window
),
patch.object(
version_history_retention, "_delete_for_transactions", return_value=0

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nothing in the tests pins which transaction IDs reach the shadow-table deletes when the cap truncates the window: here _delete_for_transactions is patched to return 0 and the window has a single ID with max_prune=1, so the cap never binds, and the integration test only checks transaction counts and that a live row survives. If a later change passed window.prunable instead of the capped tx_ids to the parent/child/M2M deletes, these tests would still pass while history beyond the cap is erased. Could a _run_prune_pass case with prunable [1, 2, 3] and max_prune=2 assert each delete is called with [1, 2] only?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed. 7868f04f16 adds a _run_prune_pass case with prunable IDs [1, 2, 3] and max_prune=2. It asserts parent, child, M2M and transaction deletes all receive [1, 2]. The test fails if the parent shadow delete is changed to use the uncapped window, and the full focused file passes (67 tests).

@aminghadersohi aminghadersohi left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

One gap in the uncertain-commit coverage, inline.

Comment thread superset/tasks/deletion_retention.py Resolved
Comment thread UPDATING.md Outdated

Purging is **live by default** (`SOFT_DELETE_PURGE_DRY_RUN=False`), so the retention promise above is real on a stock deployment. Set it to `True` to have the task log `would_purge` counts and delete nothing — the lever is retained, so an operator can return to dry-run at any time. Note `would_purge` is an **upper bound** — it counts every entity past the retention window without evaluating deletion blockers, so a real run may purge fewer (entities referenced by report schedules or set as a user's welcome dashboard are blocked and reported separately). The task only acts while the `SOFT_DELETE` rollout flag is on; it now ships on by default.

**Scheduled-run cap (behavior change):** `SOFT_DELETE_PURGE_MAX_PER_RUN` defaults to 1000 successful root-entity purges across charts, dashboards, and datasets per invocation. One root plus its cascade counts as one; physical row counts are separate. The cap bounds committed deletions, not candidate evaluations: blocked roots are re-evaluated on every run, so a blocked-heavy backlog can still require substantial work. Set `0` or `None` for unlimited scheduled purging. Invalid values skip the task before deletion. Capped runs report `cap_reached` and `remaining_eligible` (aged supported roots, including blocked roots); `remaining_count_complete=False` and a null remainder signal a post-commit measurement failure without hiding successful purge totals. Model priority rotates by day so a sustained backlog in one model does not indefinitely exclude the others. Dry-run still counts the entire eligible backlog without writes and reports `eligible_backlog` and `estimated_capped_runs`; this is an upper-bound estimate when references block deletion. The cap is per task invocation, not a quota shared across concurrent workers. The manual `superset deletion-retention force-purge` command stays uncapped.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This says a post-commit measurement failure is what remaining_count_complete=False and a null remainder mean, but _add_purge_cap_stats also emits exactly that pair when a model scan fails or a commit outcome is uncertain, before or without any successful purge. An operator reading this would treat the alert as a monitoring gap and not look at the failed scan or uncertain commit behind it. Could this name those cases too, or point to the failed/error counters as the way to tell them apart?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good catch, addressed in d5cb98e100. UPDATING and the archive guide now name the three cases (scan failure, uncertain commit and remainder-measurement failure, including runs with no confirmed purge) and point to scan_failures, commit_uncertain, the remainder-failure counter and the logs.

@geido geido left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Went over the cap paths again on top of the earlier rounds and they hold up. Only committed work counts against the budget, a cascade or transaction is never split, an unacknowledged commit stops the run instead of retrying past the cap, and invalid values stop before any write, including the audit reconcile.

I also ran the version-history prune against SQLite with synthetic shadow tables in a few backlog shapes (live anchors ahead of prunable rows, a cap that lands mid-window). The remainder probe was exact when it covered the backlog and flagged as a lower bound when it didn't. So the CodeAnt risk note about probing after the full window doesn't apply at 7868f04: the loop stops before moving the cursor.

One non-blocking note inline about the default acting as a daily ceiling.

Comment thread superset/config.py
VERSION_HISTORY_RETENTION_DAYS: int = _parse_version_history_retention_days()
# Maximum committed transactions pruned per scheduled run; 0 or None is unlimited.
# Set an int in superset_config.py; this key has no automatic environment parsing.
VERSION_HISTORY_PRUNE_MAX_TRANSACTIONS_PER_RUN: int | None = 1000

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Non-blocking: with both retention tasks on a daily beat, this default also becomes a steady-state ceiling of 1000 pruned transactions a day, not only a bound on a catch-up run. Capture is on by default and a chart, dashboard or dataset save usually writes a transaction, so an instance that saves more than that per day never drains. cap_reached stays at 1 and history keeps growing. SOFT_DELETE_PURGE_MAX_PER_RUN has the same math for archived objects.

The docs say a large backlog drains over successive runs, which only holds while daily inflow stays below the cap. Worth adding a line to both guides: size the cap (or run the task more often) above daily inflow, and treat cap_reached staying at 1 across runs as falling behind. Since each 1000-candidate window is already its own bounded transaction, a higher default for version history might also be reasonable.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good point, addressed in d5cb98e100. Both guides now explain that at 1,000 units/day, 1,500 newly eligible units/day adds 500/day of backlog, and recommend sizing the cap or beat frequency above eligible inflow with catch-up headroom. Could we keep the defaults as they are here, and let repeated cap hits plus the backlog/completeness and failure signals guide operator tuning?

scan.assert_called_once()


def test_scheduled_purge_rejects_invalid_cap_before_work(app_config: Config) -> None:

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nothing pins that the scheduled purge forwards a positive cap: every scheduled-entrypoint test here uses 0 (unlimited) or an invalid value, and the positive-cap tests call _purge_impl/_purge_model directly. Hard-coding max_per_run=None at the _purge_impl(...) call in purge_soft_deleted would leave this file green while the default 1000 is silently ignored. Could you add a scheduled-entrypoint case with SOFT_DELETE_PURGE_MAX_PER_RUN set to 2 that asserts _purge_impl receives max_per_run=2?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good catch, addressed in ce1dd20097. A new scheduled-entrypoint test sets the cap to 2 and asserts _purge_impl receives max_per_run=2. Hardcoding None makes it fail, and with the existing implementation all 178 focused tests pass. That should close the positive-cap forwarding gap without touching the production path, which was already correct.

Answer sadpandajoe's scheduled-entrypoint review: a configured cap of two must reach the purge implementation rather than silently become unlimited. The new assertion fails when the forwarding argument is replaced with None; production behavior is unchanged.
Master adds a dry-run chart-preservation test using the former five-value purge result. Consume the cap branch's named result and assert commit_uncertain is false, preserving chart-detach and no-write behavior without changing production logic.
db.session.scalar(
sa.select(sa.func.count())
.select_from(table)
.where(table.c.deleted_at.is_not(None), table.c.deleted_at < cutoff)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

remaining_eligible and estimated_capped_runs are built on this query, but every test patches _count_eligible (side_effect=[0, 3, 0, 2] etc.) and the integration test only exercises the version-history side, so the predicate itself never runs against a database. If table.c.deleted_at < cutoff were dropped or flipped, recently archived roots would be reported as eligible backlog and operators would size the cap against a number that is too large, with every test still green. Could a DB-backed case seed roots before, exactly at and after the cutoff plus a live (not soft-deleted) root, and assert the count is only the before-cutoff one?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good catch: every caller patched _count_eligible, so its predicate never ran. d4c8c32469 adds a SQLite-backed test on the real slices table. It seeds two roots archived before the cutoff, one exactly at the cutoff, one after it and one live root, then asserts the count is 2. It also asserts the purge scan selects the same two IDs, so the test checks that the reported backlog agrees with the rows the purge scans.

  • Dropping the cutoff condition fails the test (4 ≠ 2).
  • Changing < to <= fails it (3 ≠ 2).
  • Flipping the comparison fails it (1 ≠ 2).

All 405 focused retention tests and the branch-file pre-commit checks pass.

@aminghadersohi
aminghadersohi self-requested a review October 9, 2026 01:07
The remaining-eligible and estimated-capped-runs stats are built on
_count_eligible, which every purge test patched. Seed real slices rows
before, at and after the cutoff plus a live row, and assert both the count
and the purge scan select only the rows archived before the cutoff.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
total_retried += retries
for key in totals:
totals[key] += pass_stats.get(key, 0)
if max_per_run is not None and totals["pruned_transactions"] >= max_per_run:

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

With this early exit a second run is no longer a no-op: with 2,000 eligible transactions and the default cap, two back-to-back runs each prune 1,000, so the module docstring's "Idempotent: a second run prunes nothing" (line 43) is now wrong. deletion_retention.py has the same "a re-run with the same clock and data removes nothing" claim in its docstring (line 25), which the per-run cap also breaks. An operator who re-runs the task to double-check would delete another batch. Should both docstrings describe capped runs as draining the backlog over successive runs instead?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed. Updated both module docstrings in 38f9195 to describe safe, repeatable capped runs: each run removes at most the configured number of transactions or root entities, and successive runs drain the remaining prunable/purgeable backlog. The wording also accounts for blocked roots and newly eligible items. I checked UPDATING.md and the retention docs; their backlog descriptions already reflect successive runs. This changes documentation only; the hooks pass.

@EnxDev EnxDev left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Went through the commits since my approval and my approval still stands.

The UPDATING.md sentence about retries is fixed and now matches what _run_pass_with_retry actually does. The new wording on incomplete remainders names counters that really exist (scan_failures, commit_uncertain, deletion_retention.remainder_count_failed), and the 1,000-per-day capacity math lines up with the daily beat entries for both tasks. I also checked that the DB-backed _count_eligible test guards the predicate: drop the cutoff and it fails with 4 instead of 2. Nothing new from me.

)
except Exception:
try:
transaction.rollback() # pylint: disable=consider-using-transaction

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The old with conn.begin(): rolled back automatically when a delete raised; this explicit except branch is now what keeps a failure between the parent-shadow delete and the transaction-row delete from being committed. No test makes _delete_for_transactions or the transaction delete raise inside the real _run_prune_pass: test_retention_retries_on_serialization_failure fails before the pass runs, and test_prune_failed_rollback_stops_retry fails at commit. If this rollback() became a commit(), every test here would still pass while a half-applied prune (parent history gone, child rows and the transaction left) went through. Could you add a case where the child-shadow delete raises after the parent delete and assert the error propagates and rollback (not commit) is called?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks, good catch. Added test_prune_child_delete_failure_rolls_back_parent_delete in f03bdd3. It runs the real _run_prune_pass with the parent delete succeeding and the child-shadow delete raising. It asserts that the error propagates, that rollback() is called once, and that commit() isn't called and the transaction-row delete never runs.

Turning the rollback() into commit() makes the test fail. Test-only change.

# first page.
db.session.rollback() # pylint: disable=consider-using-transaction
totals.scan_failures += 1
scan_failures += 1

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If _purge_model hits a scan error after it has already committed some purges, its handler at line 475 calls db.session.rollback() before returning the counts it kept. If that rollback raises (for example the connection is gone), the exception escapes to this handler, which only counts a scan failure and continues without subtracting those committed purges from remaining_budget. With a cap of 1,000, a model that has committed 500 roots and then fails this way leaves the next model a full 1,000, so one run can delete 1,500 roots while reporting 1,000.

Should an exception that escapes _purge_model stop the pass, or should the model's committed count be kept even when the rollback fails, so the shared budget stays accurate?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks, this reproduces. Fixed in 037982c: _purge_model logs a failed scan rollback and still returns the committed purge count, so the next model receives only the remaining budget.

The regression runs both model loops with a failed second page and a rollback that raises. It failed before the fix by allowing a third root under a cap of two, and now passes alongside the successful-rollback case. All 113 deletion-retention tests and changed-file hooks pass.

Comment thread superset/tasks/deletion_retention.py Resolved
"superset.versioning.retention.remaining_count_complete", 0
)
assert run_pass.call_args_list[0].kwargs["max_prune"] == 3
assert run_pass.call_args_list[1].kwargs["max_prune"] == 1

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The live-pass loop test checks the per-pass budget (max_prune) but never which cursor each pass receives: the mocked _run_pass_with_retry ignores its after_id argument, and the probe-cursor test only shows what the final after_id is. If the loop kept calling _run_pass_with_retry(cutoff, tables, 0, ...) while still tracking max_candidate_id, a backlog whose first 1,000 aged transactions are all live anchors would re-scan those anchors on every pass and never reach prunable history, yet every test here would still pass. Could you assert that the second call receives the first window's max_candidate_id as its cursor (e.g. run_pass.call_args_list[1].args[2] == 1000)?

@aminghadersohi
aminghadersohi merged commit 38ad115 into apache:master Oct 10, 2026
71 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

doc Namespace | Anything related to documentation size/XXL

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants