Skip to content

feat(versioning): gate history APIs and runtime capture - #44514

Merged
aminghadersohi merged 21 commits into
apache:masterfrom
mikebridge:sc-121613-version-history-api-gate
Sep 28, 2026
Merged

aminghadersohi merged 21 commits into
apache:masterfrom
mikebridge:sc-121613-version-history-api-gate

Conversation

@mikebridge

@mikebridge mikebridge commented Sep 22, 2026 •

Copy link
Copy Markdown
Member

SUMMARY

Add host-policy support for version-history access/capture and soft-delete retention while keeping commercial eligibility outside Apache core. Disabled history APIs return 404 with existing permissions preserved. Ordinary saves still succeed when capture is denied, without creating history; transaction-scoped capture checks prevent untracked version restores.

An optional authoritative SOFT_DELETE_RETENTION_DAYS_FUNC callback takes precedence over stored shared values. Invalid or unavailable host policy defers purging; without the callback, ordinary shared-value/config resolution remains. Both VERSION_HISTORY_RETENTION_DAYS and SOFT_DELETE_RETENTION_DAYS use canonical integer settings/environment names with a 30-day core default; zero disables cleanup. The canonical version-history name is preferred; the previously shipped prefixed name remains a deprecated compatibility alias when the canonical setting is absent.

HOST_POLICY_API_VERSION = 1 identifies the complete API/capture/retention contract for downstream adoption. Preset shell #5218 depends on this contract and must adopt a matching merged core pin before deployment. No tier rules, live configuration changes, deployment, or cleanup activation are included here.

BEFORE/AFTER SCREENSHOTS OR ANIMATED GIF

Not applicable: backend contracts and documentation.

TESTING INSTRUCTIONS

  • Current core candidate: 479 affected tests passed after the final test-annotation correction; the earlier broad affected-unit run passed 3,276 tests on the functional repair before documentation and test-name polish. The prior paired shell validation passed 337 tests; shell was not changed or rerun for this core-only follow-up.
  • Core coverage includes config/environment resolution, invalid canonical/legacy retention values deferring cleanup, request-session capture checks, CLI behavior, retention tasks, runtime capture, and history API gates.
  • Required pre-commit checks on every changed file and the local pre-push gate passed, including MyPy, Ruff/format and applicable core pylint checks. An independent Astra review approved the exact published tree after its one test-annotation finding was fixed.
  • External services and unrelated DB/network startup were substituted in local tests. Fresh remote CI is running for this head; live Manager/Split, production database dialects and deployed acceptance are not claimed as passing.

ADDITIONAL INFORMATION

Preserve ordinary ORM saves when host capture is denied, without mutating global listeners. Bind restore authorization to its write transaction so changing policy cannot produce an untracked restore. Keep OSS defaults and independent retention; add persisted regressions and API availability tests.
@github-actions github-actions Bot added api Related to the REST API doc Namespace | Anything related to documentation labels Sep 22, 2026
@netlify

netlify Bot commented Sep 22, 2026 •

Copy link
Copy Markdown

✅ Deploy Preview for superset-docs-preview ready!

Name Link
🔨 Latest commit cbcf6a0
🔍 Latest deploy log https://app.netlify.com/projects/superset-docs-preview/deploys/6ab6dabc2eee2d00070d5d4c
😎 Deploy Preview https://deploy-preview-44514--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 Sep 22, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 96.68874% with 10 lines in your changes missing coverage. Please review.
✅ Project coverage is 81.21%. Comparing base (4bce27f) to head (903a799).
⚠️ Report is 34 commits behind head on master.

Files with missing lines Patch % Lines
superset/config.py 90.66% 6 Missing and 1 partial ⚠️
superset/versioning/utils.py 80.00% 2 Missing and 1 partial ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##           master   #44514      +/-   ##
==========================================
+ Coverage   81.11%   81.21%   +0.10%     
==========================================
  Files        2955     2963       +8     
  Lines      178330   179187     +857     
  Branches    41311    41462     +151     
==========================================
+ Hits       144651   145529     +878     
+ Misses      30974    30950      -24     
- Partials     2705     2708       +3     
Flag Coverage Δ
hive 36.71% <29.39%> (-0.11%) ⬇️
javascript 76.50% <100.00%> (+<0.01%) ⬆️
mysql 56.09% <61.14%> (+0.05%) ⬆️
postgres 56.09% <61.14%> (+0.05%) ⬆️
presto 38.65% <44.25%> (-0.08%) ⬇️
python 85.55% <96.28%> (+0.16%) ⬆️
sqlite 55.81% <62.83%> (+0.06%) ⬆️
unit 78.21% <94.93%> (+0.55%) ⬆️

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.

@github-actions github-actions Bot added the i18n Namespace | Anything related to localization label Sep 22, 2026
Align the unreleased application and environment key with VERSION_HISTORY_RETENTION_DAYS without a legacy alias. Preserve duration policy and pin environment loading and runtime task lookup in regression tests.
@bito-code-review

Copy link
Copy Markdown
Contributor

The documentation for version history has been updated to reflect that the VERSION_HISTORY feature flag now controls both the UI and the associated APIs (version-list, version-snapshot, activity, and version-restore). Since these APIs are now gated by the feature flag, the documentation correctly includes them as part of the feature's scope. There is no mention of a "dataset history UI" that needs to be omitted; the documentation describes the unified version history feature for charts, dashboards, and datasets.

Comment thread docs/static/feature-flags.json Resolved
@mikebridge
mikebridge marked this pull request as ready for review September 22, 2026 19:39

@bito-code-review bito-code-review Bot 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.

Code Review Agent Run #1af5f9

Actionable Suggestions - 4
  • superset/versioning/utils.py - 1
  • docs/docs/using-superset/version-history.mdx - 2
    • Retention cap undocumented, silent fallback · Line 75-77
    • Undocumented downgrade-grace clause · Line 84-84
  • tests/unit_tests/config_test.py - 1
Additional Suggestions - 6
  • superset/config.py - 1
    • Duplicated bounds, unlogged value · Line 1034-1046
      `_parse_soft_delete_retention_days` hardcodes the business bounds `30` and `36500` inline, while the sibling `_parse_version_history_retention_days` (lines 1786-1814) encodes the same values as `_DEFAULT_VERSION_HISTORY_RETENTION_DAYS`/`_MAX_VERSION_HISTORY_RETENTION_DAYS`. The duplicated 36500 cap can drift between the two parsers. Its warning also omits the offending value (`%r`), unlike the sibling's messages, hampering ops diagnosis of bad env seeds.
  • tests/unit_tests/config_test.py - 1
    • Duplicated env/runpy test scaffold · Line 113-118
      Lines 113-118 repeat the delenv/setenv/`runpy.run_path(config.__file__)`/assert-int scaffolding of lines 70-78 with only the env key changed. Extracting a shared helper keeps both verification surfaces (raw module dict vs Flask `app.config`) while removing the copy that can drift when env handling changes.
  • tests/unit_tests/tasks/test_deletion_retention.py - 2
    • Untyped lambda in test stub · Line 51-51
      BITO adaptive rule 13350 asks for typed named helpers over untyped lambdas. `lambda: days` hides the `-> object` contract `resolve_retention_window` expects from `SOFT_DELETE_RETENTION_DAYS_FUNC` (`superset/config.py:1052`). A nested `def host_policy() -> object: return days` keeps the closure while documenting the type. Same pattern applies at line 65.
    • Untyped lambda in test stub · Line 65-65
      Same BITO rule 13350 violation as line 51: `lambda: value` is an untyped stub for `SOFT_DELETE_RETENTION_DAYS_FUNC`, obscuring the `-> object` contract `resolve_retention_window` validates (`superset/commands/deletion_retention/window.py:86`). A nested `def host_policy() -> object: return value` documents it.
  • superset/commands/deletion_retention/window.py - 1
    • Magic retention bound duplicated · Line 86-86
      Line 86 hardcodes the retention ceiling `36500` (~100 years), duplicating the same bare literal in `_parse_soft_delete_retention_days` (`superset/config.py:1041`). If one copy is updated and the other is not, a valid host policy gets rejected (purge skipped) or an out-of-range value accepted. Name it once — e.g. `_MAX_RETENTION_DAYS` beside `_DEFAULT_RETENTION_DAYS` — and reference it in both validators.
  • superset/versioning/utils.py - 1
    • Dead constant, no consumer · Line 29-32
      `HOST_POLICY_API_VERSION` is defined but has no consumer anywhere in the repo (grep across *.py finds only this definition). The comment says downstream startup may require this version before installing policy callbacks, but no such check exists here, so the constant is dead and its contract claim is unenforced.
Review Details
  • Files reviewed - 23 · Commit Range: 7f79f55..0afd908
    • docs/docs/using-superset/version-history.mdx
    • superset/charts/api.py
    • superset/cli/deletion_retention.py
    • superset/commands/deletion_retention/window.py
    • superset/commands/version_restore.py
    • superset/config.py
    • superset/dashboards/api.py
    • superset/datasets/api.py
    • superset/extensions/__init__.py
    • superset/tasks/version_history_retention.py
    • superset/translations/messages.pot
    • superset/versioning/baseline/listener.py
    • superset/versioning/changes/listener.py
    • superset/versioning/queries.py
    • superset/versioning/unit_of_work.py
    • superset/versioning/utils.py
    • superset/views/base.py
    • tests/integration_tests/versioning/retention_prune_tests.py
    • tests/unit_tests/config_test.py
    • tests/unit_tests/tasks/test_deletion_retention.py
    • tests/unit_tests/tasks/test_version_history_retention.py
    • tests/unit_tests/versioning/test_api_feature_flag.py
    • tests/unit_tests/versioning/test_runtime_capture.py
  • Files skipped - 2
    • UPDATING.md - Reason: Filter setting
    • docs/static/feature-flags.json - Reason: Filter setting
  • Tools
    • MyPy (Static Code Analysis) - ✔︎ Successful
    • Astral Ruff (Static Code Analysis) - ✔︎ Successful
    • Whispers (Secret Scanner) - ✔︎ Successful
    • Detect-secrets (Secret Scanner) - ✔︎ Successful

Bito Usage Guide

Commands

Type the following command in the pull request comment and save the comment.

  • /review - Manually triggers an incremental AI Review.

  • /review full - Manually triggers a full AI Review.

  • /pause - Pauses automatic reviews on this pull request.

  • /resume - Resumes automatic reviews.

  • /resolve - Marks all Bito-posted review comments as resolved.

  • /abort - Cancels all in-progress reviews.

Refer to the documentation for additional commands.

Configuration

This repository uses Superset You can customize the agent settings here or contact your Bito workspace admin at [email protected].

Documentation & Help

AI Code Review powered by Bito Logo

Comment thread superset/versioning/utils.py Resolved
Comment thread tests/unit_tests/config_test.py Resolved
Accept the explicit -1 sentinel without computing a future cutoff, preserve live records and purge guards, and document permanent purge history removal.
Preserve SC-121613 behavior while incorporating upstream OAuth2 destination wording. Remove the Python 3.12 tokenizer-only catalog entry to match CI's Python 3.11 extraction.

@bito-code-review bito-code-review Bot 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.

Code Review Agent Run #ed9d1e

Actionable Suggestions - 2
  • superset/tasks/deletion_retention.py - 1
  • superset/config.py - 1
Additional Suggestions - 1
  • superset-frontend/src/utils/softDeleteCopy.ts - 1
    • Magic sentinel -1 · Line 50-50
      The `-1` sentinel (immediate eligibility, matching backend `resolve_retention_window`) is hardcoded in two comparisons (lines 50 and 72). A bare literal encoding a business rule invites divergence if the backend convention changes. Extract a named constant like `IMMEDIATE_ELIGIBILITY` and reference it in both spots.
Review Details
  • Files reviewed - 12 · Commit Range: 0afd908..a7fc18c
    • docs/docs/using-superset/version-history.mdx
    • superset-frontend/src/utils/softDeleteCopy.test.ts
    • superset-frontend/src/utils/softDeleteCopy.ts
    • superset/cli/deletion_retention.py
    • superset/commands/deletion_retention/window.py
    • superset/config.py
    • superset/tasks/deletion_retention.py
    • superset/tasks/version_history_retention.py
    • tests/unit_tests/cli/deletion_retention_test.py
    • tests/unit_tests/config_test.py
    • tests/unit_tests/tasks/test_deletion_retention.py
    • tests/unit_tests/tasks/test_version_history_retention.py
  • Files skipped - 1
    • UPDATING.md - Reason: Filter setting
  • Tools
    • MyPy (Static Code Analysis) - ✔︎ Successful
    • Astral Ruff (Static Code Analysis) - ✔︎ Successful
    • Whispers (Secret Scanner) - ✔︎ Successful
    • Detect-secrets (Secret Scanner) - ✔︎ Successful
    • Eslint (Linter) - ✔︎ Successful

Bito Usage Guide

Commands

Type the following command in the pull request comment and save the comment.

  • /review - Manually triggers an incremental AI Review.

  • /review full - Manually triggers a full AI Review.

  • /pause - Pauses automatic reviews on this pull request.

  • /resume - Resumes automatic reviews.

  • /resolve - Marks all Bito-posted review comments as resolved.

  • /abort - Cancels all in-progress reviews.

Refer to the documentation for additional commands.

Configuration

This repository uses Superset You can customize the agent settings here or contact your Bito workspace admin at [email protected].

Documentation & Help

AI Code Review powered by Bito Logo

Comment thread superset/tasks/deletion_retention.py Resolved
Comment thread superset/config.py Resolved
Continuum observes SQLAlchemy broker sessions before Celery has a Flask context. Return a denied capture decision for those sessions so queue declaration can commit without an untracked version write or worker startup crash.

Clarify the chart/dashboard version-history UI scope in the user docs and generated feature-flag catalog.
@rusackas

Copy link
Copy Markdown
Member

Heya @mikebridge, the shape here seems reasonable, the predicate plus the unit-of-work gate in particular.

One thing I'd want sorted before this merges, though: the retention parsing. 0 disables, -1 means purge on the next run, and any other negative is invalid but goes two different ways depending on which parser sees it (history skips, soft-delete falls back to 30). A -1 sitting one keystroke from "disabled" is a scary sentinel for something that purges data, and the UPDATING entry spelling out the inconsistency reads like a thing to fix rather than document. Could we at least align the two parsers, and maybe reconsider whether core needs the immediate mode at all?

Also, a handful of bito threads are still open (the capture_enabled session fallback one looks valid) plus your own two notes on the dataset wording. Mind assessing/resolving those?

@mikebridge

Copy link
Copy Markdown
Member Author

@rusackas sorry, yes, this is madly being worked on last-minute---the "-1" is my late addition so that we can test this in staging without having to wait for some number of days. QA has said that it might have been better to test this by altering dates in the DB to be outside the window....

Heya @mikebridge, the shape here seems reasonable, the predicate plus the unit-of-work gate in particular.

One thing I'd want sorted before this merges, though: the retention parsing. 0 disables, -1 means purge on the next run, and any other negative is invalid but goes two different ways depending on which parser sees it (history skips, soft-delete falls back to 30). A -1 sitting one keystroke from "disabled" is a scary sentinel for something that purges data, and the UPDATING entry spelling out the inconsistency reads like a thing to fix rather than document. Could we at least align the two parsers, and maybe reconsider whether core needs the immediate mode at all?

Also, a handful of bito threads are still open (the capture_enabled session fallback one looks valid) plus your own two notes on the dataset wording. Mind assessing/resolving those?

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

Richard's agent here: gating and restore-in-transaction look solid; all 12 history routes are covered and permission-before-flag ordering is right. A few things before merge:

1. Old setting name already ships on 7.0
SUPERSET_VERSION_HISTORY_RETENTION_DAYS is already on the 7.0 branch, and its UPDATING note says 0 or negative disables pruning. Unless this rename is backported before 7.0 is cut, a 7.0 operator's setting is silently reset to 30 on upgrade, and the next prune deletes older history.
→ Could we backport it, or read the old name with a deprecation warning?

2. -1 changes from "disable" to "purge now"
The 7.0 docs say negative values disable pruning; here -1 purges immediately.
→ Could UPDATING say this explicitly and point people to 0? A startup warning while -1 is active would also help.

3. The per-transaction capture decision is left to the host
capture_enabled calls the host check on every call and leaves per-transaction caching to the host. Helper sessions on the same connection (e.g. tagging's Session(bind=connection)) miss a host cache kept in session.info. A False there makes CaptureUnitOfWork.process_after_flush discard the shared unit of work's operations.
→ Caching the decision once per unit of work in core would make "no untracked restore" something core guarantees rather than assumes. Fine as a follow-up if you prefer.

Minor

  • The parent-snapshot rebuild runs on every captured save, and it now fails the save on error, which is worth a line in UPDATING.

@bito-code-review

bito-code-review Bot commented Sep 24, 2026 •

Copy link
Copy Markdown
Contributor

Code Review Agent Run #7a0c64

Actionable Suggestions - 0
Additional Suggestions - 2
  • superset/commands/deletion_retention/window.py - 2
    • stale docstring · Line 60-62
      The `_config_retention_days` docstring still says "Return a validated config fallback", but the changed lines now return `_defer_invalid_window(...)` (0) on malformed/oversized config instead of falling back to `_DEFAULT_RETENTION_DAYS`. The docstring no longer matches the function's behavior and could mislead future maintainers about the fail-safe semantics.
    • hardcoded metric prefix · Line 39-39
      The metric key `"deletion_retention.invalid_window"` hardcodes the `deletion_retention` prefix that `superset/tasks/deletion_retention.py` already centralizes as `_METRIC_PREFIX`. If that prefix is ever renamed, this counter silently diverges from the rest of the deletion-retention metrics. Consider a named constant so the two stay in sync.
Review Details
  • Files reviewed - 5 · Commit Range: edfe588..d658013
    • docs/docs/using-superset/version-history.mdx
    • superset/commands/deletion_retention/window.py
    • superset/commands/version_restore.py
    • tests/unit_tests/tasks/test_deletion_retention.py
    • tests/unit_tests/versioning/test_runtime_capture.py
  • Files skipped - 1
    • UPDATING.md - Reason: Filter setting
  • Tools
    • MyPy (Static Code Analysis) - ✔︎ Successful
    • Astral Ruff (Static Code Analysis) - ✔︎ Successful
    • Whispers (Secret Scanner) - ✔︎ Successful
    • Detect-secrets (Secret Scanner) - ✔︎ Successful

Bito Usage Guide

Commands

Type the following command in the pull request comment and save the comment.

  • /review - Manually triggers an incremental AI Review.

  • /review full - Manually triggers a full AI Review.

  • /pause - Pauses automatic reviews on this pull request.

  • /resume - Resumes automatic reviews.

  • /resolve - Marks all Bito-posted review comments as resolved.

  • /abort - Cancels all in-progress reviews.

Refer to the documentation for additional commands.

Configuration

This repository uses Superset You can customize the agent settings here or contact your Bito workspace admin at [email protected].

Documentation & Help

AI Code Review powered by Bito Logo

@mikebridge

mikebridge commented Sep 24, 2026 •

Copy link
Copy Markdown
Member Author

@richardfogaca Thanks for the careful review. I addressed the four points in 07a27cb:

  • The 7.0 SUPERSET_VERSION_HISTORY_RETENTION_DAYS key remains a deprecated fallback for environment and Python config. Existing 0/negative disables and longer windows are preserved. A star-imported new default cannot silently shorten an old window; an ambiguous pair keeps the safer disable or longer window.
  • The upgrade notes warn that copying an old -1 to the new key would change disable into immediate eligibility. Explicit new -1 still works and logs a startup warning; use new 0 to keep pruning disabled. Invalid or oversized values defer cleanup.
  • Continuum's connection-scoped unit of work now holds one capture decision through commit/rollback, so a helper session cannot clear captured operations or re-enable a denied unit. Tests cover both directions. The host still must keep its predicate stable for the whole transaction, as documented.
  • UPDATING.md now says a parent/child snapshot rebuild failure aborts the save and requires rollback.

The exact tree passed 578 affected unit tests, five retention integration tests on migrated SQLite, and all applicable hooks on the eight follow-up files. The full PR hook run in this isolated checkout hit only unbuilt frontend declaration artifacts (TS6305); fresh exact-head CI is queued. Shell #5218 remains dependent on this core change reaching a private production commit and a verified shell pin; this PR head is not that production SHA. Would you take another look when CI settles?

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

Richard's agent here: re-reviewed 07a27cb12 and all four points are fixed. The deprecated fallback keeps 7.0 behavior, the -1 upgrade warning and startup log are clear, and caching the capture decision per unit of work closes the helper-session gap (the tests cover both directions). Totally optional: the old/new retention merge now lives in both config.py and prune_old_versions. Pulling it into one shared helper would keep the two from drifting apart. Happy to keep as-is. LGTM.

@bito-code-review bito-code-review Bot 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.

Code Review Agent Run #4a899c

Actionable Suggestions - 2
Additional Suggestions - 7
  • tests/unit_tests/versioning/test_listener.py - 3
    • Duplicated Test Setup Block · Line 39-49
      `test_shared_connection_capture_decision_survives_helper_session` and `test_shared_connection_denial_cannot_be_reenabled_by_helper_session` duplicate the full setup — the `MagicMock(spec=Session)` pair, `CaptureUnitOfWork(versioning_manager)`, the pending statement, and the identical three-patch context — differing only in `capture_enabled`'s return value. A shared helper parameterized on the gate result prevents drift when patch targets change.
    • Inline Import Violates Rule · Line 37-37
      This function-scope `from sqlalchemy_continuum import versioning_manager` conflicts with BITO rule 12745 (module-level imports unless a documented circular dependency). None exists here: `sqlalchemy_continuum.unit_of_work` is already imported at module level (line 28). Move it to the top import block; the new test at line 62 repeats this.
    • Inline Import Violates Rule · Line 62-62
      Same inline `from sqlalchemy_continuum import versioning_manager` as line 37: BITO rule 12745 requires module-level imports absent a documented circular dependency, and line 28 already imports `sqlalchemy_continuum.unit_of_work` at module scope. Hoist it into the top import block with the other sqlalchemy_continuum imports.
  • tests/unit_tests/tasks/test_version_history_retention.py - 2
    • Duplicated test scaffold · Line 88-148
      The three new tests repeat the same scaffold — build `Flask` app, set config, `patch.object(version_history_retention, "_prune_old_versions_impl")`, assert on `prune` — duplicating `test_task_reads_canonical_application_retention` (line 66). With five near-identical blocks, a config-key or lookup-contract change must now be edited in five places. Extract a shared helper taking the config mapping and expected argument.
    • Env-dependent test config · Line 109-127
      This test reads ambient process state: with both keys set, `prune_old_versions` evaluates the legacy-merge branch (`version_history_retention.py:562-566`), gated on `"VERSION_HISTORY_RETENTION_DAYS" not in os.environ` and `retention_days == _version_history_retention_seed` (import-time, `config.py:1881`). If the env var is exported with any value other than 30, the merge is skipped, `prune` receives 30, and the 0/365 expectations fail. Patch `os.environ` and the seed for determinism.
  • superset/config.py - 1
    • Env var outranks config override · Line 3646-3649
      This guard lets the env var `VERSION_HISTORY_RETENTION_DAYS` (already applied at import, line 1829) outrank an explicit canonical `VERSION_HISTORY_RETENTION_DAYS` set in the config file, so the legacy-key merge at 3650+ runs and can only keep or raise the value (max/0 rule). That diverges from the module's config-file-override model and from `ENV_VAR_KEYS` (3666), which lists the only env vars meant to override config. Intent should be confirmed and documented.
  • tests/unit_tests/config_test.py - 1
    • Test isolation gap · Line 116-116
      Unlike the sibling tests at lines 77 and 156, this test never neutralizes a developer `superset_config` module. If one is importable in the test environment, config.py line 3646 re-normalizes the legacy override and `_parse_version_history_retention_days()` still returns the env value, so the test passes today but is not hermetic. Consider `monkeypatch.setitem(sys.modules, "superset_config", None)` for consistency.
Filtered by Review Rules

Bito filtered these suggestions based on rules created automatically for your feedback. Manage rules.

  • superset/tasks/version_history_retention.py - 2
  • superset/config.py - 1
Review Details
  • Files reviewed - 7 · Commit Range: d658013..07a27cb
    • docs/docs/using-superset/version-history.mdx
    • superset/config.py
    • superset/tasks/version_history_retention.py
    • superset/versioning/unit_of_work.py
    • tests/unit_tests/config_test.py
    • tests/unit_tests/tasks/test_version_history_retention.py
    • tests/unit_tests/versioning/test_listener.py
  • Files skipped - 1
    • UPDATING.md - Reason: Filter setting
  • Tools
    • MyPy (Static Code Analysis) - ✔︎ Successful
    • Astral Ruff (Static Code Analysis) - ✔︎ Successful
    • Whispers (Secret Scanner) - ✔︎ Successful
    • Detect-secrets (Secret Scanner) - ✔︎ Successful

Bito Usage Guide

Commands

Type the following command in the pull request comment and save the comment.

  • /review - Manually triggers an incremental AI Review.

  • /review full - Manually triggers a full AI Review.

  • /pause - Pauses automatic reviews on this pull request.

  • /resume - Resumes automatic reviews.

  • /resolve - Marks all Bito-posted review comments as resolved.

  • /abort - Cancels all in-progress reviews.

Refer to the documentation for additional commands.

Configuration

This repository uses Superset You can customize the agent settings here or contact your Bito workspace admin at [email protected].

Documentation & Help

AI Code Review powered by Bito Logo

Comment thread superset/config.py
Comment on lines +1872 to +1876
if retention_days == -1:
logger.warning(
"VERSION_HISTORY_RETENTION_DAYS=-1 makes history eligible for "
"immediate pruning on the next scheduled run; use 0 to disable"
)

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.

CWE-706: Wrong var name in warning

This warning hardcodes VERSION_HISTORY_RETENTION_DAYS, but _normalize_version_history_retention_days also runs for the legacy SUPERSET_VERSION_HISTORY_RETENTION_DAYS env var (lines 1832-1833) and for legacy config overrides (line 3650), where name is the legacy key. A legacy user setting -1 gets a warning naming a variable they never set. Use name like the other warnings do. (CWE-706)

Code Review Run #4a899c


Should Bito avoid suggestions like this for future reviews? (Manage Rules)

  • Yes, avoid them

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.

Updated in 903a799ae3a8: the warning now uses the setting name consistently, with regression coverage. The legacy -1 path already returns 0 before this warning; the regression confirms it still disables pruning and emits no immediate-pruning warning.

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 suggestion to use the name variable in the warning message is correct and has been addressed. The updated code now dynamically uses name (which correctly reflects whether the legacy or canonical setting is being processed) in all warning logs, ensuring that users receive accurate feedback regardless of which environment variable triggered the warning.

superset/config.py

try:
        if isinstance(value, bool) or not isinstance(value, (str, int)):
            raise ValueError("Retention must be integer days")
        retention_days: int = int(value)
    except ValueError:
        logger.warning("Invalid %s=%r; skipping pruning", name, value)
        return 0

Comment thread superset/config.py Outdated
)
if not _canonical_history_retention_override:
VERSION_HISTORY_RETENTION_DAYS = _legacy_history_retention_days
elif VERSION_HISTORY_RETENTION_DAYS == _version_history_retention_seed:

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.

Legacy deprecation warning skipped

When a config file sets both keys and the canonical value differs from _version_history_retention_seed, this elif skips normalization of _legacy_history_retention_value entirely — so the deprecation warning for SUPERSET_VERSION_HISTORY_RETENTION_DAYS (lines 1853-1858) never fires, unlike the legacy-only path (3653-3654) which always warns. The legacy key is silently ignored. Normalize/warn for the legacy key before the seed comparison.

Code Review Run #4a899c


Should Bito avoid suggestions like this for future reviews? (Manage Rules)

  • Yes, avoid them

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.

Addressed in 903a799ae3a8. The consolidated resolver already warned for a valid legacy config value before a differing canonical override won; a config-load regression now covers that case. Also fixed the remaining ignored-legacy paths: a canonical environment setting still allows the legacy deprecation warning, and ignored invalid legacy values no longer claim active pruning is skipped. Retention results and precedence are unchanged; 581 affected tests passed, and a differential probe matched the previous returned values in 608 cases.

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 suggestion provided by the reviewer is valid and addresses a potential issue where the legacy deprecation warning could be skipped. By normalizing and warning for the legacy key before the seed comparison, the code ensures that the deprecation warning is correctly triggered even when a canonical override is present. Applying this change improves the robustness of the configuration loading logic.

superset/config.py

_legacy_history_retention_days: int = _normalize_version_history_retention_days(
        _legacy_history_retention_value, legacy=True
    )
    if not _canonical_history_retention_override:
        VERSION_HISTORY_RETENTION_DAYS = _legacy_history_retention_days
    elif VERSION_HISTORY_RETENTION_DAYS == _version_history_retention_seed:

@github-actions github-actions Bot added the requires:rebase Requires rebasing on top of current master label Sep 25, 2026
@github-actions github-actions Bot removed the requires:rebase Requires rebasing on top of current master label Sep 25, 2026

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

Heya @mikebridge, thanks for chasing all this down. The retention parsing I flagged is fixed and tested now, test_star_imported_default_does_not_hide_legacy_retention covers the exact star-import ambiguity case, and the two parsers agree on invalid/oversized values deferring with 0. -1 immediate-purge is still in core though, just warned-on rather than removed, so that design call is still open if you want to revisit it.

@richardfogaca's three points in 07a27cb all check out too, traced each against the actual code rather than just the commit message.

One thing before this merges, though. _capture_enabled() in api_helpers.py calls capture_enabled() with no session, so it falls back to db.session() on every GET/ETag read (current_entity_version_info, used from the chart/dashboard/dataset GET and pre-write-read paths), not just at save time. VERSIONING_CAPTURE_PREDICATE is documented as a stable-per-transaction save-time decision, so a host predicate that's session/transaction-aware can now see a different session on a read than it'll see at the actual write, and the ETag computed here could disagree with what capture decides at commit. Might be worth threading the request's session through the same way version_restore.py does now.

Also prune_old_versions()'s legacy-ambiguity branch does a bare int(legacy_configured) with no try/except. A non-numeric legacy value raises past the documented "invalid values defer with 0" and turns into a hard task failure instead.

Non-blocking, but that same function re-derives a good chunk of the legacy/canonical disambiguation config.py already resolves once into app.config, a future fix to that policy won't reach the task unless someone remembers to mirror it. And reconcile_parent_snapshots runs on every captured save even when nothing changed (bito's right about that one), and CaptureUnitOfWork._capture_allowed is None doubles as both "undecided" and a legit None from a predicate breaking its own contract, minor unless a host predicate misbehaves.

Two other bito threads on config.py are still open (the -1 warning naming the wrong var, a supposedly-skipped deprecation warning) but I traced both by hand and neither reproduces, happy to explain if useful but wouldn't hold on those.

CI's green, test coverage throughout is genuinely thorough. Once the session-on-read thing and the retention task's exception path are sorted, I think this is good to go.

…nvalid retention with 0

Addresses the blocking review on apache#44514:

- `api_helpers._capture_enabled` passes the request's Session to the shared
  capture gate explicitly, as the restore command does, instead of relying on
  the gate's ambient fallback. The scoped_session proxy is resolved to its
  current Session; a plain Session bound in its place is used as-is.
- `prune_old_versions` no longer re-derives the legacy/canonical retention
  policy with bare `int()` casts. A single `_resolve_version_history_retention_days`
  in config.py serves both config load and the task, so an invalid canonical
  or legacy value defers pruning with 0 and a warning instead of failing the
  run. `-1` immediate eligibility is unchanged.
- `capture_enabled` coerces the host predicate's result to bool, so a `None`
  from a predicate breaking its contract denies capture instead of leaving
  `CaptureUnitOfWork` undecided.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Claude-Session: https://claude.ai/code/session_01WQEoQmmvQvPAc9k8dsGtL4
@mikebridge

Copy link
Copy Markdown
Member Author

Thanks, Evan. I pushed f3f75b3f to address both remaining findings. _capture_enabled() now passes the request Session explicitly, matching the restore path. The previous fallback resolved to that same request Session, so this makes the dependency explicit without changing the session lifecycle. Config loading and prune_old_versions() now use one retention resolver; malformed canonical or legacy values warn and defer pruning with 0 instead of failing the task. Tests cover the session bindings, invalid values, and the legacy ambiguity case.

I also made a predicate result of None a memoized false decision. We are intentionally retaining documented -1 immediate eligibility; unchanged-save reconciliation remains a follow-up. The local affected tests and required hooks passed, and fresh CI is running on this head. Could you re-review when convenient?

@mikebridge

Copy link
Copy Markdown
Member Author

There is one pending issue with sqlite with ID collisions that is being worked on.

A child id deleted from one dataset and reused under another while capture
was denied made the resumed save abort: `_reconcile_children` discovered the
prior row per parent and inserted under the global shadow key
`(id, transaction_id)` twice. Reconciliation now runs once per child model
over the whole captured parent set, so a reassigned id gets exactly one row
at the resumed transaction: an INSERT under its new parent, which closes the
old parent's open row. The gap-born predecessor probe is restricted to
same-parent rows so a natively edited reborn child is recorded the same way.

The restore guard accepts that surviving foreign closer as proof of the old
parent's absence (the shadow key is unique per transaction, so no
same-parent successor could have been pruned), read under the same lock as
the same-parent rows; its known-limitation list gains the matching shape.

Native coverage: both creation orders x columns/metrics x native edit of the
reborn child, asserting one shadow row per transaction for the recycled id
and restoring both parents' resumed snapshots; a guard unit table for foreign
closers. Six mock bindings in test_listener.py are declared.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Claude-Session: https://claude.ai/code/session_01WQEoQmmvQvPAc9k8dsGtL4
@bito-code-review

bito-code-review Bot commented Sep 25, 2026 •

Copy link
Copy Markdown
Contributor

Code Review Agent Run #4c5740

Actionable Suggestions - 0
Additional Suggestions - 7
  • tests/unit_tests/versioning/test_capture_gap_restore.py - 2
    • Untyped lambda predicate · Line 504-504
      BITO adaptive rule [13350] asks for typed helpers instead of untyped lambdas. `lambda s: policy["enabled"]` is passed as `VERSIONING_CAPTURE_PREDICATE`, typed `Callable[[Session], bool]` in `superset/config.py`; a small typed closure keeps that contract explicit. Five sibling tests in this file share the pattern, so a shared helper could follow; this instance is the new code.
    • Helpers missing docstrings · Line 509-526
      BITO adaptive rule [12147] requires docstrings on newly added Python functions, explicitly including helper functions in test files. The nested helpers `make_child`, `names`, `attach`, and `detach_all` carry type annotations but no docstrings; one line each (e.g. `attach` appends to the parametrized child collection) keeps the parametrized setup self-explaining.
  • tests/unit_tests/tasks/test_version_history_retention.py - 1
    • Ambient env leaks into test · Line 208-228
      `test_task_defers_invalid_legacy_retention_with_zero` expects the legacy branch to run, but `_resolve_version_history_retention_days` returns `canonical_days` early when `VERSION_HISTORY_RETENTION_DAYS` is present in `os.environ` (superset/config.py:1916). An exported var in the pytest environment flips the expectation from 0 to 30 and skips the warning. `monkeypatch.delenv(..., raising=False)`, as line 175 does, isolates the test.
  • superset/versioning/api_helpers.py - 1
    • Docstring misstates session scoping · Line 103-104
      The docstring says `db.session` resolves to one `Session` per app context, but `superset/extensions/__init__.py` restores the 2.x scopefunc (greenlet/thread identity), so one session is shared across nested app contexts on the same thread. The same-object guarantee still holds; only the stated mechanism is wrong. Reword to per-greenlet/thread.
  • tests/unit_tests/versioning/test_runtime_capture.py - 1
    • Test scope exceeds name · Line 375-393
      `test_none_predicate_result_denies_capture_and_is_memoized` builds a real `CaptureUnitOfWork(versioning_manager)` and asserts `unit._capture_enabled` memoizes, but its name and docstring only promise None-denial. The memoization claim silently depends on Continuum's `UnitOfWork.__init__` behavior; if that constructor changes, this test fails for a reason its name doesn't describe. Either split the memoization assertion into its own test or construct the unit with a mock spec so the dependency is explicit.
  • superset/versioning/snapshot.py - 2
    • Reassigned flag overbroad · Line 128-132
      `reassigned` omits the `active` check its comment and the docstring imply: a prior DELETE row under another parent also sets it. Harmless today (both branches yield INSERT), but the name overstates what is computed and invites misuse if new branches consult it. Consider `active and prior["table_id"] != row["table_id"]` or a more precise name.
    • Duplicated null-guard conjuncts · Line 128-132
      `reassigned` recomputes `row is not None and prior is not None`, which `active` (line 125) already guarantees at both use sites (lines 171, 181). The duplicated guards obscure that `active` is the real precondition; folding them away keeps the skip and kind conditions minimal and consistent.
Review Details
  • Files reviewed - 12 · Commit Range: 07a27cb..5ab4170
    • superset/config.py
    • superset/tasks/version_history_retention.py
    • superset/versioning/api_helpers.py
    • superset/versioning/utils.py
    • tests/unit_tests/config_test.py
    • tests/unit_tests/tasks/test_version_history_retention.py
    • tests/unit_tests/versioning/test_runtime_capture.py
    • superset/versioning/restore.py
    • superset/versioning/snapshot.py
    • tests/unit_tests/versioning/test_capture_gap_restore.py
    • tests/unit_tests/versioning/test_listener.py
    • tests/unit_tests/versioning/test_restore.py
  • Files skipped - 1
    • UPDATING.md - Reason: Filter setting
  • Tools
    • MyPy (Static Code Analysis) - ✔︎ Successful
    • Astral Ruff (Static Code Analysis) - ✔︎ Successful
    • Whispers (Secret Scanner) - ✔︎ Successful
    • Detect-secrets (Secret Scanner) - ✔︎ Successful

Bito Usage Guide

Commands

Type the following command in the pull request comment and save the comment.

  • /review - Manually triggers an incremental AI Review.

  • /review full - Manually triggers a full AI Review.

  • /pause - Pauses automatic reviews on this pull request.

  • /resume - Resumes automatic reviews.

  • /resolve - Marks all Bito-posted review comments as resolved.

  • /abort - Cancels all in-progress reviews.

Refer to the documentation for additional commands.

Configuration

This repository uses Superset You can customize the agent settings here or contact your Bito workspace admin at [email protected].

Documentation & Help

AI Code Review powered by Bito Logo

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

Heya @mikebridge, both things I flagged are fixed and traced against the code, not just the commit message: _capture_enabled() now threads the actual request session through instead of falling back to a fresh db.session() on reads, and the retention parsing consolidation means an invalid legacy value defers with 0 instead of crashing the task. Nice bonus on the DRY cleanup too.

I had the newest commit (5ab4170e1, recycled child ids across parents) independently verified given it touches the fail-closed restore guarantee directly, the foreign-closer matching is correct and atomic, and the tests include the adversarial wrong-transaction/wrong-child-id negatives that would catch a weakened guard. Holds up.

Two small bito threads are still open, real but minor, both are log-message completeness issues (a warning naming the wrong env var when triggered via the legacy key, and a precedence branch that skips the legacy-deprecation warning when canonical wins). Neither affects the actual retention-day resolution. Not holding up the merge for those.

CI's green. LGTM!

mikebridge and others added 3 commits September 27, 2026 22:56
…to another dataset

Continuum's reverter resolves a column or metric by integer primary key
alone. When a child id was freed by a hard delete and reused under another
dataset while capture was denied, restoring the old dataset to a
pre-recycle version rewrote the other dataset's live child in place.

`_verify_child_identities` now runs before the revert: for every child row
the reverter would apply (the latest row at or before the target per child
id, matching Continuum's one_to_many_criteria), the live row is read FOR
UPDATE, and the restore is refused with a user-facing
`RecycledChildIdentityError` (422, like the pruned-history refusal) when
that row belongs to a different dataset. Both datasets, their children and
the history stay unchanged. An id no longer live anywhere is still
recreated, and a same-parent row is still rewritten to the snapshot's
values, which keeps pre-import versions restorable after import's in-place
uuid rewrite. The SQLite write reservation is a helper each guard calls for
itself.

Native tests through the restore command: cross-dataset recycle refused
(column/metric x both-captured/old-only) with no writes; retired id
recreated with its historical id and uuid; same-parent re-birth rewritten;
endpoint 422 mapping.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Claude-Session: https://claude.ai/code/session_01WQEoQmmvQvPAc9k8dsGtL4
@mikebridge

Copy link
Copy Markdown
Member Author

Pushed 903a799ae3a8 with the remaining restore-safety follow-up and Bito warning fixes. Dataset restore now refuses safely when a historical column or metric ID is currently owned by another dataset, preserving both datasets and their history. Missing children and earlier versions of children still owned by the same dataset remain restorable.

Independent Astra review of the complete PR and final deltas passed; 581 affected tests and all six changed-file pre-commit checks passed locally. The warning fixes preserve retention values and precedence. GitHub still reports APPROVED after the push; fresh CI is queued/running.

@bito-code-review

bito-code-review Bot commented Sep 28, 2026 •

Copy link
Copy Markdown
Contributor

Code Review Agent Run #df348b

Actionable Suggestions - 0
Additional Suggestions - 1
  • superset/config.py - 1
    • Misleading deprecation warning · Line 1849-1849
      `_warn_legacy_version_history_retention_days()` is also called on the ignored-legacy paths (`_parse` line 1838, `_resolve` line 1930) where the legacy value has no effect, yet the message states 'Legacy nonpositive values disable pruning.' That can mislead operators into thinking their legacy setting still governs pruning when the canonical/env value actually wins. Reword to qualify the claim ('When used, ...').
Review Details
  • Files reviewed - 6 · Commit Range: 5ab4170..903a799
    • superset/versioning/api_helpers.py
    • superset/versioning/restore.py
    • tests/unit_tests/versioning/test_capture_gap_restore.py
    • tests/unit_tests/versioning/test_restore.py
    • superset/config.py
    • tests/unit_tests/config_test.py
  • Files skipped - 0
  • Tools
    • MyPy (Static Code Analysis) - ✔︎ Successful
    • Astral Ruff (Static Code Analysis) - ✔︎ Successful
    • Whispers (Secret Scanner) - ✔︎ Successful
    • Detect-secrets (Secret Scanner) - ✔︎ Successful

Bito Usage Guide

Commands

Type the following command in the pull request comment and save the comment.

  • /review - Manually triggers an incremental AI Review.

  • /review full - Manually triggers a full AI Review.

  • /pause - Pauses automatic reviews on this pull request.

  • /resume - Resumes automatic reviews.

  • /resolve - Marks all Bito-posted review comments as resolved.

  • /abort - Cancels all in-progress reviews.

Refer to the documentation for additional commands.

Configuration

This repository uses Superset You can customize the agent settings here or contact your Bito workspace admin at [email protected].

Documentation & Help

AI Code Review powered by Bito Logo

@aminghadersohi
aminghadersohi merged commit 7729572 into apache:master Sep 28, 2026
93 of 94 checks passed
hainenber pushed a commit that referenced this pull request Sep 29, 2026
mikebridge added a commit to mikebridge/superset that referenced this pull request Sep 29, 2026
Resolve the conflict in docs/docs/using-superset/version-history.mdx.
Master's retention section, merged with apache#44514, is kept word for word.
This branch's operator guidance is kept around it: the task name and
schedule, what pruning preserves, and how to keep history while the
feature is off.

Three statements from this branch are dropped because the merged core no
longer behaves that way: the old setting name, the 30-day fallback for an
invalid value, and non-positive values disabling pruning. The advice to
remove the beat schedule entry is dropped because that logs a warning at
every startup.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

api Related to the REST API doc Namespace | Anything related to documentation i18n Namespace | Anything related to localization size/XXL

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants