diff --git a/.github/workflows/testcontainers.yml b/.github/workflows/testcontainers.yml
index 9a34aaff2d96..96e10777ed70 100644
--- a/.github/workflows/testcontainers.yml
+++ b/.github/workflows/testcontainers.yml
@@ -27,6 +27,7 @@ on:
paths:
- ".github/workflows/testcontainers.yml"
- "tests/testcontainers/**"
+ - "!tests/testcontainers/versioning/**"
- "superset/db_engine_specs/**"
- "pyproject.toml"
- "requirements/development.in"
diff --git a/.github/workflows/versioning-testcontainers.yml b/.github/workflows/versioning-testcontainers.yml
new file mode 100644
index 000000000000..4752c39afa22
--- /dev/null
+++ b/.github/workflows/versioning-testcontainers.yml
@@ -0,0 +1,92 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+name: Version history databases
+
+permissions:
+ contents: read
+
+on:
+ schedule:
+ - cron: "0 5 * * *"
+ workflow_dispatch: {}
+ pull_request:
+ paths:
+ - ".github/workflows/versioning-testcontainers.yml"
+ - ".github/actions/setup-backend/**"
+ - "tests/testcontainers/versioning/**"
+ - "tests/testcontainers/db_engine_specs/_driver.py"
+ - "tests/conftest.py"
+ - "tests/integration_tests/test_app.py"
+ - "tests/integration_tests/superset_test_config.py"
+ - "pytest.ini"
+ - "superset/versioning/**"
+ - "superset/commands/deletion_retention/purge_cascade.py"
+ - "superset/tasks/version_history_retention.py"
+ - "superset/migrations/versions/2026-11-23_00-00_a7d29bc4e681_add_chart_archive_scope.py"
+ - "superset/migrations/shared/utils.py"
+ - "superset/initialization/__init__.py"
+ - "superset/app.py"
+ - "superset/config.py"
+ - "superset/models/slice.py"
+ - "superset/models/dashboard.py"
+ - "superset/models/helpers.py"
+ - "pyproject.toml"
+ - "requirements/base.in"
+ - "requirements/base.txt"
+ - "requirements/development.in"
+ - "requirements/development.txt"
+
+concurrency:
+ group: ${{ github.workflow }}-${{ github.ref }}
+ cancel-in-progress: true
+
+jobs:
+ archive-history:
+ if: github.event_name != 'schedule' || github.repository == 'apache/superset'
+ runs-on: ubuntu-26.04
+ timeout-minutes: 10
+ strategy:
+ fail-fast: false
+ matrix:
+ dialect: [POSTGRES, MYSQL]
+ env:
+ PYTHONPATH: ${{ github.workspace }}
+ SUPERSET_TESTENV: true
+ SUPERSET_SECRET_KEY: not-a-secret
+ SUPERSET_TESTCONTAINERS_STRICT: true
+ SUPERSET_VERSIONING_TEST_DIALECT: ${{ matrix.dialect }}
+ steps:
+ - name: Checkout
+ uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
+ with:
+ persist-credentials: false
+ - name: Setup Python
+ uses: $/.github/actions/setup-backend/
+ with:
+ python-version: current
+ - name: Run archive transaction and migration tests
+ run: |
+ pytest --durations-min=2 -v -m testcontainers \
+ tests/testcontainers/versioning/test_chart_archive.py \
+ --junit-xml=test-results/junit-archive-${{ matrix.dialect }}.xml
+ - name: Upload JUnit test results
+ if: always()
+ uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
+ with:
+ name: junit-results-archive-${{ matrix.dialect }}
+ path: test-results/
+ retention-days: 7
diff --git a/UPDATING.md b/UPDATING.md
index a03b3ca705fb..51724200bf46 100644
--- a/UPDATING.md
+++ b/UPDATING.md
@@ -24,6 +24,23 @@ assists people when migrating to a new version.
## Next
+- Dashboard history records related chart archives using the new
+ `version_chart_archive_scope` table. Run `superset db upgrade` before deploying
+ new archive writes with versioning capture enabled. During a rollout, activity
+ reads tolerate a missing scope table and continue returning content history;
+ archive capture skipped before the migration cannot be reconstructed or
+ backfilled. Archive activity adds no content version and does not change
+ recovery or content-restore behavior. Downgrade removes archive scopes and
+ archive records but leaves content history intact; empty activity transactions
+ may remain until normal history retention removes them.
+
+- Version-history commit-time finalization rejects the whole save when a database
+ error occurs outside a recoverable savepoint, including final field or child
+ diff generation and version-transaction lookup. This applies to ordinary
+ content saves as well as chart archives. A lost transaction or savepoint also
+ rejects the save. Optional capture failures isolated by a successful savepoint
+ rollback may still omit history without rejecting the save.
+
- `list` and `pages` are now reserved extension publisher names. An
extension already published under either will fail manifest validation
and the `superset-extensions` CLI will refuse to build it; the host owns
diff --git a/docs/docs/using-superset/version-history.mdx b/docs/docs/using-superset/version-history.mdx
index a1bc9752faa4..a36b9248de15 100644
--- a/docs/docs/using-superset/version-history.mdx
+++ b/docs/docs/using-superset/version-history.mdx
@@ -84,6 +84,13 @@ stops filling — an empty or stale history misrepresents the entity as
unchanged. History only accrues while capture is on; edits made while it was
off are not reconstructed.
+At commit time, an optional history-capture failure isolated by a successful
+savepoint rollback may omit history while allowing the save to succeed. A database
+error outside that isolation, or a lost transaction or savepoint, rejects the
+whole save. This applies to ordinary content saves as well as archive operations:
+Superset does not report success when it cannot establish that the user's changes
+survived the capture failure.
+
## Retention
The `version_history.prune_old_versions` background task prunes expired
@@ -375,6 +382,49 @@ you are looking at.
Changes made outside a save, such as ownership or permission edits, are not part
of version history.
+### Chart archive activity on dashboards
+
+With `SOFT_DELETE` and versioning capture enabled, archiving a chart records
+an archive event for each dashboard containing it at capture time.
+`VERSION_HISTORY` controls whether the UI and supporting APIs expose that activity;
+turning it off does not stop archive capture. With the flag enabled, dashboards
+show **Chart archived: <chart name>** in related activity. Bulk archives show
+one entry per chart. The entry uses the chart's name and the archive capture time, and remains
+an archive entry after the chart is recovered. Chart history itself contains only
+content activity.
+
+Membership is captured after the archive transaction's changes have been flushed.
+A chart attached while capture was disabled can therefore appear in its dashboard's
+archive activity; one detached during that interval does not. Later membership
+changes do not move old archive entries between dashboards. Archived dashboards
+retain their captured membership and can show the activity after recovery.
+A dashboard with no saved content history can show archive activity without an
+**Original version** entry.
+
+Archive entries have no content preview, restore-version, or open-as-new action.
+Archived charts do not link to Explore; recovering a chart enables the link again.
+Recover charts through **Recently Archived**: restoring a content version does not
+unarchive them. Explicit recovery events are not recorded. The chart's last content
+version remains current after recovery without another save.
+
+History permissions still apply: dashboard history requires edit access, related
+names require access to the related resource, and actor and raw change details
+require edit access to that resource. For archived related resources, actor and
+raw detail remain hidden from non-Admin readers, including the archiver. The panel
+labels a hidden or unavailable actor **System**; this label does not establish that
+the action was automated.
+
+Permanent purge removes a chart's archive entries from all dashboards, even when history retention is disabled or longer
+than archive retention. Normal history retention can also remove expired archive
+activity; archive membership does not keep expired transactions alive.
+
+Deploy the database migration before enabling archive capture. Archives made with
+capture disabled, denied by host policy, or skipped because capture storage was
+unavailable are not backfilled. If capture was disabled during archive and a later
+write creates the first content baseline, its attribution comes from the archived
+row's stored audit fields and can credit the archiver; it does not reconstruct an
+archive event.
+
### Resuming capture after a disabled interval
When a dataset or dashboard snapshot is saved with capture enabled, its child
diff --git a/docs/static/resources/openapi.json b/docs/static/resources/openapi.json
index 752bdc022ffe..9d01464d4ee4 100644
--- a/docs/static/resources/openapi.json
+++ b/docs/static/resources/openapi.json
@@ -291,7 +291,7 @@
"type": "string"
},
"entity_name": {
- "description": "Name of the source entity *at the time of the change* \u2014 denormalized from the validity-strategy shadow row. Survives entity rename / delete.",
+ "description": "Name of the source entity *at the time of the change* \u2014 denormalized from the validity-strategy shadow row, or from the capture-time payload for ``__archive__`` records. Preserved across renames; redacted for deleted related entities.",
"type": "string"
},
"entity_uuid": {
@@ -322,7 +322,7 @@
"type": "string"
},
"kind": {
- "description": "Content category \u2014 what kind of thing changed. ``field`` is the fallback for scalar changes without a more specific category. Per-record.",
+ "description": "Content category \u2014 what kind of thing changed. ``field`` is the fallback for scalar changes without a more specific category. Per-record. ``__archive__`` announces a chart archive in related dashboard activity only.",
"enum": [
"filter",
"metric",
@@ -339,7 +339,8 @@
"color_palette",
"field",
"__meta__",
- "__creation__"
+ "__creation__",
+ "__archive__"
],
"type": "string"
},
@@ -372,11 +373,11 @@
"type": "string"
},
"summary": {
- "description": "Synthesized headline for ``source: \"related\"`` records \u2014 e.g., ``\"Dataset updated: Sales Transactions\"``. Empty string for ``source: \"self\"`` records, except ``__meta__`` self records (e.g. restore announcements), which carry their own headline.",
+ "description": "Synthesized headline for ``source: \"related\"`` records \u2014 e.g., ``\"Dataset updated: Sales Transactions\"`` or ``\"Chart archived: Sales\"``. Empty string for ``source: \"self\"`` records, except ``__meta__`` self records (e.g. restore announcements), which carry their own headline.",
"type": "string"
},
"to_value": {
- "description": "New value; ``null`` = removed.",
+ "description": "New value; ``null`` = removed. For ``__archive__``, an object with the archived chart's ``entity_uuid`` and capture-time ``entity_name``; null when related detail is redacted.",
"nullable": true
},
"transaction_id": {
diff --git a/superset-frontend/src/features/versionHistory/RelatedUpdateRow.test.tsx b/superset-frontend/src/features/versionHistory/RelatedUpdateRow.test.tsx
index ee99f0952d78..085fa5c4d843 100644
--- a/superset-frontend/src/features/versionHistory/RelatedUpdateRow.test.tsx
+++ b/superset-frontend/src/features/versionHistory/RelatedUpdateRow.test.tsx
@@ -175,3 +175,50 @@ test('a row whose records span several kinds of change gets a neutral headline',
).toBeInTheDocument();
expect(screen.queryByText(/metric changed/)).not.toBeInTheDocument();
});
+
+test.each([
+ {
+ entity_deleted: false,
+ entity_deletion_state: 'soft_deleted',
+ entity_uuid: 'abc',
+ },
+ { entity_deleted: true, entity_deletion_state: null, entity_uuid: 'abc' },
+ { entity_deleted: false, entity_deletion_state: null, entity_uuid: null },
+])('unavailable related charts have no navigation links: %s', unavailable => {
+ render(
+ ,
+ );
+ expect(screen.queryByRole('button')).not.toBeInTheDocument();
+});
+
+test('a recovered chart links from its archive event and keeps shared author formatting', async () => {
+ const onOpen = jest.fn();
+ const archive: ActivityRecord = {
+ ...baseRecord,
+ entity_kind: 'chart',
+ kind: '__archive__',
+ operation: 'announce',
+ impact: null,
+ path: null,
+ to_value: null,
+ };
+ render();
+ expect(screen.getByText(/Chart archived:/)).toBeInTheDocument();
+ expect(screen.getByText(/System ·/)).toBeInTheDocument();
+ await userEvent.click(
+ screen.getByRole('button', { name: 'Sales Transactions' }),
+ );
+ expect(onOpen).toHaveBeenCalledWith(archive);
+});
diff --git a/superset-frontend/src/features/versionHistory/RelatedUpdateRow.tsx b/superset-frontend/src/features/versionHistory/RelatedUpdateRow.tsx
index e83a5fbe9276..f94938c4557f 100644
--- a/superset-frontend/src/features/versionHistory/RelatedUpdateRow.tsx
+++ b/superset-frontend/src/features/versionHistory/RelatedUpdateRow.tsx
@@ -22,6 +22,7 @@ import { styled } from '@apache-superset/core/theme';
import { Icons, Tooltip } from '@superset-ui/core/components';
import type { IconType } from '@superset-ui/core/components/Icons/types';
import type { ActivityEntityKind, ActivityRecord } from './types';
+import { canOpenRelatedEntity } from './lifecycle';
import {
entityDisplayName,
formatAuthor,
@@ -202,7 +203,7 @@ export default function RelatedUpdateRow({
impactCount,
);
}
- const linkable = !record.entity_deleted && Boolean(onOpen);
+ const linkable = canOpenRelatedEntity(record) && Boolean(onOpen);
// Both the server summary and the impact-aware phrasing end with the
// entity name; split it out so the name can render as a link. Records
// without a name can't be split (the empty string matches anywhere).
diff --git a/superset-frontend/src/features/versionHistory/VersionHistoryPanel.test.tsx b/superset-frontend/src/features/versionHistory/VersionHistoryPanel.test.tsx
index 7c33285e3aa6..720c46341293 100644
--- a/superset-frontend/src/features/versionHistory/VersionHistoryPanel.test.tsx
+++ b/superset-frontend/src/features/versionHistory/VersionHistoryPanel.test.tsx
@@ -772,3 +772,23 @@ test('leaves the panel unchanged when no footer is registered', () => {
expect(screen.getByText('No history yet')).toBeInTheDocument();
expect(screen.queryByRole('note')).not.toBeInTheDocument();
});
+
+test('an archive-only dashboard shows activity without a fabricated content version', () => {
+ const timeline = buildTimeline([
+ record({
+ source: 'related',
+ kind: '__archive__',
+ operation: 'announce',
+ version_uuid: null,
+ entity_deletion_state: 'soft_deleted',
+ path: null,
+ to_value: null,
+ }),
+ ]);
+ render();
+ expect(screen.getByText('Chart archived: My chart')).toBeInTheDocument();
+ expect(screen.queryByText('No history yet')).not.toBeInTheDocument();
+ expect(screen.queryByText('Original version')).not.toBeInTheDocument();
+ expect(screen.queryByText('Restore this version')).not.toBeInTheDocument();
+ expect(screen.queryByText('Preview')).not.toBeInTheDocument();
+});
diff --git a/superset-frontend/src/features/versionHistory/display.test.ts b/superset-frontend/src/features/versionHistory/display.test.ts
index 2f290ae88a3b..1875bf184a4a 100644
--- a/superset-frontend/src/features/versionHistory/display.test.ts
+++ b/superset-frontend/src/features/versionHistory/display.test.ts
@@ -521,3 +521,77 @@ test.each([
).toBe(expected);
},
);
+
+test.each(['soft_deleted', null])(
+ 'archive headline remains historical after recovery (%s)',
+ entity_deletion_state => {
+ expect(
+ relatedHeadline(
+ record({
+ source: 'related',
+ kind: '__archive__',
+ operation: 'announce',
+ entity_deletion_state,
+ path: null,
+ to_value: null,
+ summary: '',
+ }),
+ ),
+ ).toBe('Chart archived: My chart');
+ },
+);
+
+test('archive headline uses the untitled fallback without inspecting its payload', () => {
+ expect(
+ relatedHeadline(
+ record({
+ kind: '__archive__',
+ entity_name: '',
+ path: null,
+ to_value: null,
+ }),
+ ),
+ ).toBe('Chart archived: Untitled chart');
+});
+
+test('deleted archive preserves the redacted summary', () => {
+ expect(
+ relatedHeadline(
+ record({
+ kind: '__archive__',
+ entity_deleted: true,
+ entity_name: '',
+ entity_uuid: null,
+ path: null,
+ to_value: null,
+ summary: 'Chart deleted',
+ }),
+ ),
+ ).toBe('Chart deleted');
+});
+
+test('redacted paths can be described without reconstructing their values', () => {
+ expect(
+ describeRecord(
+ record({ kind: 'field', operation: 'edit', path: null, to_value: null }),
+ ),
+ ).toBe("Changed 'setting'");
+});
+
+test('deleted dataset headline retains its affected-chart count without restoring its name', () => {
+ expect(
+ relatedHeadline(
+ record({
+ source: 'related',
+ entity_kind: 'dataset',
+ entity_deleted: true,
+ entity_uuid: null,
+ entity_name: '',
+ summary: '(deleted) Dataset',
+ impact: { charts: 3 },
+ path: null,
+ to_value: null,
+ }),
+ ),
+ ).toBe('Dataset used by 3 charts updated: Untitled dataset');
+});
diff --git a/superset-frontend/src/features/versionHistory/display.ts b/superset-frontend/src/features/versionHistory/display.ts
index 88cb4ca509ef..daa83732d080 100644
--- a/superset-frontend/src/features/versionHistory/display.ts
+++ b/superset-frontend/src/features/versionHistory/display.ts
@@ -25,6 +25,7 @@ import type {
SaveGroup,
CreationKind,
} from './types';
+import { isChartArchiveRecord } from './lifecycle';
/** Activity timestamps are naive UTC; parse as UTC, render local. */
export function parseIssuedAt(issuedAt: string) {
@@ -130,7 +131,7 @@ function recordSubject(record: ActivityRecord): string | null {
if (fromValues && !isOpaqueId(fromValues)) {
return fromValues;
}
- const last = record.path[record.path.length - 1];
+ const last = record.path?.[record.path.length - 1];
if (typeof last === 'string' && last !== '' && !isOpaqueId(last)) {
return last;
}
@@ -148,7 +149,7 @@ function humanizeFieldName(field: string): string {
}
function fieldSubject(record: ActivityRecord): string {
- const path = record.path.filter(
+ const path = (record.path ?? []).filter(
(segment): segment is string => typeof segment === 'string',
);
const meaningful =
@@ -185,7 +186,7 @@ function layoutKindLabel(kind: string): string | null {
* headline, or null when the record isn't a top-level name change.
*/
function renameHeadline(record: ActivityRecord): string | null {
- const field = record.path.length === 1 ? record.path[0] : null;
+ const field = record.path?.length === 1 ? record.path[0] : null;
const to = valueLabel(record.to_value);
switch (field) {
case 'slice_name':
@@ -420,6 +421,12 @@ export function relatedHeadline(
record: ActivityRecord,
records: ActivityRecord[] = [record],
): string {
+ if (isChartArchiveRecord(record)) {
+ if (record.entity_deleted) {
+ return record.summary || t('Item updated: %s', entityDisplayName(record));
+ }
+ return t('Chart archived: %s', entityDisplayName(record));
+ }
const chartCount = record.impact?.charts ?? 0;
if (record.entity_kind === 'dataset' && chartCount > 1) {
// tn even though this branch only runs for counts above one: English has
diff --git a/superset-frontend/src/features/versionHistory/grouping.test.ts b/superset-frontend/src/features/versionHistory/grouping.test.ts
index 0f74e5321d31..d4ab461a2377 100644
--- a/superset-frontend/src/features/versionHistory/grouping.test.ts
+++ b/superset-frontend/src/features/versionHistory/grouping.test.ts
@@ -474,3 +474,48 @@ test('creationKind survives for pre_tracking and imported variants', () => {
expect((entries[0] as SaveGroup).creationKind).toBe(kind);
});
});
+
+test.each([true, false])(
+ 'archive and adjacent update stay separate (archive first: %s)',
+ archiveFirst => {
+ const archive = record({
+ source: 'related',
+ kind: '__archive__',
+ operation: 'announce',
+ version_uuid: null,
+ path: null,
+ to_value: null,
+ transaction_id: archiveFirst ? 12 : 11,
+ });
+ const update = record({
+ source: 'related',
+ transaction_id: archiveFirst ? 11 : 12,
+ });
+ const entries = buildTimeline([archive, update]);
+ expect(entries).toHaveLength(2);
+ expect(
+ entries.map(entry => entry.type === 'related' && entry.records.length),
+ ).toEqual([1, 1]);
+ },
+);
+
+test('bulk archives retain one row per chart and deduplicate overlapping pages', () => {
+ const archives = ['a', 'b', 'c'].map(entity_uuid =>
+ record({
+ source: 'related',
+ kind: '__archive__',
+ operation: 'announce',
+ entity_uuid,
+ version_uuid: null,
+ path: null,
+ to_value: null,
+ }),
+ );
+ const entries = buildTimeline(mergeActivityPages(archives, archives));
+ expect(entries).toHaveLength(3);
+ expect(
+ entries.every(
+ entry => entry.type === 'related' && !entry.rollupEntityNames,
+ ),
+ ).toBe(true);
+});
diff --git a/superset-frontend/src/features/versionHistory/grouping.ts b/superset-frontend/src/features/versionHistory/grouping.ts
index 44b213f3fd80..9c98cc5e770e 100644
--- a/superset-frontend/src/features/versionHistory/grouping.ts
+++ b/superset-frontend/src/features/versionHistory/grouping.ts
@@ -22,6 +22,7 @@ import type {
SaveGroup,
TimelineEntry,
} from './types';
+import { isChartArchiveRecord } from './lifecycle';
/**
* Stable identity for one activity record, used to deduplicate rows
@@ -103,6 +104,8 @@ function mergeAdjacentRelatedEntries(
if (
entry.type === 'related' &&
previous?.type === 'related' &&
+ !isChartArchiveRecord(entry.record) &&
+ !isChartArchiveRecord(previous.record) &&
relatedEntityKey(previous.record) === relatedEntityKey(entry.record) &&
Math.abs(
Date.parse(previous.record.issued_at) -
@@ -133,7 +136,7 @@ function rollupSameTransactionRelated(
): TimelineEntry[] {
const buckets = new Map();
entries.forEach(entry => {
- if (entry.type !== 'related') {
+ if (entry.type !== 'related' || isChartArchiveRecord(entry.record)) {
return;
}
const key = `${entry.record.transaction_id}|${entry.record.entity_kind}`;
diff --git a/superset-frontend/src/features/versionHistory/lifecycle.ts b/superset-frontend/src/features/versionHistory/lifecycle.ts
new file mode 100644
index 000000000000..a0501115fdce
--- /dev/null
+++ b/superset-frontend/src/features/versionHistory/lifecycle.ts
@@ -0,0 +1,34 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+import type { ActivityRecord } from './types';
+
+/** Identify chart archive activity even when its details have been redacted. */
+export function isChartArchiveRecord(record: ActivityRecord): boolean {
+ return record.entity_kind === 'chart' && record.kind === '__archive__';
+}
+
+/** Only active related entities with a stable identity can be opened. */
+export function canOpenRelatedEntity(record: ActivityRecord): boolean {
+ return (
+ !record.entity_deleted &&
+ !record.entity_deletion_state &&
+ Boolean(record.entity_uuid)
+ );
+}
diff --git a/superset-frontend/src/features/versionHistory/openRelated.test.ts b/superset-frontend/src/features/versionHistory/openRelated.test.ts
index 9886a59b6b1f..38d886ed2360 100644
--- a/superset-frontend/src/features/versionHistory/openRelated.test.ts
+++ b/superset-frontend/src/features/versionHistory/openRelated.test.ts
@@ -128,3 +128,30 @@ test('closes the claimed tab when the id lookup fails', async () => {
expect(mockedNavigateOpenedTab).not.toHaveBeenCalled();
expect(mockedCloseOpenedTab).toHaveBeenCalledWith(claimedTab);
});
+
+test.each([
+ { entity_deleted: true },
+ { entity_deletion_state: 'soft_deleted' },
+])('does not resolve or open an unavailable target: %s', async unavailable => {
+ const onError = jest.fn();
+ await openRelatedEntity(record(unavailable), onError);
+ expect(mockedResolveEntityId).not.toHaveBeenCalled();
+ expect(mockedOpenBlankTab).not.toHaveBeenCalled();
+ expect(onError).toHaveBeenCalledWith('Could not find My chart');
+});
+
+test('an archive event can open its recovered chart', async () => {
+ mockedResolveEntityId.mockResolvedValue(42);
+ await openRelatedEntity(
+ record({
+ kind: '__archive__',
+ entity_deleted: false,
+ entity_deletion_state: null,
+ }),
+ jest.fn(),
+ );
+ expect(mockedNavigateOpenedTab).toHaveBeenCalledWith(
+ claimedTab,
+ '/explore/?slice_id=42',
+ );
+});
diff --git a/superset-frontend/src/features/versionHistory/openRelated.ts b/superset-frontend/src/features/versionHistory/openRelated.ts
index c585e73d7658..a801aab7e82f 100644
--- a/superset-frontend/src/features/versionHistory/openRelated.ts
+++ b/superset-frontend/src/features/versionHistory/openRelated.ts
@@ -24,6 +24,7 @@ import {
} from 'src/utils/navigationUtils';
import type { ActivityEntityKind, ActivityRecord } from './types';
import { resolveEntityId } from './api';
+import { canOpenRelatedEntity } from './lifecycle';
function entityUrl(kind: ActivityEntityKind, id: number): string {
if (kind === 'chart') {
@@ -40,7 +41,7 @@ export async function openRelatedEntity(
record: ActivityRecord,
onError: (message: string) => void,
): Promise {
- if (!record.entity_uuid) {
+ if (!record.entity_uuid || !canOpenRelatedEntity(record)) {
onError(t('Could not find %s', record.entity_name));
return;
}
diff --git a/superset-frontend/src/features/versionHistory/types.ts b/superset-frontend/src/features/versionHistory/types.ts
index 34c16179004c..0b0c35326ed3 100644
--- a/superset-frontend/src/features/versionHistory/types.ts
+++ b/superset-frontend/src/features/versionHistory/types.ts
@@ -56,7 +56,7 @@ export interface ActivityRecord {
changed_by: ActivityChangedBy | null;
kind: string;
operation: ActivityOperation;
- path: Array;
+ path: Array | null;
from_value: unknown;
to_value: unknown;
summary: string;
diff --git a/superset-frontend/src/features/versionHistory/useVersionActivity.test.ts b/superset-frontend/src/features/versionHistory/useVersionActivity.test.ts
index 4a1fae71313c..7238491e097e 100644
--- a/superset-frontend/src/features/versionHistory/useVersionActivity.test.ts
+++ b/superset-frontend/src/features/versionHistory/useVersionActivity.test.ts
@@ -422,3 +422,32 @@ test('clearing the uuid ignores an in-flight response', async () => {
expect(result.current.records).toEqual([]);
expect(result.current.count).toBe(0);
});
+
+test('repeated refreshes preserve the newest content-only self response', async () => {
+ mockedFetchActivity.mockImplementation(async (_type, _uuid, options) => ({
+ count: options?.pageSize === 1 ? 1 : 2,
+ result:
+ options?.pageSize === 1
+ ? [record(20, 0)]
+ : [record(20, 0), record(10, 0)],
+ }));
+ const { result } = renderHook(() =>
+ useVersionActivity('chart', 'uuid-1', 'all'),
+ );
+ await waitFor(() =>
+ expect(result.current.currentVersionStatus).toBe('known'),
+ );
+ for (let cycle = 0; cycle < 3; cycle += 1) {
+ await act(async () => result.current.refresh());
+ await waitFor(() =>
+ expect(result.current.currentVersionStatus).toBe('known'),
+ );
+ expect(result.current.newestGroup?.transactionId).toBe(20);
+ expect(result.current.timeline).toHaveLength(2);
+ }
+ expect(mockedFetchActivity).toHaveBeenCalledWith('chart', 'uuid-1', {
+ include: 'self',
+ page: 0,
+ pageSize: 1,
+ });
+});
diff --git a/superset/commands/deletion_retention/purge_cascade.py b/superset/commands/deletion_retention/purge_cascade.py
index 5b73d2c8e745..64a0e038aeda 100644
--- a/superset/commands/deletion_retention/purge_cascade.py
+++ b/superset/commands/deletion_retention/purge_cascade.py
@@ -36,7 +36,8 @@
ORM hard delete of the dataset leaves them.
* **Version history** — the entity's own ``*_version`` shadows and
the ``version_changes`` scoped to them, plus an orphan-sweep of any
- ``version_transaction`` left owning zero surviving shadows. Runs
+ ``version_transaction`` left owning zero surviving shadows, change records,
+ or archive scopes. Runs
behind a ``has_table`` check so it no-ops when versioning is absent.
"""
@@ -372,7 +373,8 @@ def _delete_version_history(session: Session, entity: Any, entity_id: int) -> in
Deletes the entity's parent + child + M2M ``*_version`` shadow rows and the
``version_changes`` rows scoped to this entity (by ``entity_kind`` +
``entity_id`` — **not** by transaction, which is shared), then sweeps any
- ``version_transaction`` left owning zero surviving shadow / change rows. A
+ ``version_transaction`` left owning zero surviving shadow, change,
+ or archive-scope rows. A
``version_transaction`` is a *shared* unit-of-work boundary that can span
entities, so it is removed only once orphaned — never blind-deleted. Gated
on the version tables existing, so it no-ops cleanly without versioning.
@@ -399,39 +401,87 @@ def _delete_version_history(session: Session, entity: Any, entity_id: int) -> in
changes = metadata.tables.get("version_changes")
targets = _entity_version_targets(model, metadata, parent_shadow, entity_id)
- # Transactions these shadow rows are anchored to — orphan-sweep candidates.
- tx_ids: set[int] = set()
- for tbl, pred in targets:
- if "transaction_id" in tbl.c:
- tx_ids.update(
- row[0]
- for row in session.execute(
- sa.select(tbl.c.transaction_id).where(pred).distinct()
- )
- )
+ from superset.versioning.changes import ENTITY_KIND_BY_CLASS_NAME
- removed = 0
- for tbl, pred in targets:
- removed += session.execute(sa.delete(tbl).where(pred)).rowcount
-
- # version_changes scoped to this entity (entity_kind + entity_id).
- # Counted alongside the shadow rows: callers report the total as the
- # definitive number of version-history rows removed.
- if changes is not None:
- from superset.versioning.changes import ENTITY_KIND_BY_CLASS_NAME
-
- kind = ENTITY_KIND_BY_CLASS_NAME.get(model.__name__)
- if kind is not None:
- removed += session.execute(
- sa.delete(changes).where(
+ kind = ENTITY_KIND_BY_CLASS_NAME.get(model.__name__)
+ if changes is not None and kind is not None:
+ targets.append(
+ (
+ changes,
+ sa.and_(
changes.c.entity_kind == kind,
changes.c.entity_id == entity_id,
- )
- ).rowcount
+ ),
+ )
+ )
+
+ scope = metadata.tables.get("version_chart_archive_scope")
+ if scope is not None and not sa.inspect(session.connection()).has_table(scope.name):
+ scope = None
+ # A re-imported dashboard must not remove another incarnation's scopes.
+ if (
+ scope is not None
+ and kind in {"chart", "dashboard"}
+ and entity_uuid(entity) is not None
+ ):
+ identity = scope.c[f"{kind}_uuid"] == entity_uuid(entity)
+ if kind == "chart" and changes is not None:
+ # Existing purge policy removes all changes for the internal chart
+ # ID, including an older incarnation. Remove its event projections
+ # before those canonical changes disappear, avoiding orphan scopes.
+ from superset.versioning.lifecycle import CHART_ARCHIVE_KIND
+
+ identity = sa.or_(
+ identity,
+ sa.exists(
+ sa.select(1)
+ .select_from(changes)
+ .where(
+ changes.c.entity_kind == "chart",
+ changes.c.entity_id == scope.c.chart_id,
+ changes.c.transaction_id == scope.c.transaction_id,
+ changes.c.kind == CHART_ARCHIVE_KIND,
+ )
+ ),
+ )
+ targets.insert(
+ 0, (scope, sa.and_(scope.c[f"{kind}_id"] == entity_id, identity))
+ )
+
+ tx_ids: set[int] = set()
+ removed = _delete_history_targets(session, targets, tx_ids)
if tx is not None and tx_ids:
- _sweep_orphan_transactions(session, metadata, tx, changes, tx_ids)
+ _sweep_orphan_transactions(session, metadata, tx, changes, tx_ids, scope)
+
+ return removed
+
+def _delete_history_targets(
+ session: Session,
+ targets: list[tuple[sa.Table, Any]],
+ tx_ids: set[int],
+) -> int:
+ """Remove scoped history and collect every referenced transaction for sweeping."""
+ removed = 0
+ for table, predicate in targets:
+ # Both shadow endpoints can become orphaned when their rows are removed.
+ # Change records and archive scopes have only the opening endpoint.
+ endpoints = [
+ table.c[name]
+ for name in ("transaction_id", "end_transaction_id")
+ if name in table.c
+ ]
+ if endpoints:
+ tx_ids.update(
+ endpoint
+ for row in session.execute(
+ sa.select(*endpoints).where(predicate).distinct()
+ )
+ for endpoint in row
+ if endpoint is not None
+ )
+ removed += session.execute(sa.delete(table).where(predicate)).rowcount
return removed
@@ -456,10 +506,12 @@ def _sweep_orphan_transactions(
tx: sa.Table,
changes: sa.Table | None,
tx_ids: set[int],
+ archive_scope: sa.Table | None = None,
) -> None:
"""Delete unreferenced ``version_transaction`` rows.
- Every ``*_version`` table and ``version_changes`` is checked. A double-sweep
+ Every ``*_version`` table, ``version_changes``, and archive scope is checked.
+ A double-sweep
of the same orphan is a harmless no-op.
A shadow row references a transaction through **either** endpoint of its
@@ -485,6 +537,8 @@ def _sweep_orphan_transactions(
]
if changes is not None and "transaction_id" in changes.c:
sources.append(changes)
+ if archive_scope is not None:
+ sources.append(archive_scope)
still_referenced: set[int] = set()
for source in sources:
# ``version_changes`` has no closing endpoint; shadow tables do.
diff --git a/superset/initialization/__init__.py b/superset/initialization/__init__.py
index cc1413b99c3a..54cf613771c2 100644
--- a/superset/initialization/__init__.py
+++ b/superset/initialization/__init__.py
@@ -855,6 +855,9 @@ def init_versioning(self) -> None:
# at the same restart is the cheap, observability-positive shape.
self._warn_if_retention_beat_missing()
+ # Register archive scope metadata even when capture is disabled.
+ from superset.versioning import lifecycle_table # noqa: F401
+
if not self.config.get("ENABLE_VERSIONING_CAPTURE", False):
logger.warning(
"versioning: ENABLE_VERSIONING_CAPTURE is False; "
diff --git a/superset/migrations/versions/2026-11-23_00-00_a7d29bc4e681_add_chart_archive_scope.py b/superset/migrations/versions/2026-11-23_00-00_a7d29bc4e681_add_chart_archive_scope.py
new file mode 100644
index 000000000000..40c5c6f53bee
--- /dev/null
+++ b/superset/migrations/versions/2026-11-23_00-00_a7d29bc4e681_add_chart_archive_scope.py
@@ -0,0 +1,78 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""Persist chart archive dashboard membership.
+
+Revision ID: a7d29bc4e681
+Revises: dfa683969f48
+Create Date: 2026-11-23 00:00:00.000000
+"""
+
+import sqlalchemy as sa
+from alembic import op
+from sqlalchemy_utils import UUIDType
+
+from superset.migrations.shared.utils import (
+ create_index,
+ create_table,
+ drop_table,
+ has_table,
+)
+
+revision = "a7d29bc4e681"
+down_revision = "dfa683969f48"
+
+
+def upgrade() -> None:
+ """Create empty scope storage and complete indexes on interrupted upgrades."""
+ create_table(
+ "version_chart_archive_scope",
+ sa.Column("id", UUIDType(binary=True), nullable=False),
+ sa.Column("transaction_id", sa.BigInteger, nullable=False),
+ sa.Column("chart_id", sa.Integer, nullable=False),
+ sa.Column("chart_uuid", UUIDType(binary=True), nullable=False),
+ sa.Column("dashboard_id", sa.Integer, nullable=False),
+ sa.Column("dashboard_uuid", UUIDType(binary=True), nullable=False),
+ sa.PrimaryKeyConstraint("id"),
+ sa.ForeignKeyConstraint(
+ ["transaction_id"], ["version_transaction.id"], ondelete="CASCADE"
+ ),
+ sa.UniqueConstraint(
+ "transaction_id",
+ "chart_uuid",
+ "dashboard_id",
+ "dashboard_uuid",
+ name="uq_chart_archive_scope_identity",
+ ),
+ )
+ create_index(
+ "version_chart_archive_scope",
+ "ix_chart_archive_scope_dashboard",
+ ["dashboard_id", "dashboard_uuid", "transaction_id"],
+ )
+ create_index(
+ "version_chart_archive_scope",
+ "ix_chart_archive_scope_chart",
+ ["chart_id", "transaction_id"],
+ )
+
+
+def downgrade() -> None:
+ """Remove archive records while preserving content and transaction rows."""
+ drop_table("version_chart_archive_scope")
+ if has_table("version_changes"):
+ changes = sa.table("version_changes", sa.column("kind", sa.String(32)))
+ op.get_bind().execute(changes.delete().where(changes.c.kind == "__archive__"))
diff --git a/superset/tasks/version_history_retention.py b/superset/tasks/version_history_retention.py
index 6b77a790abdd..0638d82f07b1 100644
--- a/superset/tasks/version_history_retention.py
+++ b/superset/tasks/version_history_retention.py
@@ -72,7 +72,7 @@
@dataclass(frozen=True)
class ShadowTables:
- """The four Continuum-managed Table objects the prune walks.
+ """The content shadows and activity tables the prune walks.
Bundled here so the prune helper's signature stays at two arguments
instead of five. The shape is set once at task entry by
@@ -83,6 +83,7 @@ class ShadowTables:
child: list[sa.Table]
m2m: sa.Table | None
transaction: sa.Table
+ archive_scope: sa.Table | None = None
def _resolve_shadow_tables(tx_table: sa.Table) -> ShadowTables:
@@ -143,6 +144,11 @@ def _resolve_shadow_tables(tx_table: sa.Table) -> ShadowTables:
child=child_tables,
m2m=m2m_table,
transaction=tx_table,
+ archive_scope=(
+ metadata.tables.get("version_chart_archive_scope")
+ if metadata is not None
+ else None
+ ),
)
@@ -436,6 +442,24 @@ def _run_prune_pass(
else 0
)
+ # Scope rows do not anchor live content. Explicit cleanup also
+ # covers metadata-created schemas without the migration's FK.
+ archive_scope_rows = 0
+ if (
+ tx_ids
+ and tables.archive_scope is not None
+ and sa.inspect(conn).has_table(tables.archive_scope.name)
+ ):
+ for chunk in _chunked(tx_ids, _TX_ID_CHUNK_SIZE):
+ archive_scope_rows += (
+ conn.execute(
+ sa.delete(tables.archive_scope).where(
+ tables.archive_scope.c.transaction_id.in_(chunk)
+ )
+ ).rowcount
+ or 0
+ )
+
# Drop the version_transaction rows themselves. ON DELETE
# CASCADE on version_changes.transaction_id removes the
# associated change records automatically. Same SQLite bind-
@@ -483,6 +507,7 @@ def _run_prune_pass(
"pruned_parent_shadows": parent_rows,
"pruned_child_shadows": child_rows,
"pruned_m2m_shadows": m2m_rows,
+ "pruned_archive_scopes": archive_scope_rows,
}
@@ -662,6 +687,7 @@ def _prune_old_versions_impl(
"pruned_parent_shadows": 0,
"pruned_child_shadows": 0,
"pruned_m2m_shadows": 0,
+ "pruned_archive_scopes": 0,
}
total_retried: int = 0
after_id: int = 0
diff --git a/superset/translations/messages.pot b/superset/translations/messages.pot
index 26725ac492a1..453afab1439a 100644
--- a/superset/translations/messages.pot
+++ b/superset/translations/messages.pot
@@ -3328,6 +3328,10 @@ msgstr ""
msgid "Chart [%s] was added to dashboard [%s]"
msgstr ""
+#, python-format
+msgid "Chart archived: %s"
+msgstr ""
+
msgid "Chart cache timeout"
msgstr ""
diff --git a/superset/versioning/activity/orchestrator.py b/superset/versioning/activity/orchestrator.py
index d2acf94f4997..79d8a3befbf4 100644
--- a/superset/versioning/activity/orchestrator.py
+++ b/superset/versioning/activity/orchestrator.py
@@ -277,7 +277,8 @@ def get_activity(
self_start_tx = first_tracked_tx(model_cls, path_id, path_entity.uuid)
with _phase_timer(kind_key, "relationship_resolution_ms"):
entity_windows = resolve_scope(path_kind, path_id, include, self_start_tx)
- if not entity_windows:
+ include_archives = path_kind == "Dashboard" and include in {"all", "related"}
+ if not entity_windows and not include_archives:
_emit_request_shape_attributes(
kind_key,
include=include,
@@ -296,7 +297,16 @@ def get_activity(
# tombstone probes + impact counts on records the requester
# can't see (the silent-filter contract).
with _phase_timer(kind_key, "fetch_ms"):
- records, truncated = fetch_change_records(entity_windows, since, until)
+ if include_archives:
+ records, truncated = fetch_change_records(
+ entity_windows,
+ since,
+ until,
+ dashboard_id=path_id,
+ dashboard_uuid=path_entity.uuid,
+ )
+ else:
+ records, truncated = fetch_change_records(entity_windows, since, until)
with _phase_timer(kind_key, "visibility_filter_ms"):
records = filter_records_by_visibility(records)
with _phase_timer(kind_key, "denormalize_ms"):
diff --git a/superset/versioning/activity/queries.py b/superset/versioning/activity/queries.py
index 0b8f998307e6..6d207a671983 100644
--- a/superset/versioning/activity/queries.py
+++ b/superset/versioning/activity/queries.py
@@ -63,6 +63,7 @@
ACTION_KINDS,
version_changes_table,
)
+from superset.versioning.lifecycle import CHART_ARCHIVE_KIND
logger = logging.getLogger(__name__)
@@ -209,6 +210,9 @@ def fetch_change_records(
entity_window_tuples: list[EntityWindows],
since: datetime | None,
until: datetime | None,
+ *,
+ dashboard_id: int | None = None,
+ dashboard_uuid: UUID | None = None,
) -> tuple[list[dict[str, Any]], bool]:
"""Fetch all ``version_changes`` rows matching any of the supplied
entity-window tuples, joined with ``version_transaction`` for
@@ -236,7 +240,8 @@ def fetch_change_records(
over the filtered list — there is no DB-level page ``OFFSET`` here.
There IS a per-kind safety ceiling (``_MAX_FETCHED_RECORDS``) that
bounds how much history a single request materializes (to at most
- ``n_kinds * _MAX_FETCHED_RECORDS``); when a kind exhausts it, the
+ ``(n_kinds + 1) * _MAX_FETCHED_RECORDS`` including dashboard archives);
+ when a stream exhausts it, the
second return value is ``True``, the returned stream is clamped to a
clean total-order cut (records below the highest per-kind fetch floor
are dropped so truncation does not create per-kind holes), and the caller
@@ -246,9 +251,6 @@ def fetch_change_records(
``(issued_at DESC, transaction_id DESC, sequence DESC)`` — the
secondary keys break ties for the stable-ordering contract.
"""
- if not entity_window_tuples:
- return [], False
-
# Group windows by (table_kind, entity_id) and by table_kind for SQL
# narrowing. The fetch is per-kind; the post-filter is per-entity.
windows_by_entity: dict[tuple[str, int], list[Window]] = {}
@@ -260,9 +262,6 @@ def fetch_change_records(
ids_by_kind.setdefault(table_kind, set()).add(entity_id)
windows_by_entity.setdefault((table_kind, entity_id), []).extend(windows)
- if not ids_by_kind:
- return [], False
-
# Per-kind transaction_id bounds = the union of that kind's windows.
# Pushing these into the SQL WHERE ensures the per-statement LIMIT
# selects from IN-WINDOW rows. Without it, a related entity whose
@@ -289,6 +288,18 @@ def fetch_change_records(
until,
_MAX_FETCHED_RECORDS,
)
+ if dashboard_id is not None and dashboard_uuid is not None:
+ archives, archive_truncated, archive_floor = (
+ _fetch_dashboard_archive_candidates(
+ dashboard_id, dashboard_uuid, since, until, _MAX_FETCHED_RECORDS
+ )
+ )
+ rows.extend(archives)
+ truncated = truncated or archive_truncated
+ floors = [
+ floor for floor in (truncation_floor, archive_floor) if floor is not None
+ ]
+ truncation_floor = max(floors) if floors else None
filtered = rows
if truncated and truncation_floor is not None:
# Collapse truncation to a clean cut in the same TOTAL order used by
@@ -311,39 +322,8 @@ def fetch_change_records(
return filtered, truncated
-def _select_change_rows_for_kinds(
- ids_by_kind: dict[str, set[int]],
- bounds_by_kind: dict[str, tuple[int, int | None]],
- windows_by_entity: dict[tuple[str, int], list[Window]],
- since: datetime | None,
- until: datetime | None,
- limit: int,
-) -> tuple[list[dict[str, Any]], bool, RecordSortKey | None]:
- """Fetch bounded candidates per entity kind and ID chunk.
-
- Each SELECT uses ``entity_id IN (...)`` and joins ``version_transaction``
- + ``ab_user`` so the orchestrator has the columns it needs for
- decoration.
-
- Per-kind, not one query: SQLAlchemy's ``tuple_(entity_kind,
- entity_id).in_(...)`` would collapse the three queries into one,
- but its SQL emission is not portable across Postgres, MySQL, and
- SQLite. The per-kind shape is the correct trade-off given
- Superset's multi-dialect requirement (at most 3 round-trips per
- request, bounded by the kind taxonomy). Do not "optimise" into a
- composite-tuple IN clause without verifying the SQL on all three
- dialects.
-
- **Init-order dependency.** ``tx_tbl.c.action_kind`` resolves only
- after ``init_versioning()`` has run — the column is appended onto
- Continuum's transaction Table by
- ``superset.versioning.factory.VersionTransactionFactory`` at app
- start via ``append_column`` + ``add_property``. This helper is
- safe to call from request-path code because the app is fully
- initialised by then; calling it from a script that imports the
- versioning package without going through ``init_versioning()``
- will raise ``AttributeError`` on the ``action_kind`` attribute
- access below."""
+def _change_record_projection() -> tuple[tuple[Any, ...], Any, sa.Table]:
+ """Share the DTO projection between disjoint content and archive streams."""
# pylint: disable=import-outside-toplevel
from sqlalchemy_continuum import versioning_manager
@@ -384,6 +364,47 @@ def _select_change_rows_for_kinds(
user_tbl.c.last_name,
)
+ return select_cols, join_tree, tx_tbl
+
+
+def _select_change_rows_for_kinds(
+ ids_by_kind: dict[str, set[int]],
+ bounds_by_kind: dict[str, tuple[int, int | None]],
+ windows_by_entity: dict[tuple[str, int], list[Window]],
+ since: datetime | None,
+ until: datetime | None,
+ limit: int,
+) -> tuple[list[dict[str, Any]], bool, RecordSortKey | None]:
+ """Fetch bounded candidates per entity kind and ID chunk.
+
+ Each SELECT uses ``entity_id IN (...)`` and joins ``version_transaction``
+ + ``ab_user`` so the orchestrator has the columns it needs for
+ decoration.
+
+ Per-kind, not one query: SQLAlchemy's ``tuple_(entity_kind,
+ entity_id).in_(...)`` would collapse the three queries into one,
+ but its SQL emission is not portable across Postgres, MySQL, and
+ SQLite. The per-kind shape is the correct trade-off given
+ Superset's multi-dialect requirement (at most 3 round-trips per
+ request, bounded by the kind taxonomy). Do not "optimise" into a
+ composite-tuple IN clause without verifying the SQL on all three
+ dialects.
+
+ **Init-order dependency.** ``tx_tbl.c.action_kind`` resolves only
+ after ``init_versioning()`` has run — the column is appended onto
+ Continuum's transaction Table by
+ ``superset.versioning.factory.VersionTransactionFactory`` at app
+ start via ``append_column`` + ``add_property``. This helper is
+ safe to call from request-path code because the app is fully
+ initialised by then; calling it from a script that imports the
+ versioning package without going through ``init_versioning()``
+ will raise ``AttributeError`` on the ``action_kind`` attribute
+ access below."""
+ if not ids_by_kind:
+ return [], False, None
+ select_cols, join_tree, tx_tbl = _change_record_projection()
+ vc = version_changes_table
+
out: list[dict[str, Any]] = []
truncated = False
truncation_floors: list[RecordSortKey] = []
@@ -403,6 +424,7 @@ def _select_change_rows_for_kinds(
.select_from(join_tree)
.where(
vc.c.entity_kind == table_kind,
+ vc.c.kind != CHART_ARCHIVE_KIND,
vc.c.entity_id.in_(chunk),
)
)
@@ -455,6 +477,104 @@ def _select_change_rows_for_kinds(
return out, truncated, truncation_floor
+def archive_entity_uuid(record: dict[str, Any]) -> UUID | None:
+ """Validate archive payload identity without borrowing a live incarnation."""
+ payload = record.get("to_value")
+ if not isinstance(payload, dict):
+ return None
+ value = payload.get("entity_uuid")
+ if not isinstance(value, (str, UUID)):
+ return None
+ try:
+ return UUID(str(value))
+ except ValueError:
+ return None
+
+
+def _fetch_dashboard_archive_candidates(
+ path_id: int,
+ path_uuid: UUID,
+ since: datetime | None,
+ until: datetime | None,
+ limit: int,
+) -> tuple[list[dict[str, Any]], bool, RecordSortKey | None]:
+ """Read bounded immutable archive membership independently of content windows."""
+ # pylint: disable=import-outside-toplevel
+ from sqlalchemy.exc import DBAPIError
+
+ from superset.versioning.db_errors import is_missing_table_error
+ from superset.versioning.lifecycle import (
+ begin_capture_savepoint,
+ release_capture_savepoint,
+ rollback_capture_savepoint,
+ )
+ from superset.versioning.lifecycle_table import version_chart_archive_scope_table
+
+ scope = version_chart_archive_scope_table
+ vc = version_changes_table
+ columns, join_tree, tx_tbl = _change_record_projection()
+ stmt = (
+ sa.select(*columns, scope.c.chart_uuid.label("scope_chart_uuid"))
+ .select_from(
+ join_tree.join(
+ scope,
+ sa.and_(
+ scope.c.transaction_id == vc.c.transaction_id,
+ scope.c.chart_id == vc.c.entity_id,
+ ),
+ )
+ )
+ .where(
+ vc.c.entity_kind == "chart",
+ vc.c.kind == CHART_ARCHIVE_KIND,
+ scope.c.dashboard_id == path_id,
+ scope.c.dashboard_uuid == path_uuid,
+ )
+ .order_by(
+ tx_tbl.c.issued_at.desc(),
+ vc.c.transaction_id.desc(),
+ vc.c.sequence.desc(),
+ vc.c.entity_kind.desc(),
+ vc.c.entity_id.desc(),
+ )
+ )
+ if since is not None:
+ stmt = stmt.where(tx_tbl.c.issued_at >= since)
+ if until is not None:
+ stmt = stmt.where(tx_tbl.c.issued_at < until)
+
+ connection = db.session.connection()
+ outer_transaction = connection.get_transaction()
+ assert outer_transaction is not None
+ savepoint = begin_capture_savepoint(connection, outer_transaction)
+ result = None
+ rows: list[dict[str, Any]] = []
+ try:
+ result = connection.execute(
+ stmt.execution_options(stream_results=True)
+ ).mappings()
+ try:
+ for mapping in result:
+ row = dict(mapping)
+ scope_uuid = row.pop("scope_chart_uuid")
+ if archive_entity_uuid(row) != scope_uuid:
+ continue
+ rows.append(row)
+ if len(rows) > limit:
+ break
+ finally:
+ result.close()
+ except Exception as error:
+ rollback_capture_savepoint(connection, savepoint, outer_transaction, error)
+ if isinstance(error, DBAPIError) and is_missing_table_error(error):
+ return [], False, None
+ raise
+ release_capture_savepoint(connection, savepoint, outer_transaction)
+ truncated = len(rows) > limit
+ rows = rows[:limit]
+ return rows, truncated, _record_sort_key(rows[-1]) if truncated else None
+
+
def _record_sort_key(record: dict[str, Any]) -> RecordSortKey:
"""Return the total newest-first activity ordering key."""
return (
@@ -499,7 +619,8 @@ def _merge_result_into_heap(
# Per-KIND safety ceiling on how many change rows a single activity request
# will retain for one entity kind (shared across that kind's id-chunks).
# Bounds application memory for a path entity with very long history or many
-# related entities to <= n_kinds * (_MAX_FETCHED_RECORDS + 1) per request.
+# related entities to <= (n_kinds + 1) * (_MAX_FETCHED_RECORDS + 1) per request,
+# including the independent dashboard archive stream.
# When a kind exhausts its budget the response is flagged ``truncated`` and
# the returned stream is clamped to a clean total-order cut.
_MAX_FETCHED_RECORDS: int = 5000
@@ -701,7 +822,7 @@ def resolve_historical_entity_snapshots(
needed_by_kind: dict[str, set[tuple[int, int]]] = {}
for record in records:
api_kind = TABLE_KIND_TO_API.get(record["entity_kind"])
- if api_kind is None:
+ if api_kind is None or record.get("kind") == CHART_ARCHIVE_KIND:
continue
needed_by_kind.setdefault(api_kind, set()).add(
(record["entity_id"], record["transaction_id"])
@@ -735,7 +856,11 @@ def apply_entity_name_denormalization(records: list[dict[str, Any]]) -> None:
needed_by_kind: dict[str, set[tuple[int, int]]] = {}
for record in records:
api_kind = TABLE_KIND_TO_API.get(record["entity_kind"])
- if api_kind is None or api_kind not in NAME_COLUMN:
+ if (
+ api_kind is None
+ or api_kind not in NAME_COLUMN
+ or record.get("kind") == CHART_ARCHIVE_KIND
+ ):
continue
needed_by_kind.setdefault(api_kind, set()).add(
(record["entity_id"], record["transaction_id"])
@@ -751,7 +876,16 @@ def apply_entity_name_denormalization(records: list[dict[str, Any]]) -> None:
for record in records:
api_kind_for_record = TABLE_KIND_TO_API.get(record["entity_kind"], "")
key = (api_kind_for_record, record["entity_id"], record["transaction_id"])
- record["entity_name"] = resolved.get(key, "")
+ if record.get("kind") == CHART_ARCHIVE_KIND:
+ payload = record.get("to_value")
+ payload_name = (
+ payload.get("entity_name") if isinstance(payload, dict) else None
+ )
+ record["entity_name"] = (
+ payload_name if isinstance(payload_name, str) else ""
+ )
+ else:
+ record["entity_name"] = resolved.get(key, "")
# ---- Live-row existence + soft-delete state -------------------------------
diff --git a/superset/versioning/activity/render.py b/superset/versioning/activity/render.py
index 9d357eeb8179..d79164d9aaef 100644
--- a/superset/versioning/activity/render.py
+++ b/superset/versioning/activity/render.py
@@ -59,13 +59,16 @@
USER_FACING_KIND,
)
from superset.versioning.activity.queries import (
+ archive_entity_uuid,
check_entity_tombstones,
resolve_historical_entity_snapshots,
)
from superset.versioning.activity.visibility import resolve_editorship
+from superset.versioning.lifecycle import CHART_ARCHIVE_KIND
from superset.versioning.queries import derive_version_uuid
_SUMMARY_VERBS: dict[str, str] = {
+ CHART_ARCHIVE_KIND: "archived",
# The kind taxonomy mapped to past-tense verbs for the
# " : " headline. "field" is
# the fallback for scalar changes that don't map to a named verb.
@@ -132,16 +135,19 @@ def apply_record_decoration(
historical_uuid, snapshot_tx = historical_snapshots.get(
(api_kind, entity_id, record["transaction_id"]), (None, None)
)
+ is_archive = record.get("kind") == CHART_ARCHIVE_KIND
+ if is_archive:
+ historical_uuid = archive_entity_uuid(record)
reused_identity = (
live_uuid is not None
and historical_uuid is not None
and live_uuid != historical_uuid
)
entity_uuid = historical_uuid or live_uuid
- if tombstone["deleted"] or reused_identity:
- entity_uuid = None
- if reused_identity:
+ if reused_identity or (is_archive and historical_uuid is None):
tombstone = {"deleted": True, "deletion_state": None}
+ if tombstone["deleted"]:
+ entity_uuid = None
is_self = api_kind == path_kind and entity_id == path_id
# Emit the user-facing form ("dashboard"/"chart"/"dataset") on the
diff --git a/superset/versioning/activity/visibility.py b/superset/versioning/activity/visibility.py
index 26a27d03a597..fbdd92a928f6 100644
--- a/superset/versioning/activity/visibility.py
+++ b/superset/versioning/activity/visibility.py
@@ -212,6 +212,7 @@ def _resolve_visibility(
from flask_appbuilder.models.sqla.interface import SQLAInterface
from superset.charts.filters import ChartFilter
+ from superset.constants import SKIP_VISIBILITY_FILTER_CLASSES
from superset.dashboards.filters import DashboardAccessFilter
from superset.views.base import DatasourceFilter
@@ -253,6 +254,12 @@ def _resolve_visibility(
continue
model_cls = load_live_model(NAME_COLUMN[api_kind][0])
access_filter = access_filter_classes[api_kind]("id", SQLAInterface(model_cls))
+ # Archived related rows still use their resource's normal read policy.
+ visibility_options = (
+ {SKIP_VISIBILITY_FILTER_CLASSES: {model_cls}}
+ if api_kind in {"Slice", "SqlaTable"}
+ else {}
+ )
# Chunk the candidate ids to stay under SQLite's bind-variable floor
# (a dashboard built from a large chart library can exceed it).
@@ -266,6 +273,7 @@ def _resolve_visibility(
live_ids.update(
row[0]
for row in db.session.query(model_cls.id)
+ .execution_options(**visibility_options)
.filter(model_cls.id.in_(chunk))
.all()
)
@@ -275,7 +283,9 @@ def _resolve_visibility(
visible_ids.update(
row[0]
for row in access_filter.apply(
- db.session.query(model_cls.id).filter(model_cls.id.in_(chunk)),
+ db.session.query(model_cls.id)
+ .execution_options(**visibility_options)
+ .filter(model_cls.id.in_(chunk)),
value=None,
).all()
)
diff --git a/superset/versioning/changes/listener.py b/superset/versioning/changes/listener.py
index 6d3d5f91e945..e587a22b6fb1 100644
--- a/superset/versioning/changes/listener.py
+++ b/superset/versioning/changes/listener.py
@@ -48,7 +48,7 @@
import sqlalchemy as sa
from sqlalchemy import event
-from sqlalchemy.exc import OperationalError, ProgrammingError
+from sqlalchemy.exc import DBAPIError, OperationalError, ProgrammingError
from sqlalchemy.orm import Session, SessionTransaction
from superset.versioning.changes.normalization import NORMALIZATION_CONTEXT_KEY
@@ -62,7 +62,10 @@
compute_records_from_state,
)
from superset.versioning.changes.table import ENTITY_KIND_BY_CLASS_NAME
-from superset.versioning.db_errors import is_missing_table_error
+from superset.versioning.db_errors import (
+ is_lost_transaction_error,
+ is_missing_table_error,
+)
from superset.versioning.diff import (
ChangeRecord,
fold_dashboard_layout_with_chart_changes,
@@ -213,7 +216,9 @@ def _build_scalar_buffer(
for key, (obj, pre_state) in initial_states.items():
try:
records = compute_records_from_state(obj, pre_state)
- except Exception: # pylint: disable=broad-except
+ except Exception as error: # pylint: disable=broad-except
+ if isinstance(error, DBAPIError) or is_lost_transaction_error(error):
+ raise
logger.exception(
"version_changes: final diff failed for %s id=%s",
type(obj).__name__,
@@ -273,7 +278,9 @@ def _append_child_records_to_buffer(
buffer[key] = fold_dashboard_layout_with_chart_changes(buffer[key])
if not buffer[key]:
del buffer[key]
- except Exception: # pylint: disable=broad-except
+ except Exception as error: # pylint: disable=broad-except
+ if isinstance(error, DBAPIError) or is_lost_transaction_error(error):
+ raise
logger.exception("version_changes: child-diff failed for tx %s", tx_id)
incr_capture_error("child_diff")
@@ -387,7 +394,9 @@ def _stamp_action_kind_on_transaction(
return
action_kind = ACTION_KIND_CREATE
_write_action_kind(session, tx_tbl, tx_id, action_kind)
- except Exception: # pylint: disable=broad-except
+ except Exception as error: # pylint: disable=broad-except
+ if is_lost_transaction_error(error):
+ raise
logger.exception(
"version_changes: failed to stamp action_kind=%s on tx %s",
action_kind,
@@ -421,15 +430,16 @@ def _persist_buffered_records(
with session.connection().begin_nested():
bulk_insert_records(session, tx_id, buffer)
except Exception as ex: # pylint: disable=broad-except
+ if is_lost_transaction_error(ex):
+ raise
if isinstance(
ex, (OperationalError, ProgrammingError)
) and is_missing_table_error(ex):
# version_changes table missing (migration not yet applied) —
# the one genuinely benign case; stay quiet.
return
- # Everything else — a deadlock or dropped connection as much as a
- # malformed record — is a real capture loss. Swallowing it silently
- # made "the save succeeded but its history doesn't exist" invisible.
+ # Recoverable failures are capture loss. Logging keeps a successful
+ # save with missing history visible even without a metrics backend.
logger.exception(
"version_changes: bulk insert failed for tx %s (%d entities)",
tx_id,
@@ -438,6 +448,37 @@ def _persist_buffered_records(
incr_capture_error("bulk_insert")
+def _capture_lifecycle(
+ session: Session,
+ initial_states: dict[tuple[str, int], tuple[Any, dict[str, Any]]],
+) -> None:
+ """Skip ordinary collection failures while propagating unsafe database state."""
+ from superset.versioning.lifecycle import (
+ capture_chart_archives,
+ collect_chart_archives,
+ LifecycleCaptureFatalError,
+ )
+
+ try:
+ archives = collect_chart_archives(session, initial_states)
+ except LifecycleCaptureFatalError:
+ raise
+ except Exception as error: # pylint: disable=broad-except
+ # Collection has no SQL savepoint. A failed database read cannot be
+ # assumed isolated, unlike an ordinary missing/deleted ORM instance.
+ if isinstance(error, DBAPIError) or is_lost_transaction_error(error):
+ raise
+ logger.exception("version_changes: archive transition collection failed")
+ incr_capture_error("lifecycle_collect")
+ archives = []
+ try:
+ capture_chart_archives(session, archives)
+ except LifecycleCaptureFatalError:
+ logger.exception("version_changes: fatal archive capture failure")
+ incr_capture_error("lifecycle_fatal")
+ raise
+
+
def finalize_change_records(session: Session) -> None:
"""Build and persist the transaction's change records at commit time.
@@ -445,7 +486,17 @@ def finalize_change_records(session: Session) -> None:
so the capture write path can be exercised directly by unit tests
against an isolated session; it depends only on the session and the
module helpers, never on the registered entity classes.
+
+ Ordinary computation failures may skip optional metadata. DBAPI failures in
+ unisolated scalar, child, transaction-lookup, or archive-collection reads
+ propagate because no savepoint rollback proves caller work survived. This
+ policy applies to ordinary content saves as well as archives, preventing a
+ successful commit response after the database rolled back the user's work.
"""
+ from sqlalchemy_continuum import versioning_manager
+
+ if not versioning_manager.options["versioning"]:
+ return
if session.in_nested_transaction() or session.info.get(_FINALIZING_KEY):
return
if not capture_for_write(session):
@@ -471,20 +522,21 @@ def finalize_change_records(session: Session) -> None:
try:
tx_id: int | None = _current_transaction_id(session)
- except Exception: # pylint: disable=broad-except
+ except Exception as error: # pylint: disable=broad-except
+ if isinstance(error, DBAPIError) or is_lost_transaction_error(error):
+ raise
logger.exception("version_changes: transaction lookup failed")
incr_capture_error("transaction_lookup")
return
- if tx_id is None:
- return
-
- _stamp_action_kind_on_transaction(session, tx_id)
- _append_child_records_to_buffer(session, tx_id, buffer)
- _inject_action_meta_record(session, buffer)
-
- if buffer:
- _persist_buffered_records(session, tx_id, buffer)
- reconcile_parent_snapshots(session, tx_id)
+ if tx_id is not None:
+ _stamp_action_kind_on_transaction(session, tx_id)
+ _append_child_records_to_buffer(session, tx_id, buffer)
+ _inject_action_meta_record(session, buffer)
+
+ if buffer:
+ _persist_buffered_records(session, tx_id, buffer)
+ reconcile_parent_snapshots(session, tx_id)
+ _capture_lifecycle(session, initial_states)
finally:
session.info.pop(_FINALIZING_KEY, None)
if start is not None:
diff --git a/superset/versioning/db_errors.py b/superset/versioning/db_errors.py
index 786e525f34b8..8f1f65ba5b70 100644
--- a/superset/versioning/db_errors.py
+++ b/superset/versioning/db_errors.py
@@ -14,20 +14,20 @@
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
-"""Classify database errors the versioning capture path swallows.
-
-The capture listeners fail open — a versioning bug must never break a
-user's save — and one failure is genuinely benign: the versioning tables
-not existing yet, during the window between deploying the code and
-running its migration. The listeners swallow that case silently.
-
-But the exception classes that case raises (``OperationalError`` on
-SQLite/MySQL, ``ProgrammingError`` on PostgreSQL) also cover deadlocks,
-lock timeouts, and dropped connections. Swallowing the whole class turns
-any of those into a silent capture drop: the user's save succeeds and its
-version history quietly doesn't exist. :func:`is_missing_table_error`
-separates the benign case from everything else, so the listeners can stay
-quiet for the migration race and log-plus-count the rest.
+"""Classify database failures at version-history capture boundaries.
+
+Database failures during optional metadata writes may be skipped only when
+savepoint recovery proves caller work survived. Missing versioning tables are a
+quiet rollout case after successful rollback; other recoverable capture failures
+are logged and counted.
+Lost transactions and invalidated connections must propagate to the caller.
+
+Unisolated finalization reads also fail closed on DBAPI errors, including during
+ordinary content saves without archive activity. Without a savepoint rollback,
+continuation could report success after the database discarded the user's work.
+Ordinary computation errors remain optional capture failures. Driver diagnostics
+separate missing tables, recoverable statement failures, and transaction loss;
+exception class alone does not establish that a failed statement was isolated.
"""
from __future__ import annotations
@@ -116,6 +116,42 @@ def is_lock_contention_error(exc: BaseException | None) -> bool:
return any(phrase in text for phrase in _LOCK_CONTENTION_PHRASES)
+def is_lost_transaction_error(exc: BaseException | None) -> bool:
+ """Recognize structured evidence that optional capture lost caller work.
+
+ MySQL deadlocks roll back the whole transaction; a missing savepoint or an
+ invalidated connection also makes continuation unsafe. PostgreSQL deadlocks
+ and MySQL lock timeouts alone are not fatal: an enclosing savepoint may
+ isolate them. Inspect exception chains because savepoint cleanup can replace
+ the original driver error. Only DBAPIError.orig supplies structured driver
+ diagnostics: ordinary Python exception arguments are not database errnos.
+ Never classify on SQL or parameter text.
+ """
+ pending = [exc] if exc is not None else []
+ seen: set[int] = set()
+ while pending:
+ error = pending.pop()
+ if id(error) in seen:
+ continue
+ seen.add(id(error))
+ if isinstance(error, DBAPIError) and error.connection_invalidated:
+ return True
+ diagnostic = error.orig if isinstance(error, DBAPIError) else None
+ args = getattr(diagnostic, "args", ())
+ if args and isinstance(args[0], int):
+ # MySQL drivers may expose SQLSTATE as well as their decisive errno.
+ if args[0] in (1213, 1305):
+ return True
+ elif (
+ getattr(diagnostic, "pgcode", None) or getattr(diagnostic, "sqlstate", None)
+ ) == "3B001":
+ return True
+ for linked in (error.__cause__, error.__context__):
+ if linked is not None:
+ pending.append(linked)
+ return False
+
+
#: MySQL/MariaDB errnos for a foreign key violation: adding a child row whose
#: parent is missing (1452, and 1216 from older servers).
_MYSQL_FOREIGN_KEY_VIOLATION: tuple[int, ...] = (1452, 1216)
@@ -168,17 +204,18 @@ def is_missing_table_error(exc: DBAPIError) -> bool:
"""
orig = getattr(exc, "orig", None)
+ # MySQL/MariaDB drivers can also expose SQLSTATE; their numeric errno
+ # takes precedence over the PostgreSQL SQLSTATE vocabulary.
+ args = getattr(orig, "args", ())
+ if args and isinstance(args[0], int):
+ return args[0] == _MYSQL_NO_SUCH_TABLE
+
# PostgreSQL via psycopg2. (psycopg 3 spells it ``sqlstate``; checked
# too so a driver swap doesn't silently widen the swallow.)
pgcode = getattr(orig, "pgcode", None) or getattr(orig, "sqlstate", None)
if pgcode is not None:
return pgcode == _PG_UNDEFINED_TABLE
- # MySQL/MariaDB drivers put the numeric errno first in args.
- args = getattr(orig, "args", ())
- if args and isinstance(args[0], int):
- return args[0] == _MYSQL_NO_SUCH_TABLE
-
# SQLite has no error codes on OperationalError; the message is the
# documented, stable signal.
return "no such table" in str(orig if orig is not None else exc).lower()
diff --git a/superset/versioning/factory.py b/superset/versioning/factory.py
index 2e03b8244e33..231c9d982e23 100644
--- a/superset/versioning/factory.py
+++ b/superset/versioning/factory.py
@@ -148,6 +148,32 @@ def create_class(self, manager: Any) -> Any:
return cls
+def transaction_actor_args() -> dict[str, Any]:
+ """Return validated request actor attribution for content and lifecycle writes."""
+ # pylint: disable=import-outside-toplevel
+ from flask import has_request_context, request
+
+ from superset.utils.core import get_user_id
+
+ user_id = get_user_id()
+ # get_user_id() returns an int in a real request, or None for a
+ # context-less save (CLI, Celery, import/export). Guard against any
+ # non-int so a bogus value never reaches the integer
+ # ``version_transaction.user_id`` column — notably a mocked ``g`` in
+ # tests, where ``g.user.id`` is a Mock rather than None and would
+ # otherwise blow up the flush with a SQL bind error.
+ if not isinstance(user_id, int):
+ return {}
+
+ remote_addr: str | None
+ try:
+ remote_addr = request.remote_addr if has_request_context() else None
+ except RuntimeError:
+ remote_addr = None
+
+ return {"user_id": user_id, "remote_addr": remote_addr}
+
+
class VersioningFlaskPlugin(FlaskPlugin):
"""FlaskPlugin subclass that uses Superset's :func:`get_user_id` (which
reads ``g.user``) instead of Flask-Login's ``current_user``. Superset's
@@ -159,28 +185,7 @@ class VersioningFlaskPlugin(FlaskPlugin):
"""
def transaction_args(self, uow: Any, session: Any) -> dict[str, Any]:
- # pylint: disable=import-outside-toplevel
- from flask import has_request_context, request
-
- from superset.utils.core import get_user_id
-
- user_id = get_user_id()
- # get_user_id() returns an int in a real request, or None for a
- # context-less save (CLI, Celery, import/export). Guard against any
- # non-int so a bogus value never reaches the integer
- # ``version_transaction.user_id`` column — notably a mocked ``g`` in
- # tests, where ``g.user.id`` is a Mock rather than None and would
- # otherwise blow up the flush with a SQL bind error.
- if not isinstance(user_id, int):
- return {}
-
- remote_addr: str | None
- try:
- remote_addr = request.remote_addr if has_request_context() else None
- except RuntimeError:
- remote_addr = None
-
- return {"user_id": user_id, "remote_addr": remote_addr}
+ return transaction_actor_args()
class SkipUnmodifiedPlugin(Plugin):
diff --git a/superset/versioning/lifecycle.py b/superset/versioning/lifecycle.py
new file mode 100644
index 000000000000..855ecb89e0da
--- /dev/null
+++ b/superset/versioning/lifecycle.py
@@ -0,0 +1,339 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""Capture net chart archives without creating restorable content versions."""
+
+from __future__ import annotations
+
+import logging
+from dataclasses import dataclass
+from time import perf_counter
+from typing import Any
+from uuid import UUID, uuid4
+
+import sqlalchemy as sa
+from sqlalchemy.engine import Connection, NestedTransaction, Transaction
+from sqlalchemy.exc import DBAPIError, SQLAlchemyError
+from sqlalchemy.orm import Session
+
+from superset.utils.dates import naive_utcnow
+from superset.versioning.changes.table import version_changes_table
+from superset.versioning.db_errors import (
+ is_lost_transaction_error,
+ is_missing_table_error,
+)
+from superset.versioning.factory import transaction_actor_args
+from superset.versioning.lifecycle_table import version_chart_archive_scope_table
+from superset.versioning.metrics import emit_capture_timing, incr_capture_error
+
+CHART_ARCHIVE_KIND = "__archive__"
+_BATCH_SIZE = 500
+logger = logging.getLogger(__name__)
+
+
+class LifecycleCaptureFatalError(SQLAlchemyError):
+ """Optional capture cannot prove the caller's transaction survived."""
+
+
+def _check_transaction(connection: Connection, outer_transaction: Transaction) -> None:
+ """Reject invalidated, replaced, or ended application transactions."""
+ if (
+ connection.invalidated
+ or connection.closed
+ or not outer_transaction.is_active
+ or connection.get_transaction() is not outer_transaction
+ ):
+ raise LifecycleCaptureFatalError(
+ "Archive capture lost its application transaction"
+ )
+
+
+def begin_capture_savepoint(
+ connection: Connection, outer_transaction: Transaction
+) -> NestedTransaction:
+ """Establish an isolation boundary, propagating uncertain transaction state."""
+ _check_transaction(connection, outer_transaction)
+ try:
+ return connection.begin_nested()
+ except Exception as error:
+ raise LifecycleCaptureFatalError(
+ "Could not establish archive capture savepoint"
+ ) from error
+
+
+def release_capture_savepoint(
+ connection: Connection, savepoint: NestedTransaction, outer_transaction: Transaction
+) -> None:
+ """Release successful work without swallowing lost savepoints."""
+ _check_transaction(connection, outer_transaction)
+ try:
+ # This connection savepoint belongs to optional metadata, not the ORM unit.
+ savepoint.commit() # pylint: disable=consider-using-transaction
+ except Exception as error:
+ raise LifecycleCaptureFatalError(
+ "Could not release archive capture savepoint"
+ ) from error
+ _check_transaction(connection, outer_transaction)
+
+
+def rollback_capture_savepoint(
+ connection: Connection,
+ savepoint: NestedTransaction,
+ outer_transaction: Transaction,
+ error: Exception,
+) -> None:
+ """Prove a failed optional statement was isolated before allowing more SQL."""
+ if isinstance(error, LifecycleCaptureFatalError):
+ raise error
+ if connection.invalidated or getattr(error, "connection_invalidated", False):
+ raise LifecycleCaptureFatalError(
+ "Archive capture connection was invalidated"
+ ) from error
+ if not savepoint.is_active:
+ raise LifecycleCaptureFatalError(
+ "Archive capture savepoint is no longer active"
+ ) from error
+ try:
+ # Explicit recovery preserves both the statement and rollback failures.
+ savepoint.rollback() # pylint: disable=consider-using-transaction
+ except Exception as rollback_error:
+ # Keep both the original failure and failed recovery in the exception chain.
+ try:
+ raise rollback_error from error
+ except Exception as chained_error:
+ raise LifecycleCaptureFatalError(
+ "Could not roll back archive capture savepoint"
+ ) from chained_error
+ _check_transaction(connection, outer_transaction)
+ if is_lost_transaction_error(error):
+ raise LifecycleCaptureFatalError(
+ "Database reported lost archive capture transaction state"
+ ) from error
+
+
+@dataclass(frozen=True)
+class ChartArchive:
+ """The final identity and name of one observed active-to-archived transition."""
+
+ chart_id: int
+ chart_uuid: UUID
+ chart_name: str | None
+
+
+def collect_chart_archives(
+ session: Session, initial_states: dict[tuple[str, int], tuple[Any, dict[str, Any]]]
+) -> list[ChartArchive]:
+ """Retain persisted net transitions, including an active insert flushed earlier."""
+ archives = []
+ for (kind, entity_id), (obj, before) in initial_states.items():
+ if (
+ kind != "chart"
+ or "deleted_at" not in before
+ or before["deleted_at"] is not None
+ ):
+ continue
+ state = sa.inspect(obj)
+ if (
+ not state.persistent
+ or state.session is not session
+ or obj.deleted_at is None
+ or obj.uuid is None
+ ):
+ continue
+ archives.append(ChartArchive(entity_id, UUID(str(obj.uuid)), obj.slice_name))
+ return archives
+
+
+def _memberships(
+ connection: Connection, chart_ids: list[int]
+) -> dict[int, list[tuple[int, UUID]]]:
+ """Read post-flush membership with Core, including archived dashboards."""
+ from superset.models.dashboard import Dashboard, dashboard_slices
+
+ dashboard = Dashboard.__table__
+ memberships: dict[int, list[tuple[int, UUID]]] = {
+ chart_id: [] for chart_id in chart_ids
+ }
+ result = connection.execute(
+ sa.select(dashboard_slices.c.slice_id, dashboard.c.id, dashboard.c.uuid)
+ .select_from(
+ dashboard_slices.join(
+ dashboard, dashboard_slices.c.dashboard_id == dashboard.c.id
+ )
+ )
+ .where(dashboard_slices.c.slice_id.in_(chart_ids))
+ .execution_options(stream_results=True)
+ )
+ try:
+ for row in result:
+ if row.uuid is not None:
+ memberships[row.slice_id].append((row.id, row.uuid))
+ finally:
+ result.close()
+ return memberships
+
+
+def _write_archive(
+ connection: Connection,
+ transaction_id: int,
+ archive: ChartArchive,
+ memberships: list[tuple[int, UUID]],
+) -> int:
+ """Write one canonical event and every destination in bounded insert batches."""
+ connection.execute(
+ version_changes_table.insert().values(
+ transaction_id=transaction_id,
+ entity_kind="chart",
+ entity_id=archive.chart_id,
+ sequence=0,
+ kind=CHART_ARCHIVE_KIND,
+ operation="announce",
+ path=["deleted_at"],
+ from_value=None,
+ to_value={
+ "entity_uuid": str(archive.chart_uuid),
+ "entity_name": archive.chart_name,
+ },
+ )
+ )
+ for offset in range(0, len(memberships), _BATCH_SIZE):
+ connection.execute(
+ version_chart_archive_scope_table.insert(),
+ [
+ {
+ "id": uuid4(),
+ "transaction_id": transaction_id,
+ "chart_id": archive.chart_id,
+ "chart_uuid": archive.chart_uuid,
+ "dashboard_id": dashboard_id,
+ "dashboard_uuid": dashboard_uuid,
+ }
+ for dashboard_id, dashboard_uuid in memberships[
+ offset : offset + _BATCH_SIZE
+ ]
+ ],
+ )
+ return len(memberships)
+
+
+def _emit_counts(events: int, scopes: int) -> None:
+ """Report captured volumes without entity identifiers."""
+ try:
+ from superset.extensions import stats_logger_manager
+
+ stats_logger_manager.instance.gauge(
+ "superset.versioning.capture.lifecycle.events", events
+ )
+ stats_logger_manager.instance.gauge(
+ "superset.versioning.capture.lifecycle.scopes", scopes
+ )
+ except Exception: # pylint: disable=broad-except
+ logger.warning("versioning: failed to emit lifecycle counts")
+
+
+def _capture_chunk(
+ connection: Connection,
+ outer_transaction: Transaction,
+ transaction_id: int,
+ chunk: list[ChartArchive],
+) -> tuple[int, int]:
+ """Isolate a membership query and each complete chart's metadata."""
+ event_count = scope_count = 0
+ membership_savepoint = begin_capture_savepoint(connection, outer_transaction)
+ try:
+ memberships = _memberships(connection, [archive.chart_id for archive in chunk])
+ except Exception as error: # pylint: disable=broad-except
+ rollback_capture_savepoint(
+ connection, membership_savepoint, outer_transaction, error
+ )
+ logger.exception("versioning: archive membership capture failed")
+ incr_capture_error("lifecycle_membership")
+ return 0, 0
+ release_capture_savepoint(connection, membership_savepoint, outer_transaction)
+ for archive in chunk:
+ chart_savepoint = begin_capture_savepoint(connection, outer_transaction)
+ try:
+ scopes = _write_archive(
+ connection,
+ transaction_id,
+ archive,
+ memberships[archive.chart_id],
+ )
+ except Exception as error: # pylint: disable=broad-except
+ rollback_capture_savepoint(
+ connection, chart_savepoint, outer_transaction, error
+ )
+ if not isinstance(error, DBAPIError) or not is_missing_table_error(error):
+ logger.exception("versioning: chart archive capture failed")
+ incr_capture_error("lifecycle_chart")
+ continue
+ release_capture_savepoint(connection, chart_savepoint, outer_transaction)
+ event_count += 1
+ scope_count += scopes
+ return event_count, scope_count
+
+
+def capture_chart_archives(session: Session, archives: list[ChartArchive]) -> None:
+ """Capture optional metadata atomically per chart on the caller's connection."""
+ if not archives:
+ return
+ from sqlalchemy_continuum import versioning_manager
+
+ start = perf_counter()
+ connection = session.connection()
+ outer_transaction = connection.get_transaction()
+ if outer_transaction is None:
+ raise LifecycleCaptureFatalError(
+ "Archive capture requires an application transaction"
+ )
+ outer_savepoint = begin_capture_savepoint(connection, outer_transaction)
+ event_count = scope_count = 0
+ try:
+ transaction_table = versioning_manager.transaction_cls.__table__
+ inserted = connection.execute(
+ transaction_table.insert().values(
+ issued_at=naive_utcnow(), action_kind=None, **transaction_actor_args()
+ )
+ )
+ transaction_id = inserted.inserted_primary_key[0]
+ for offset in range(0, len(archives), _BATCH_SIZE):
+ chunk = archives[offset : offset + _BATCH_SIZE]
+ events, scopes = _capture_chunk(
+ connection, outer_transaction, transaction_id, chunk
+ )
+ event_count += events
+ scope_count += scopes
+ if event_count:
+ release_capture_savepoint(connection, outer_savepoint, outer_transaction)
+ else:
+ rollback_capture_savepoint(
+ connection,
+ outer_savepoint,
+ outer_transaction,
+ RuntimeError("No archive events survived"),
+ )
+ except LifecycleCaptureFatalError:
+ raise
+ except Exception as error: # pylint: disable=broad-except
+ rollback_capture_savepoint(
+ connection, outer_savepoint, outer_transaction, error
+ )
+ if not isinstance(error, DBAPIError) or not is_missing_table_error(error):
+ logger.exception("versioning: archive transaction capture failed")
+ incr_capture_error("lifecycle")
+ finally:
+ emit_capture_timing("lifecycle", (perf_counter() - start) * 1000)
+ _emit_counts(event_count, scope_count)
diff --git a/superset/versioning/lifecycle_table.py b/superset/versioning/lifecycle_table.py
new file mode 100644
index 000000000000..1536752cec8f
--- /dev/null
+++ b/superset/versioning/lifecycle_table.py
@@ -0,0 +1,48 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""Immutable archive-time dashboard membership, registered on shared metadata."""
+
+import sqlalchemy as sa
+from flask_appbuilder import Model
+from sqlalchemy_utils import UUIDType
+
+version_chart_archive_scope_table = sa.Table(
+ "version_chart_archive_scope",
+ Model.metadata, # pylint: disable=no-member
+ sa.Column("id", UUIDType(binary=True), primary_key=True),
+ # The migration owns the FK to Continuum's dynamically registered table.
+ sa.Column("transaction_id", sa.BigInteger, nullable=False),
+ sa.Column("chart_id", sa.Integer, nullable=False),
+ sa.Column("chart_uuid", UUIDType(binary=True), nullable=False),
+ sa.Column("dashboard_id", sa.Integer, nullable=False),
+ sa.Column("dashboard_uuid", UUIDType(binary=True), nullable=False),
+ sa.UniqueConstraint(
+ "transaction_id",
+ "chart_uuid",
+ "dashboard_id",
+ "dashboard_uuid",
+ name="uq_chart_archive_scope_identity",
+ ),
+ sa.Index(
+ "ix_chart_archive_scope_dashboard",
+ "dashboard_id",
+ "dashboard_uuid",
+ "transaction_id",
+ ),
+ sa.Index("ix_chart_archive_scope_chart", "chart_id", "transaction_id"),
+ extend_existing=True,
+)
diff --git a/superset/versioning/schemas.py b/superset/versioning/schemas.py
index 074800bea686..0fc38b9e642a 100644
--- a/superset/versioning/schemas.py
+++ b/superset/versioning/schemas.py
@@ -27,6 +27,7 @@
from superset.versioning.changes import ACTION_KINDS
from superset.versioning.creation_kinds import CREATION_KINDS, CREATION_RECORD_KIND
+from superset.versioning.lifecycle import CHART_ARCHIVE_KIND
class VersionChangedBySchema(Schema):
@@ -206,6 +207,7 @@ class VersionListResponseSchema(Schema):
# ``version_uuid`` / ``version_number``.
"__meta__",
CREATION_RECORD_KIND,
+ CHART_ARCHIVE_KIND,
)
#: Allowed values for ``ActivityRecordSchema.operation`` — the per-record
@@ -349,8 +351,9 @@ class ActivityRecordSchema(Schema):
metadata={
"description": (
"Name of the source entity *at the time of the change* — "
- "denormalized from the validity-strategy shadow row. "
- "Survives entity rename / delete."
+ "denormalized from the validity-strategy shadow row, or from "
+ "the capture-time payload for ``__archive__`` records. "
+ "Preserved across renames; redacted for deleted related entities."
)
},
)
@@ -405,7 +408,8 @@ class ActivityRecordSchema(Schema):
"description": (
"Content category — what kind of thing changed. "
"``field`` is the fallback for scalar changes without a "
- "more specific category. Per-record."
+ "more specific category. Per-record. ``__archive__`` announces a "
+ "chart archive in related dashboard activity only."
)
},
)
@@ -454,13 +458,20 @@ class ActivityRecordSchema(Schema):
)
to_value = fields.Raw(
allow_none=True,
- metadata={"description": "New value; ``null`` = removed."},
+ metadata={
+ "description": (
+ "New value; ``null`` = removed. For ``__archive__``, an object "
+ "with the archived chart's ``entity_uuid`` and capture-time "
+ "``entity_name``; null when related detail is redacted."
+ )
+ },
)
summary = fields.String(
metadata={
"description": (
'Synthesized headline for ``source: "related"`` records — '
- 'e.g., ``"Dataset updated: Sales Transactions"``. '
+ 'e.g., ``"Dataset updated: Sales Transactions"`` or '
+ '``"Chart archived: Sales"``. '
'Empty string for ``source: "self"`` records, except '
"``__meta__`` self records (e.g. restore announcements), "
"which carry their own headline."
diff --git a/tests/integration_tests/deletion_retention/purge_performance_tests.py b/tests/integration_tests/deletion_retention/purge_performance_tests.py
index fdf410a1664f..2b5d6348b8ee 100644
--- a/tests/integration_tests/deletion_retention/purge_performance_tests.py
+++ b/tests/integration_tests/deletion_retention/purge_performance_tests.py
@@ -46,9 +46,12 @@
from ._base import DeletionRetentionTestBase
-CHART_PURGE_BASELINE_STATEMENTS: int = 35
-DASHBOARD_PURGE_BASELINE_STATEMENTS: int = 36
-DATASET_PURGE_BASELINE_STATEMENTS: int = 43
+# Archive scopes require an existence probe, scoped candidate collection/deletion,
+# and an extra orphan-reference check. Change-only transactions also contribute
+# candidates. Both shadow endpoints are collected in one SELECT per table.
+CHART_PURGE_BASELINE_STATEMENTS: int = 42
+DASHBOARD_PURGE_BASELINE_STATEMENTS: int = 41
+DATASET_PURGE_BASELINE_STATEMENTS: int = 51
MAX_STATEMENT_REGRESSION: float = 0.10
WARMUP_RUNS: int = 5
MEASURED_RUNS: int = 20
diff --git a/tests/integration_tests/versioning/chart_archive_activity_tests.py b/tests/integration_tests/versioning/chart_archive_activity_tests.py
new file mode 100644
index 000000000000..899f4c8ee886
--- /dev/null
+++ b/tests/integration_tests/versioning/chart_archive_activity_tests.py
@@ -0,0 +1,431 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""Chart lifecycle capture through API commands and dashboard activity reads."""
+
+from __future__ import annotations
+
+from collections.abc import Iterator
+from datetime import datetime, timedelta, timezone
+from typing import Any
+from unittest.mock import patch
+from uuid import uuid4
+
+import pytest
+import sqlalchemy as sa
+from sqlalchemy_continuum import versioning_manager
+
+from superset import db, security_manager
+from superset.connectors.sqla.models import SqlaTable
+from superset.constants import SKIP_VISIBILITY_FILTER_CLASSES
+from superset.models.core import Database
+from superset.models.dashboard import Dashboard
+from superset.models.slice import Slice
+from superset.reports.models import (
+ ReportCreationMethod,
+ ReportSchedule,
+ ReportScheduleType,
+)
+from superset.subjects.utils import get_user_subject
+from superset.utils import json
+from superset.utils.core import override_user
+from superset.versioning.changes import version_changes_table
+from superset.versioning.lifecycle import CHART_ARCHIVE_KIND
+from tests.integration_tests.base_tests import SupersetTestCase
+from tests.integration_tests.conftest import with_feature_flags
+from tests.integration_tests.constants import ADMIN_USERNAME, GAMMA_USERNAME
+
+
+class TestChartArchiveActivity(SupersetTestCase):
+ """Use isolated assets so permission and lifecycle assertions need no examples."""
+
+ @pytest.fixture(autouse=True)
+ def assets(self, app_context: Any) -> Iterator[None]:
+ """Create two charts sharing a dashboard and clean up archived rows too."""
+ admin = security_manager.find_user(ADMIN_USERNAME)
+ editor = get_user_subject(admin.id)
+ database = Database(
+ database_name=f"archive-{uuid4()}", sqlalchemy_uri="sqlite://"
+ )
+ dataset = SqlaTable(
+ table_name="archive_activity", database=database, editors=[editor]
+ )
+ db.session.add_all([database, dataset])
+ db.session.flush()
+ self.charts = [
+ Slice(
+ slice_name=f"Archive chart {index}",
+ uuid=uuid4(),
+ datasource_id=dataset.id,
+ datasource_type="table",
+ viz_type="table",
+ params="{}",
+ editors=[editor],
+ )
+ for index in range(2)
+ ]
+ self.dashboard = Dashboard(
+ dashboard_title="Archive dashboard",
+ uuid=uuid4(),
+ slices=self.charts,
+ editors=[editor],
+ )
+ db.session.add(self.dashboard)
+ db.session.commit()
+ self.dataset = dataset
+ try:
+ yield
+ finally:
+ db.session.rollback()
+ cleanup_targets: list[
+ tuple[type[Dashboard] | type[Slice] | type[SqlaTable], list[int]]
+ ] = [
+ (Dashboard, [self.dashboard.id]),
+ (Slice, [chart.id for chart in self.charts]),
+ (SqlaTable, [dataset.id]),
+ ]
+ for model, ids in cleanup_targets:
+ for entity in (
+ db.session.query(model)
+ .execution_options(**{SKIP_VISIBILITY_FILTER_CLASSES: {model}})
+ .filter(model.id.in_(ids))
+ ):
+ db.session.delete(entity)
+ db.session.flush()
+ db.session.delete(database)
+ db.session.commit()
+
+ def activity(self, **params: Any) -> list[dict[str, Any]]:
+ """Read the actual dashboard DTO and assert the endpoint succeeds."""
+ response = self.client.get(
+ f"/api/v1/dashboard/{self.dashboard.uuid}/activity/", query_string=params
+ )
+ assert response.status_code == 200, response.data
+ return json.loads(response.data)["result"]
+
+ def archives(self, **params: Any) -> list[dict[str, Any]]:
+ """Select archive announcements from the dashboard stream."""
+ return [
+ row for row in self.activity(**params) if row["kind"] == CHART_ARCHIVE_KIND
+ ]
+
+ @with_feature_flags(SOFT_DELETE=True, VERSION_HISTORY=True)
+ def test_single_delete_has_archive_timestamp_and_no_content_version(self) -> None:
+ """Single DELETE produces a related announcement with the capturing actor."""
+ self.login(ADMIN_USERNAME)
+ before = datetime.now(timezone.utc).replace(tzinfo=None) - timedelta(seconds=1)
+ response = self.client.delete(f"/api/v1/chart/{self.charts[0].id}")
+ assert response.status_code == 200, response.data
+ rows = self.archives()
+ assert len(rows) == 1
+ row = rows[0]
+ issued_at = datetime.fromisoformat(
+ row["issued_at"].replace("Z", "+00:00")
+ ).replace(tzinfo=None)
+ # MySQL DATETIME can round the capture timestamp to the next second.
+ after = datetime.now(timezone.utc).replace(tzinfo=None) + timedelta(seconds=1)
+ assert before <= issued_at <= after
+ assert row["summary"] == "Chart archived: Archive chart 0"
+ assert row["source"] == "related"
+ assert row["version_uuid"] is None
+ assert row["first_tracked_save"] is False
+ assert row["entity_deletion_state"] == "soft_deleted"
+ assert row["changed_by"]["id"] == self.get_user(ADMIN_USERNAME).id
+ assert self.archives(include="self") == []
+ assert len(self.archives(include="related", q="archived", page_size=1)) == 1
+ assert self.archives(q="not-the-chart") == []
+
+ @with_feature_flags(SOFT_DELETE=True, VERSION_HISTORY=True)
+ def test_bulk_delete_keeps_one_row_per_chart(self) -> None:
+ """Bulk DELETE uses one lifecycle transaction and distinct chart records."""
+ self.login(ADMIN_USERNAME)
+ response = self.client.delete(
+ "/api/v1/chart/",
+ query_string={"q": json.dumps([chart.id for chart in self.charts])},
+ )
+ assert response.status_code == 200, response.data
+ rows = self.archives()
+ assert len(rows) == 2
+ assert len({row["transaction_id"] for row in rows}) == 1
+ assert {row["entity_name"] for row in rows} == {
+ chart.slice_name for chart in self.charts
+ }
+
+ @with_feature_flags(SOFT_DELETE=True, VERSION_HISTORY=True)
+ def test_direct_soft_delete_and_recovery_keep_chart_history_content_only(
+ self,
+ ) -> None:
+ """Folder-style ORM deletion and recovery preserve the existing self probe."""
+ self.login(ADMIN_USERNAME)
+ chart = self.charts[0]
+ for name in ["First save", "Second save"]:
+ chart.slice_name = name
+ db.session.commit()
+ for _ in range(2):
+ chart.soft_delete()
+ db.session.commit()
+ chart.restore()
+ db.session.commit()
+ rows = self.archives()
+ assert len(rows) == 2
+ assert all(row["entity_deletion_state"] is None for row in rows)
+ response = self.client.get(
+ f"/api/v1/chart/{chart.uuid}/activity/",
+ query_string={"include": "self", "page_size": 1},
+ )
+ assert response.status_code == 200
+ current = json.loads(response.data)["result"][0]
+ assert current["kind"] != CHART_ARCHIVE_KIND
+ assert current["version_uuid"] is not None
+ assert current["to_value"] == "Second save"
+
+ @with_feature_flags(SOFT_DELETE=True, VERSION_HISTORY=True)
+ def test_capture_gap_membership_is_taken_at_archive(self) -> None:
+ """Capture-disabled detach excludes stale windows; a later attach includes."""
+ self.login(ADMIN_USERNAME)
+ chart = self.charts[0]
+ with patch.dict(versioning_manager.options, versioning=False):
+ self.dashboard.slices.remove(chart)
+ db.session.commit()
+ chart.soft_delete()
+ db.session.commit()
+ assert self.archives() == []
+ chart.restore()
+ db.session.commit()
+ with patch.dict(versioning_manager.options, versioning=False):
+ self.dashboard.slices.append(chart)
+ db.session.commit()
+ chart.soft_delete()
+ db.session.commit()
+ assert len(self.archives()) == 1
+
+ @with_feature_flags(SOFT_DELETE=True, VERSION_HISTORY=True)
+ def test_dataset_read_grant_shows_archived_chart_without_actor_or_detail(
+ self,
+ ) -> None:
+ """Dashboard editorship and dataset read access grant presence, not detail."""
+ gamma = security_manager.find_user(GAMMA_USERNAME)
+ self.dashboard.editors.append(get_user_subject(gamma.id))
+ role = security_manager.find_role("Gamma")
+ permission = security_manager.add_permission_view_menu(
+ "datasource_access", self.dataset.perm
+ )
+ role.permissions.append(permission)
+ db.session.commit()
+ try:
+ with override_user(security_manager.find_user(ADMIN_USERNAME)):
+ self.charts[0].soft_delete()
+ db.session.commit()
+ self.login(GAMMA_USERNAME)
+ rows = self.archives()
+ assert len(rows) == 1
+ assert rows[0]["entity_name"] == "Archive chart 0"
+ assert rows[0]["changed_by"] is None
+ assert rows[0]["to_value"] is None
+ assert rows[0]["path"] is None
+ security_manager.del_permission_role(role, permission)
+ db.session.commit()
+ assert self.archives() == []
+ finally:
+ security_manager.del_permission_role(role, permission)
+ db.session.commit()
+
+ @with_feature_flags(SOFT_DELETE=True, VERSION_HISTORY=True)
+ def test_rolled_back_archive_leaves_no_activity(self) -> None:
+ """An unsuccessful outer transaction cannot leave a committed announcement."""
+ self.login(ADMIN_USERNAME)
+ self.charts[0].soft_delete()
+ db.session.flush()
+ db.session.rollback()
+ assert self.archives() == []
+ assert (
+ db.session.connection()
+ .execute(
+ sa.select(sa.func.count())
+ .select_from(version_changes_table)
+ .where(version_changes_table.c.kind == CHART_ARCHIVE_KIND)
+ )
+ .scalar()
+ == 0
+ )
+
+ @with_feature_flags(SOFT_DELETE=True, VERSION_HISTORY=True)
+ def test_report_blocked_delete_emits_no_archive(self) -> None:
+ """A report validation failure never reaches archive capture."""
+ report = ReportSchedule(
+ type=ReportScheduleType.REPORT,
+ name=f"Archive blocker {uuid4()}",
+ crontab="0 9 * * *",
+ chart=self.charts[0],
+ creation_method=ReportCreationMethod.ALERTS_REPORTS,
+ )
+ db.session.add(report)
+ db.session.commit()
+ try:
+ self.login(ADMIN_USERNAME)
+ response = self.client.delete(f"/api/v1/chart/{self.charts[0].id}")
+ assert response.status_code == 422
+ assert self.archives() == []
+ finally:
+ db.session.delete(report)
+ db.session.commit()
+
+ @with_feature_flags(SOFT_DELETE=True, VERSION_HISTORY=True)
+ def test_dashboard_read_without_editorship_cannot_read_archive_activity(
+ self,
+ ) -> None:
+ """Version history retains the path editorship boundary."""
+ self.charts[0].soft_delete()
+ db.session.commit()
+ self.login(GAMMA_USERNAME)
+ response = self.client.get(f"/api/v1/dashboard/{self.dashboard.uuid}/activity/")
+ assert response.status_code == 403
+
+ @with_feature_flags(SOFT_DELETE=True, VERSION_HISTORY=True)
+ def test_archived_dataset_presence_retains_read_and_editor_policy(self) -> None:
+ """Archived related datasets remain read-gated with conservative detail."""
+ gamma = security_manager.find_user(GAMMA_USERNAME)
+ self.dashboard.editors.append(get_user_subject(gamma.id))
+ self.dataset.description = "Dataset description before archive"
+ db.session.commit()
+ self.dataset.soft_delete()
+ db.session.commit()
+ self.login(GAMMA_USERNAME)
+ assert not [row for row in self.activity() if row["entity_kind"] == "dataset"]
+ role = security_manager.find_role("Gamma")
+ permission = security_manager.add_permission_view_menu(
+ "datasource_access", self.dataset.perm
+ )
+ role.permissions.append(permission)
+ db.session.commit()
+ try:
+ rows = [row for row in self.activity() if row["entity_kind"] == "dataset"]
+ assert rows
+ assert all(row["entity_deletion_state"] == "soft_deleted" for row in rows)
+ assert all(row["entity_name"] == self.dataset.table_name for row in rows)
+ assert all(
+ row["changed_by"] is None and row["to_value"] is None for row in rows
+ )
+ security_manager.del_permission_role(role, permission)
+ self.dataset.editors.append(get_user_subject(gamma.id))
+ db.session.commit()
+ rows = [row for row in self.activity() if row["entity_kind"] == "dataset"]
+ assert rows
+ assert all(
+ row["changed_by"] is None and row["to_value"] is None for row in rows
+ )
+ finally:
+ security_manager.del_permission_role(role, permission)
+ db.session.commit()
+
+ @with_feature_flags(SOFT_DELETE=True, VERSION_HISTORY=True)
+ def test_archived_chart_editor_can_read_presence_without_dataset_grant(
+ self,
+ ) -> None:
+ """Archived chart editors retain presence but no archived raw detail."""
+ gamma = security_manager.find_user(GAMMA_USERNAME)
+ editor = get_user_subject(gamma.id)
+ self.dashboard.editors.append(editor)
+ self.charts[0].editors.append(editor)
+ db.session.commit()
+ self.charts[0].soft_delete()
+ db.session.commit()
+ self.login(GAMMA_USERNAME)
+ rows = self.archives()
+ assert len(rows) == 1
+ assert rows[0]["entity_name"] == "Archive chart 0"
+ assert rows[0]["changed_by"] is None
+ assert rows[0]["to_value"] is None
+
+ @with_feature_flags(SOFT_DELETE=True, VERSION_HISTORY=True, EMBEDDED_SUPERSET=True)
+ def test_guest_cannot_read_archive_activity_even_with_role_editorship(self) -> None:
+ """Guest tokens never gain history through an operator-granted editor role."""
+ from flask import current_app
+
+ from superset.security.guest_token import GuestTokenResourceType
+ from superset.subjects.utils import subjects_from_roles
+
+ guest_role = security_manager.find_role(current_app.config["GUEST_ROLE_NAME"])
+ self.dashboard.editors.extend(subjects_from_roles([guest_role]))
+ self.charts[0].soft_delete()
+ db.session.commit()
+ token = security_manager.create_guest_access_token(
+ user={"username": "archive_guest"},
+ resources=[
+ {
+ "type": GuestTokenResourceType.DASHBOARD,
+ "id": str(self.dashboard.uuid),
+ }
+ ],
+ rls=[],
+ )
+ response = self.client.get(
+ f"/api/v1/dashboard/{self.dashboard.uuid}/activity/",
+ headers={current_app.config["GUEST_TOKEN_HEADER_NAME"]: token},
+ )
+ assert response.status_code == 403
+
+ @with_feature_flags(SOFT_DELETE=True, VERSION_HISTORY=True)
+ def test_untracked_dashboard_shows_archive_without_original_version(self) -> None:
+ """Archive membership can exist without inventing a dashboard baseline."""
+ from sqlalchemy_continuum import version_class
+
+ self.login(ADMIN_USERNAME)
+ with patch.dict(versioning_manager.options, versioning=False):
+ dashboard = Dashboard(
+ dashboard_title="Untracked archive dashboard",
+ uuid=uuid4(),
+ slices=[self.charts[0]],
+ editors=[get_user_subject(self.get_user(ADMIN_USERNAME).id)],
+ )
+ db.session.add(dashboard)
+ db.session.commit()
+ try:
+ self.charts[0].soft_delete()
+ db.session.commit()
+ response = self.client.get(f"/api/v1/dashboard/{dashboard.uuid}/activity/")
+ assert response.status_code == 200
+ records = json.loads(response.data)["result"]
+ assert [row["kind"] for row in records] == [CHART_ARCHIVE_KIND]
+ assert records[0]["version_uuid"] is None
+ shadow = version_class(Dashboard)
+ assert (
+ db.session.query(shadow).filter(shadow.id == dashboard.id).count() == 0
+ )
+ finally:
+ db.session.delete(dashboard)
+ db.session.commit()
+
+ @with_feature_flags(SOFT_DELETE=True, VERSION_HISTORY=True)
+ def test_fatal_capture_failure_rolls_back_delete_with_public_error(self) -> None:
+ """Fatal capture rejects DELETE without leaking internal error details."""
+ from superset.versioning.lifecycle import LifecycleCaptureFatalError
+
+ self.login(ADMIN_USERNAME)
+ chart_id = self.charts[0].id
+ private_error = "private driver failure during archive capture"
+ with patch(
+ "superset.versioning.lifecycle._write_archive",
+ side_effect=LifecycleCaptureFatalError(private_error),
+ ):
+ response = self.client.delete(f"/api/v1/chart/{chart_id}")
+ assert response.status_code == 422
+ assert private_error not in response.get_data(as_text=True)
+ assert self.archives() == []
+ db.session.expire_all()
+ persisted = db.session.get(Slice, chart_id)
+ assert persisted is not None
+ assert persisted.deleted_at is None
diff --git a/tests/integration_tests/versioning/conftest.py b/tests/integration_tests/versioning/conftest.py
index f4a5d02c983f..12fea2af6e01 100644
--- a/tests/integration_tests/versioning/conftest.py
+++ b/tests/integration_tests/versioning/conftest.py
@@ -37,6 +37,7 @@
"tables_version",
"table_columns_version",
"sql_metrics_version",
+ "version_chart_archive_scope",
"version_changes",
"version_transaction",
)
@@ -55,7 +56,8 @@ def _assert_table_list_covers_schema() -> None:
# Continuum shadow tables are ``_version``; exclude
# Alembic's own ``alembic_version`` bookkeeping table, which shares
# the suffix but is not a shadow table.
- if name.endswith("_version") and name != "alembic_version"
+ if (name.endswith("_version") and name != "alembic_version")
+ or name == "version_chart_archive_scope"
}
missing = shadow_tables - known
assert not missing, (
diff --git a/tests/testcontainers/versioning/__init__.py b/tests/testcontainers/versioning/__init__.py
new file mode 100644
index 000000000000..13a83393a912
--- /dev/null
+++ b/tests/testcontainers/versioning/__init__.py
@@ -0,0 +1,16 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
diff --git a/tests/testcontainers/versioning/test_chart_archive.py b/tests/testcontainers/versioning/test_chart_archive.py
new file mode 100644
index 000000000000..9c5c935f4646
--- /dev/null
+++ b/tests/testcontainers/versioning/test_chart_archive.py
@@ -0,0 +1,730 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""Archive transaction boundaries against disposable PostgreSQL and MySQL servers.
+
+Run with pytest -m testcontainers tests/testcontainers/versioning/test_chart_archive.py.
+The dedicated versioning-testcontainers workflow exercises both engines on PRs.
+"""
+
+from __future__ import annotations
+
+import os
+import sys
+from collections.abc import Iterator
+from importlib import import_module
+from threading import Event, Thread
+from time import perf_counter
+from types import SimpleNamespace
+from typing import Any
+from uuid import uuid4
+
+import pytest
+import sqlalchemy as sa
+from alembic.migration import MigrationContext
+from alembic.operations import Operations
+from sqlalchemy.engine import Connection, Engine
+from sqlalchemy.exc import DBAPIError, IntegrityError
+from sqlalchemy.orm import Session
+from sqlalchemy_continuum import versioning_manager
+from sqlalchemy_utils import UUIDType
+
+from superset.versioning import lifecycle
+from superset.versioning.changes.table import version_changes_table
+from superset.versioning.lifecycle_table import (
+ version_chart_archive_scope_table as scope,
+)
+
+pytestmark = pytest.mark.testcontainers
+
+# CI splits engines into independent jobs; a local invocation exercises both.
+_selected_backend = os.environ.get("SUPERSET_VERSIONING_TEST_DIALECT")
+if _selected_backend not in (None, "POSTGRES", "MYSQL"):
+ raise ValueError("SUPERSET_VERSIONING_TEST_DIALECT must be POSTGRES or MYSQL")
+_BACKENDS = [_selected_backend] if _selected_backend else ["POSTGRES", "MYSQL"]
+
+migration = import_module(
+ "superset.migrations.versions.2026-11-23_00-00_a7d29bc4e681_add_chart_archive_scope"
+)
+
+
+@pytest.fixture(scope="module", autouse=True)
+def model_import_context() -> Iterator[None]:
+ """Reuse pytest's app, or initialize SQLite for standalone execution."""
+ # CI loads tests/conftest.py, which imports tests.integration_tests.test_app
+ # and initializes models using its test configuration before this fixture.
+ # The SQLite fallback supports standalone invocations with --noconftest.
+ if "superset.models.dashboard" in sys.modules:
+ yield
+ return
+
+ from superset.app import SupersetApp
+ from superset.extensions import db
+ from superset.initialization import SupersetAppInitializer
+
+ app = SupersetApp(__name__)
+ app.config.from_object("superset.config")
+ app.config.update(
+ SQLALCHEMY_DATABASE_URI="sqlite://",
+ TESTING=True,
+ WTF_CSRF_ENABLED=False,
+ SECRET_KEY="isolated-archive-backend-tests", # noqa: S106
+ ENABLE_VERSIONING_CAPTURE=False,
+ )
+ SupersetAppInitializer(app).init_app()
+ with app.app_context():
+ yield
+ db.session.remove()
+ db.engine.dispose()
+
+
+@pytest.fixture(scope="module", params=_BACKENDS)
+def backend_uri(request: pytest.FixtureRequest) -> Iterator[str]:
+ """Start a real disposable metadata server; absent drivers fail in CI."""
+ from tests.testcontainers.db_engine_specs._driver import require_driver
+
+ if request.param == "POSTGRES":
+ require_driver("testcontainers.community.postgres")
+ from testcontainers.community.postgres import PostgresContainer
+
+ with PostgresContainer("postgres:17-alpine") as container:
+ yield container.get_connection_url()
+ else:
+ require_driver("testcontainers.community.mysql")
+ require_driver("pymysql")
+ from testcontainers.community.mysql import MySqlContainer
+
+ with MySqlContainer("mysql:8.0", dialect="pymysql") as container:
+ yield container.get_connection_url()
+
+
+@pytest.fixture
+def backend(backend_uri: str, monkeypatch: pytest.MonkeyPatch) -> Iterator[Engine]:
+ """Create minimal real metadata tables in the test-owned database."""
+ engine = sa.create_engine(backend_uri)
+ metadata = sa.MetaData()
+ tx = sa.Table(
+ "version_transaction",
+ metadata,
+ sa.Column("id", sa.BigInteger, primary_key=True),
+ sa.Column("issued_at", sa.DateTime),
+ sa.Column("user_id", sa.Integer),
+ sa.Column("action_kind", sa.String(32)),
+ )
+ version_changes_table.to_metadata(metadata)
+ sa.Table(
+ "dashboards",
+ metadata,
+ sa.Column("id", sa.Integer, primary_key=True),
+ sa.Column("uuid", UUIDType(binary=True)),
+ )
+ sa.Table(
+ "dashboard_slices",
+ metadata,
+ sa.Column("dashboard_id", sa.Integer),
+ sa.Column("slice_id", sa.Integer),
+ )
+ sa.Table(
+ "archive_test_work",
+ metadata,
+ sa.Column("id", sa.Integer, primary_key=True),
+ sa.Column("value", sa.Integer),
+ )
+ sa.Table(
+ "archive_test_locks",
+ metadata,
+ sa.Column("id", sa.Integer, primary_key=True),
+ sa.Column("value", sa.Integer),
+ )
+ # Refuse to overwrite a deployment or another concurrently running fixture.
+ assert not set(metadata.tables).intersection(sa.inspect(engine).get_table_names())
+ metadata.create_all(engine)
+ with engine.begin() as connection:
+ with Operations.context(MigrationContext.configure(connection)):
+ started = perf_counter()
+ migration.upgrade()
+ print(
+ f"{engine.dialect.name}: empty-table upgrade="
+ f"{(perf_counter() - started) * 1000:.2f}ms"
+ )
+ connection.execute(
+ metadata.tables["archive_test_work"].insert(), {"id": 1, "value": 0}
+ )
+ connection.execute(
+ metadata.tables["archive_test_locks"].insert(),
+ [{"id": i, "value": 0} for i in range(1, 103)],
+ )
+ monkeypatch.setattr(
+ versioning_manager, "transaction_cls", SimpleNamespace(__table__=tx)
+ )
+ monkeypatch.setattr(lifecycle, "transaction_actor_args", lambda: {})
+ try:
+ yield engine
+ finally:
+ with engine.begin() as connection:
+ with Operations.context(MigrationContext.configure(connection)):
+ migration.downgrade()
+ metadata.drop_all(engine)
+ engine.dispose()
+
+
+def _code(error: DBAPIError) -> str | int:
+ """Return the driver's structured diagnostic without parsing SQL or messages."""
+ return getattr(error.orig, "pgcode", None) or error.orig.args[0]
+
+
+def _hold_conflicting_lock(
+ backend: Engine,
+ blocker_ready: Event,
+ contender_ready: Event,
+ blocker_errors: list[BaseException],
+) -> None:
+ """Hold row two and wait on row one, with a heavier MySQL transaction."""
+ pg = backend.dialect.name == "postgresql"
+ try:
+ with backend.begin() as connection:
+ if pg:
+ connection.exec_driver_sql("SET LOCAL deadlock_timeout='10s'")
+ connection.exec_driver_sql(
+ "UPDATE archive_test_locks SET value=2 WHERE id=2"
+ )
+ if not pg:
+ connection.exec_driver_sql(
+ "UPDATE archive_test_locks SET value=2 WHERE id>=3"
+ )
+ blocker_ready.set()
+ assert contender_ready.wait(10)
+ connection.exec_driver_sql(
+ "UPDATE archive_test_locks SET value=2 WHERE id=1"
+ )
+ except BaseException as error:
+ blocker_errors.append(error)
+
+
+def test_lifecycle_real_contention(
+ backend: Engine, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """The capture loop recovers PG deadlocks and aborts MySQL transaction loss."""
+ pg = backend.dialect.name == "postgresql"
+ blocker_ready, contender_ready = Event(), Event()
+ blocker_errors: list[BaseException] = []
+ observed_codes: list[str | int] = []
+ attempted_charts: list[int] = []
+ sql_after_error: list[str] = []
+ error_seen = False
+
+ original_write = lifecycle._write_archive
+
+ def contended_write(
+ connection: Connection,
+ transaction_id: int,
+ archive: lifecycle.ChartArchive,
+ memberships: list[tuple[int, Any]],
+ ) -> int:
+ """Force the first chart's optional metadata statement into a real deadlock."""
+ nonlocal error_seen
+ attempted_charts.append(archive.chart_id)
+ if archive.chart_id == 1:
+ contender_ready.set()
+ try:
+ connection.exec_driver_sql(
+ "UPDATE archive_test_locks SET value=1 WHERE id=2"
+ )
+ except DBAPIError as error:
+ observed_codes.append(_code(error))
+ error_seen = True
+ raise
+ return original_write(connection, transaction_id, archive, memberships)
+
+ monkeypatch.setattr(lifecycle, "_write_archive", contended_write)
+ thread = Thread(
+ target=_hold_conflicting_lock,
+ args=(backend, blocker_ready, contender_ready, blocker_errors),
+ daemon=True,
+ )
+ thread.start()
+ assert blocker_ready.wait(10)
+ try:
+ with Session(backend) as session:
+ connection = session.connection()
+ if pg:
+ connection.exec_driver_sql("SET LOCAL deadlock_timeout='100ms'")
+ connection.exec_driver_sql(
+ "UPDATE archive_test_work SET value=1 WHERE id=1"
+ )
+ connection.exec_driver_sql(
+ "UPDATE archive_test_locks SET value=1 WHERE id=1"
+ )
+
+ def record_sql(
+ _connection: Connection,
+ _cursor: Any,
+ statement: str,
+ _parameters: Any,
+ _context: Any,
+ _many: bool,
+ ) -> None:
+ """Record every SQL statement after the failed optional write."""
+ if error_seen:
+ sql_after_error.append(statement)
+
+ sa.event.listen(connection, "before_cursor_execute", record_sql)
+ archives = [lifecycle.ChartArchive(i, uuid4(), str(i)) for i in (1, 2)]
+ if pg:
+ lifecycle.capture_chart_archives(session, archives)
+ session.commit()
+ assert observed_codes == ["40P01"]
+ assert attempted_charts == [1, 2]
+ else:
+ with pytest.raises(lifecycle.LifecycleCaptureFatalError) as raised:
+ lifecycle.capture_chart_archives(session, archives)
+ assert observed_codes == [1213]
+ assert attempted_charts == [1]
+ rollback_error = raised.value.__cause__
+ assert isinstance(rollback_error, DBAPIError)
+ assert _code(rollback_error) == 1305
+ assert isinstance(rollback_error.__cause__, DBAPIError)
+ assert _code(rollback_error.__cause__) == 1213
+ assert len(sql_after_error) == 1
+ assert sql_after_error[0].startswith("ROLLBACK TO SAVEPOINT")
+ session.rollback()
+ finally:
+ contender_ready.set()
+ thread.join(15)
+ assert not thread.is_alive()
+ assert blocker_errors == []
+ with backend.connect() as fresh:
+ assert fresh.exec_driver_sql(
+ "SELECT value FROM archive_test_work WHERE id=1"
+ ).scalar_one() == int(pg)
+ assert fresh.execute(
+ sa.select(version_changes_table.c.entity_id)
+ ).scalars().all() == ([2] if pg else [])
+
+
+def test_mysql_timeout_preserves_caller_and_other_chart(
+ backend: Engine, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """MySQL 1205 is optional only after the actual chart savepoint rolls back."""
+ if backend.dialect.name != "mysql":
+ pytest.skip("MySQL-specific timeout semantics")
+ original_write = lifecycle._write_archive
+ codes: list[str | int] = []
+
+ def timeout_write(
+ connection: Connection,
+ transaction_id: int,
+ archive: lifecycle.ChartArchive,
+ memberships: list[tuple[int, Any]],
+ ) -> int:
+ """Timeout only the first chart's metadata statement."""
+ if archive.chart_id == 1:
+ try:
+ connection.exec_driver_sql(
+ "UPDATE archive_test_locks SET value=1 WHERE id=2"
+ )
+ except DBAPIError as error:
+ codes.append(_code(error))
+ raise
+ return original_write(connection, transaction_id, archive, memberships)
+
+ monkeypatch.setattr(lifecycle, "_write_archive", timeout_write)
+ with backend.connect() as blocker_connection:
+ blocker_transaction = blocker_connection.begin()
+ blocker_connection.exec_driver_sql(
+ "UPDATE archive_test_locks SET value=2 WHERE id=2"
+ )
+ try:
+ with Session(backend) as session:
+ session.execute(sa.text("SET SESSION innodb_lock_wait_timeout=1"))
+ assert (
+ session.execute(
+ sa.text("SELECT @@innodb_rollback_on_timeout")
+ ).scalar_one()
+ == 0
+ )
+ session.execute(
+ sa.text("UPDATE archive_test_work SET value=1 WHERE id=1")
+ )
+ lifecycle.capture_chart_archives(
+ session,
+ [lifecycle.ChartArchive(i, uuid4(), str(i)) for i in (1, 2)],
+ )
+ session.commit()
+ finally:
+ blocker_transaction.rollback()
+ assert codes == [1205]
+ with backend.connect() as fresh:
+ assert (
+ fresh.exec_driver_sql(
+ "SELECT value FROM archive_test_work WHERE id=1"
+ ).scalar_one()
+ == 1
+ )
+ assert fresh.execute(
+ sa.select(version_changes_table.c.entity_id)
+ ).scalars().all() == [2]
+
+
+def test_migration_rerun_uuid_cascade_and_downgrade(backend: Engine) -> None:
+ """Exercise production DDL with interrupted indexes and repeated rollback."""
+ with backend.begin() as connection:
+ with Operations.context(MigrationContext.configure(connection)):
+ sa.Index(
+ "ix_chart_archive_scope_chart", scope.c.chart_id, scope.c.transaction_id
+ ).drop(connection)
+ start = perf_counter()
+ migration.upgrade()
+ upgrade_ms = (perf_counter() - start) * 1000
+ migration.upgrade()
+ index_names = {
+ index["name"] for index in sa.inspect(connection).get_indexes(scope.name)
+ }
+ assert {
+ "ix_chart_archive_scope_dashboard",
+ "ix_chart_archive_scope_chart",
+ } <= index_names
+ assert (
+ connection.execute(
+ versioning_manager.transaction_cls.__table__.insert().values(
+ action_kind=None
+ )
+ ).inserted_primary_key[0]
+ == 1
+ )
+ row = {
+ "id": uuid4(),
+ "transaction_id": 1,
+ "chart_id": 1,
+ "chart_uuid": uuid4(),
+ "dashboard_id": 1,
+ "dashboard_uuid": uuid4(),
+ }
+ connection.execute(scope.insert(), row)
+ assert (
+ connection.execute(sa.select(scope.c.chart_uuid)).scalar_one()
+ == row["chart_uuid"]
+ )
+ with pytest.raises(IntegrityError), connection.begin_nested():
+ connection.execute(scope.insert(), {**row, "id": uuid4()})
+ connection.exec_driver_sql("DELETE FROM version_transaction WHERE id=1")
+ assert connection.scalar(sa.select(sa.func.count()).select_from(scope)) == 0
+ connection.exec_driver_sql("INSERT INTO version_transaction (id) VALUES (2)")
+ for index, kind in enumerate(("field", lifecycle.CHART_ARCHIVE_KIND)):
+ connection.execute(
+ version_changes_table.insert(),
+ {
+ "transaction_id": 2,
+ "entity_kind": "chart",
+ "entity_id": 1,
+ "sequence": index,
+ "kind": kind,
+ "operation": "announce",
+ "path": [],
+ "from_value": None,
+ "to_value": None,
+ },
+ )
+ with Operations.context(MigrationContext.configure(connection)):
+ start = perf_counter()
+ migration.downgrade()
+ downgrade_ms = (perf_counter() - start) * 1000
+ migration.downgrade()
+ assert connection.execute(
+ sa.select(version_changes_table.c.kind)
+ ).scalars().all() == ["field"]
+ assert connection.exec_driver_sql(
+ "SELECT id FROM version_transaction"
+ ).scalars().all() == [2]
+ assert not sa.inspect(connection).has_table(scope.name)
+ print(
+ f"{backend.dialect.name}: index-repair upgrade={upgrade_ms:.2f}ms "
+ f"downgrade={downgrade_ms:.2f}ms"
+ )
+
+
+def test_missing_scope_read_and_write_keep_connection_usable(
+ backend: Engine, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """A rollout without scope storage preserves content reads and caller writes."""
+ import superset
+ from superset.versioning.activity import queries
+ from superset.versioning.activity.kinds import Window
+
+ # Project nullable actor fields without requiring the application's FAB tables.
+ users = sa.Table(
+ "archive_test_users",
+ sa.MetaData(),
+ sa.Column("id", sa.Integer, primary_key=True),
+ sa.Column("first_name", sa.String(30)),
+ sa.Column("last_name", sa.String(30)),
+ )
+ users.create(backend)
+ monkeypatch.setattr(
+ superset,
+ "security_manager",
+ SimpleNamespace(user_model=SimpleNamespace(__table__=users)),
+ )
+ try:
+ with backend.begin() as connection:
+ scope.drop(connection)
+ connection.exec_driver_sql(
+ "INSERT INTO version_transaction (id, issued_at) "
+ "VALUES (50, '2020-01-01')"
+ )
+ connection.execute(
+ version_changes_table.insert(),
+ {
+ "transaction_id": 50,
+ "entity_kind": "chart",
+ "entity_id": 1,
+ "sequence": 0,
+ "kind": "field",
+ "operation": "edit",
+ "path": [],
+ "from_value": None,
+ "to_value": None,
+ },
+ )
+ with Session(backend) as session:
+ monkeypatch.setattr(queries, "db", SimpleNamespace(session=session))
+ rows, truncated, floor = queries._fetch_dashboard_archive_candidates(
+ 1, uuid4(), None, None, 100
+ )
+ assert (rows, truncated, floor) == ([], False, None)
+ content, content_truncated = queries.fetch_change_records(
+ [("Slice", 1, [Window(0, None)])],
+ None,
+ None,
+ dashboard_id=1,
+ dashboard_uuid=uuid4(),
+ )
+ assert [row["transaction_id"] for row in content] == [50]
+ assert not content_truncated
+ assert (
+ session.execute(
+ sa.text("SELECT count(*) FROM version_changes")
+ ).scalar_one()
+ == 1
+ )
+ session.execute(sa.text("UPDATE archive_test_work SET value=1 WHERE id=1"))
+ dashboard_uuid = uuid4()
+ session.execute(sa.text("INSERT INTO dashboard_slices VALUES (1, 1)"))
+ # Match the live UUID binding type, including MySQL binary UUIDs.
+ dashboards = sa.Table(
+ "dashboards",
+ sa.MetaData(),
+ sa.Column("id", sa.Integer),
+ sa.Column("uuid", UUIDType(binary=True)),
+ )
+ session.execute(dashboards.insert().values(id=1, uuid=dashboard_uuid))
+ lifecycle.capture_chart_archives(
+ session, [lifecycle.ChartArchive(1, uuid4(), "chart")]
+ )
+ session.commit()
+ with backend.connect() as fresh:
+ assert (
+ fresh.exec_driver_sql(
+ "SELECT value FROM archive_test_work WHERE id=1"
+ ).scalar_one()
+ == 1
+ )
+ assert fresh.execute(
+ sa.select(version_changes_table.c.kind)
+ ).scalars().all() == ["field"]
+ finally:
+ users.drop(backend)
+
+
+@pytest.mark.parametrize("capture_step", ["stamp", "changes"])
+def test_content_deadlock_cannot_commit_phantom_archive(
+ backend: Engine,
+ monkeypatch: pytest.MonkeyPatch,
+ capture_step: str,
+) -> None:
+ """The real before-commit pipeline stops after MySQL loses caller content work."""
+ from superset.versioning.changes import listener
+ from superset.versioning.diff import ChangeRecord
+
+ pg = backend.dialect.name == "postgresql"
+ blocker_ready, contender_ready = Event(), Event()
+ blocker_errors: list[BaseException] = []
+ error_codes: list[str | int] = []
+ after_error_sql: list[str] = []
+ archive = lifecycle.ChartArchive(1, uuid4(), "renamed chart")
+ change = ChangeRecord(
+ kind="field",
+ operation="edit",
+ path=["slice_name"],
+ from_value="old",
+ to_value="renamed chart",
+ )
+ # Isolate the SQL transaction protocol from Continuum's model diff setup;
+ # finalization, content savepoints, and subsequent lifecycle capture are real.
+ monkeypatch.setattr(listener, "capture_for_write", lambda session: True)
+ monkeypatch.setattr(listener, "_current_transaction_id", lambda session: 1)
+ monkeypatch.setattr(
+ listener, "_build_scalar_buffer", lambda states: {("chart", 1): [change]}
+ )
+ monkeypatch.setattr(
+ lifecycle, "collect_chart_archives", lambda session, states: [archive]
+ )
+ monkeypatch.setitem(versioning_manager.options, "versioning", True)
+ monkeypatch.setattr(
+ listener, "_append_child_records_to_buffer", lambda session, tx, buffer: None
+ )
+ monkeypatch.setattr(
+ listener, "reconcile_parent_snapshots", lambda session, tx: None
+ )
+
+ def contend(session: Session, *_args: Any) -> None:
+ """Make the actual content savepoint encounter a database deadlock."""
+ contender_ready.set()
+ try:
+ session.connection().exec_driver_sql(
+ "UPDATE archive_test_locks SET value=1 WHERE id=2"
+ )
+ except DBAPIError as error:
+ error_codes.append(_code(error))
+ raise
+
+ seam = "_write_action_kind" if capture_step == "stamp" else "bulk_insert_records"
+ monkeypatch.setattr(listener, seam, contend)
+ thread = Thread(
+ target=_hold_conflicting_lock,
+ args=(backend, blocker_ready, contender_ready, blocker_errors),
+ daemon=True,
+ )
+ thread.start()
+ assert blocker_ready.wait(10)
+ try:
+ with Session(backend) as session:
+ connection = session.connection()
+ if pg:
+ connection.exec_driver_sql("SET LOCAL deadlock_timeout='100ms'")
+ assert (
+ connection.execute(
+ versioning_manager.transaction_cls.__table__.insert().values(
+ action_kind=None
+ )
+ ).inserted_primary_key[0]
+ == 1
+ )
+ connection.exec_driver_sql(
+ "UPDATE archive_test_work SET value=1 WHERE id=1"
+ )
+ connection.exec_driver_sql(
+ "UPDATE archive_test_locks SET value=1 WHERE id=1"
+ )
+ session.info[listener.ACTION_KIND_KEY] = "restore"
+
+ def record_sql(
+ _connection: Connection,
+ _cursor: Any,
+ statement: str,
+ _parameters: Any,
+ _context: Any,
+ _many: bool,
+ ) -> None:
+ """Detect any SQL after content savepoint recovery fails."""
+ if error_codes:
+ after_error_sql.append(statement)
+
+ sa.event.listen(connection, "before_cursor_execute", record_sql)
+ sa.event.listen(session, "before_commit", listener.finalize_change_records)
+ if pg:
+ session.commit()
+ assert error_codes == ["40P01"]
+ else:
+ with pytest.raises(DBAPIError) as raised:
+ session.commit()
+ assert _code(raised.value) == 1305
+ assert error_codes == [1213]
+ assert len(after_error_sql) == 1
+ assert after_error_sql[0].startswith("ROLLBACK TO SAVEPOINT")
+ session.rollback()
+ finally:
+ contender_ready.set()
+ thread.join(15)
+ assert not thread.is_alive()
+ assert blocker_errors == []
+ with backend.connect() as fresh:
+ assert fresh.exec_driver_sql(
+ "SELECT value FROM archive_test_work WHERE id=1"
+ ).scalar_one() == int(pg)
+ archived_ids = (
+ fresh.execute(
+ sa.select(version_changes_table.c.entity_id).where(
+ version_changes_table.c.kind == lifecycle.CHART_ARCHIVE_KIND
+ )
+ )
+ .scalars()
+ .all()
+ )
+ assert archived_ids == ([1] if pg else [])
+
+
+def test_purge_reads_both_shadow_endpoints_in_one_statement(backend: Engine) -> None:
+ """Endpoint collection has the same bounded SQL cost on both metadata engines."""
+ from superset.commands.deletion_retention.purge_cascade import (
+ _delete_history_targets,
+ )
+
+ shadow = sa.Table(
+ "archive_test_shadow",
+ sa.MetaData(),
+ sa.Column("id", sa.Integer),
+ sa.Column("transaction_id", sa.BigInteger),
+ sa.Column("end_transaction_id", sa.BigInteger),
+ )
+ shadow.create(backend)
+ try:
+ with Session(backend) as session:
+ session.execute(
+ shadow.insert(),
+ [
+ {"id": 1, "transaction_id": 10, "end_transaction_id": 11},
+ {"id": 1, "transaction_id": 11, "end_transaction_id": None},
+ ],
+ )
+ statements: list[str] = []
+
+ def track(
+ _connection: Connection,
+ _cursor: Any,
+ statement: str,
+ _parameters: Any,
+ _context: Any,
+ _many: bool,
+ ) -> None:
+ """Count only candidate collection and deletion SQL."""
+ statements.append(statement)
+
+ sa.event.listen(session.connection(), "before_cursor_execute", track)
+ candidates: set[int] = set()
+ assert (
+ _delete_history_targets(
+ session, [(shadow, shadow.c.id == 1)], candidates
+ )
+ == 2
+ )
+ assert candidates == {10, 11}
+ assert len(statements) == 2
+ assert statements[0].startswith("SELECT DISTINCT")
+ assert statements[1].startswith("DELETE")
+ session.commit()
+ finally:
+ shadow.drop(backend)
diff --git a/tests/unit_tests/migrations/test_chart_archive_scope.py b/tests/unit_tests/migrations/test_chart_archive_scope.py
new file mode 100644
index 000000000000..0a40c6883054
--- /dev/null
+++ b/tests/unit_tests/migrations/test_chart_archive_scope.py
@@ -0,0 +1,104 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""Exercise archive scope DDL, interrupted upgrades, and content-safe rollback."""
+
+from importlib import import_module
+from uuid import uuid4
+
+import pytest
+import sqlalchemy as sa
+from alembic.migration import MigrationContext
+from alembic.operations import Operations
+from sqlalchemy.exc import IntegrityError
+
+migration = import_module(
+ "superset.migrations.versions.2026-11-23_00-00_a7d29bc4e681_add_chart_archive_scope"
+)
+
+
+def test_archive_scope_upgrade_constraints_and_cascade() -> None:
+ """Rerun upgrade repairs indexes and UUID scopes cascade with their transaction."""
+ engine = sa.create_engine("sqlite://")
+ with engine.begin() as connection:
+ connection.exec_driver_sql("PRAGMA foreign_keys=ON")
+ connection.exec_driver_sql(
+ "CREATE TABLE version_transaction (id BIGINT PRIMARY KEY)"
+ )
+ with Operations.context(MigrationContext.configure(connection)):
+ migration.upgrade()
+ connection.exec_driver_sql("DROP INDEX ix_chart_archive_scope_chart")
+ migration.upgrade()
+ inspector = sa.inspect(connection)
+ assert {
+ index["name"]
+ for index in inspector.get_indexes("version_chart_archive_scope")
+ } == {"ix_chart_archive_scope_dashboard", "ix_chart_archive_scope_chart"}
+ assert (
+ inspector.get_foreign_keys("version_chart_archive_scope")[0]["options"][
+ "ondelete"
+ ]
+ == "CASCADE"
+ )
+ from superset.versioning.lifecycle_table import (
+ version_chart_archive_scope_table as scope,
+ )
+
+ connection.exec_driver_sql("INSERT INTO version_transaction VALUES (1)")
+ row = {
+ "id": uuid4(),
+ "transaction_id": 1,
+ "chart_id": 2,
+ "chart_uuid": uuid4(),
+ "dashboard_id": 3,
+ "dashboard_uuid": uuid4(),
+ }
+ connection.execute(scope.insert().values(**row))
+ assert (
+ connection.execute(sa.select(scope.c.chart_uuid)).scalar_one()
+ == row["chart_uuid"]
+ )
+ with pytest.raises(IntegrityError):
+ connection.execute(scope.insert().values(**{**row, "id": uuid4()}))
+ connection.exec_driver_sql("DELETE FROM version_transaction WHERE id=1")
+ assert connection.scalar(sa.select(sa.func.count()).select_from(scope)) == 0
+ engine.dispose()
+
+
+def test_archive_scope_downgrade_preserves_content_and_transactions() -> None:
+ """Repeated downgrade deletes only archive events without sweeping transactions."""
+ engine = sa.create_engine("sqlite://")
+ with engine.begin() as connection:
+ connection.exec_driver_sql(
+ "CREATE TABLE version_transaction (id BIGINT PRIMARY KEY)"
+ )
+ connection.exec_driver_sql("INSERT INTO version_transaction VALUES (1)")
+ connection.exec_driver_sql("CREATE TABLE version_changes (kind VARCHAR(32))")
+ connection.exec_driver_sql(
+ "INSERT INTO version_changes VALUES ('field'), ('__archive__')"
+ )
+ with Operations.context(MigrationContext.configure(connection)):
+ migration.upgrade()
+ migration.downgrade()
+ migration.downgrade()
+ assert not sa.inspect(connection).has_table("version_chart_archive_scope")
+ assert connection.exec_driver_sql(
+ "SELECT kind FROM version_changes"
+ ).scalars().all() == ["field"]
+ assert connection.exec_driver_sql(
+ "SELECT id FROM version_transaction"
+ ).scalars().all() == [1]
+ engine.dispose()
diff --git a/tests/unit_tests/versioning/conftest.py b/tests/unit_tests/versioning/conftest.py
new file mode 100644
index 000000000000..acdee5b688da
--- /dev/null
+++ b/tests/unit_tests/versioning/conftest.py
@@ -0,0 +1,38 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""Shared disposable database fixture for native version capture tests."""
+
+from collections.abc import Iterator
+
+import pytest
+from flask_appbuilder import Model
+from sqlalchemy.orm import Session
+
+from superset.app import SupersetApp
+from superset.extensions import db
+
+
+@pytest.fixture
+def capture_session(app: SupersetApp) -> Iterator[Session]:
+ """Create only disposable in-memory tables; retain native listener wiring."""
+ assert db.engine.url.get_backend_name() == "sqlite"
+ assert not db.engine.url.database
+ Model.metadata.create_all(db.engine)
+ session: Session = db.session()
+ yield session
+ db.session.remove()
+ Model.metadata.drop_all(db.engine)
diff --git a/tests/unit_tests/versioning/test_archive_activity.py b/tests/unit_tests/versioning/test_archive_activity.py
new file mode 100644
index 000000000000..eaf194822807
--- /dev/null
+++ b/tests/unit_tests/versioning/test_archive_activity.py
@@ -0,0 +1,423 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""Archive candidate identity, bounded streaming, and decoration regressions."""
+
+from __future__ import annotations
+
+from collections.abc import Iterator
+from datetime import datetime, timedelta
+from types import SimpleNamespace
+from typing import Any
+from uuid import uuid4
+
+import pytest
+import sqlalchemy as sa
+
+from superset.versioning.activity import queries, render
+from superset.versioning.activity.kinds import Window
+from superset.versioning.lifecycle import CHART_ARCHIVE_KIND
+from superset.versioning.schemas import ActivityRecordSchema
+
+
+@pytest.fixture
+def archive_store(monkeypatch: pytest.MonkeyPatch) -> Iterator[SimpleNamespace]:
+ """Exercise both streams against real SQL and a metadata-created scope table."""
+ from sqlalchemy_continuum import versioning_manager
+
+ import superset
+ from superset.versioning import lifecycle_table
+
+ metadata = sa.MetaData()
+ changes = queries.version_changes_table.to_metadata(metadata)
+ scope = lifecycle_table.version_chart_archive_scope_table.to_metadata(metadata)
+ transactions = sa.Table(
+ "version_transaction",
+ metadata,
+ sa.Column("id", sa.Integer, primary_key=True),
+ sa.Column("issued_at", sa.DateTime),
+ sa.Column("user_id", sa.Integer),
+ sa.Column("action_kind", sa.String(32)),
+ )
+ users = sa.Table(
+ "archive_activity_users",
+ metadata,
+ sa.Column("id", sa.Integer, primary_key=True),
+ sa.Column("first_name", sa.String),
+ sa.Column("last_name", sa.String),
+ )
+ monkeypatch.setattr(queries, "version_changes_table", changes)
+ monkeypatch.setattr(lifecycle_table, "version_chart_archive_scope_table", scope)
+ monkeypatch.setattr(
+ versioning_manager, "transaction_cls", SimpleNamespace(__table__=transactions)
+ )
+ monkeypatch.setattr(
+ superset,
+ "security_manager",
+ SimpleNamespace(user_model=SimpleNamespace(__table__=users)),
+ )
+ engine = sa.create_engine("sqlite://")
+ dashboard_uuid = uuid4()
+ chart_uuid = uuid4()
+ with engine.begin() as connection:
+ metadata.create_all(connection)
+ monkeypatch.setattr(
+ queries,
+ "db",
+ SimpleNamespace(session=SimpleNamespace(connection=lambda: connection)),
+ )
+
+ def add(
+ tx: int, *, archive: bool = True, valid: bool = True, chart_id: int = 7
+ ) -> None:
+ """Insert a content or scoped archive event with sortable UTC time."""
+ connection.execute(
+ transactions.insert().values(
+ id=tx, issued_at=datetime(2026, 1, 1) + timedelta(seconds=tx)
+ )
+ )
+ connection.execute(
+ changes.insert().values(
+ id=tx,
+ transaction_id=tx,
+ entity_kind="chart",
+ entity_id=chart_id,
+ sequence=0,
+ kind=CHART_ARCHIVE_KIND if archive else "field",
+ operation="announce" if archive else "replace",
+ path=["deleted_at"],
+ to_value={
+ "entity_uuid": str(chart_uuid if valid else uuid4()),
+ "entity_name": f"Chart {tx}",
+ },
+ )
+ )
+ if archive:
+ connection.execute(
+ scope.insert().values(
+ id=uuid4(),
+ transaction_id=tx,
+ chart_id=chart_id,
+ chart_uuid=chart_uuid,
+ dashboard_id=9,
+ dashboard_uuid=dashboard_uuid,
+ )
+ )
+
+ yield SimpleNamespace(
+ connection=connection,
+ changes=changes,
+ scope=scope,
+ add=add,
+ dashboard_uuid=dashboard_uuid,
+ chart_uuid=chart_uuid,
+ )
+ engine.dispose()
+
+
+def test_archive_query_admits_valid_rows_before_applying_ceiling(
+ archive_store: SimpleNamespace,
+) -> None:
+ """Malformed identities cannot consume the budget or hide truncation."""
+ for tx in range(1, 4):
+ archive_store.add(tx)
+ for tx in range(4, 12):
+ archive_store.add(tx, valid=False)
+ rows, truncated, floor = queries._fetch_dashboard_archive_candidates(
+ 9, archive_store.dashboard_uuid, None, None, 2
+ )
+ assert [row["transaction_id"] for row in rows] == [3, 2]
+ assert truncated
+ assert floor == queries._record_sort_key(rows[-1])
+ assert all("scope_chart_uuid" not in row for row in rows)
+
+
+def test_archive_scope_matches_dashboard_id_and_uuid(
+ archive_store: SimpleNamespace,
+) -> None:
+ """Re-importing a UUID with another ID cannot inherit old dashboard activity."""
+ archive_store.add(1)
+ for dashboard_id, dashboard_uuid in [
+ (10, archive_store.dashboard_uuid),
+ (9, uuid4()),
+ ]:
+ assert queries._fetch_dashboard_archive_candidates(
+ dashboard_id, dashboard_uuid, None, None, 2
+ ) == ([], False, None)
+
+
+def test_content_probe_excludes_archives_before_budget(
+ archive_store: SimpleNamespace, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """An arbitrarily long archive/recovery history cannot displace latest content."""
+ archive_store.add(1, archive=False)
+ archive_store.add(2, archive=False)
+ for tx in range(3, 20):
+ archive_store.add(tx)
+ monkeypatch.setattr(queries, "_MAX_FETCHED_RECORDS", 1)
+ records, truncated = queries.fetch_change_records(
+ [("Slice", 7, [Window(0, None)])], None, None
+ )
+ assert [record["transaction_id"] for record in records] == [2]
+ assert truncated
+
+
+def test_archive_stream_has_no_content_window_lower_bound(
+ archive_store: SimpleNamespace,
+) -> None:
+ """An untracked dashboard can show archives without fabricated content."""
+ archive_store.add(1)
+ rows, truncated = queries.fetch_change_records(
+ [], None, None, dashboard_id=9, dashboard_uuid=archive_store.dashboard_uuid
+ )
+ assert [row["transaction_id"] for row in rows] == [1]
+ assert not truncated
+
+
+def test_archive_and_content_streams_share_highest_truncation_floor(
+ archive_store: SimpleNamespace, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """Rows older than an exhausted stream's floor never create pagination holes."""
+ for tx in (1, 4, 7):
+ archive_store.add(tx, archive=False)
+ for tx in (2, 3, 5, 6):
+ archive_store.add(tx)
+ monkeypatch.setattr(queries, "_MAX_FETCHED_RECORDS", 2)
+ rows, truncated = queries.fetch_change_records(
+ [("Slice", 7, [Window(0, None)])],
+ None,
+ None,
+ dashboard_id=9,
+ dashboard_uuid=archive_store.dashboard_uuid,
+ )
+ assert truncated
+ assert [row["transaction_id"] for row in rows] == [7, 6, 5]
+ keys = [
+ (r["transaction_id"], r["entity_kind"], r["entity_id"], r["sequence"])
+ for r in rows
+ ]
+ assert len(keys) == len(set(keys))
+
+
+def test_archive_query_time_bounds(archive_store: SimpleNamespace) -> None:
+ """The archive stream uses inclusive since and exclusive until bounds."""
+ for tx in range(1, 5):
+ archive_store.add(tx)
+ start = datetime(2026, 1, 1)
+ rows, truncated, _ = queries._fetch_dashboard_archive_candidates(
+ 9,
+ archive_store.dashboard_uuid,
+ start + timedelta(seconds=2),
+ start + timedelta(seconds=4),
+ 10,
+ )
+ assert [row["transaction_id"] for row in rows] == [3, 2]
+ assert not truncated
+
+
+def test_missing_scope_table_preserves_content_and_connection(
+ archive_store: SimpleNamespace,
+) -> None:
+ """Missing migration rolls back just the optional read savepoint."""
+ archive_store.add(1, archive=False)
+ archive_store.scope.drop(archive_store.connection)
+ rows, truncated = queries.fetch_change_records(
+ [("Slice", 7, [Window(0, None)])],
+ None,
+ None,
+ dashboard_id=9,
+ dashboard_uuid=archive_store.dashboard_uuid,
+ )
+ assert [row["transaction_id"] for row in rows] == [1]
+ assert not truncated
+ assert archive_store.connection.execute(sa.select(sa.literal(1))).scalar() == 1
+ archive_store.scope.create(archive_store.connection)
+ archive_store.add(2)
+ assert (
+ len(
+ queries._fetch_dashboard_archive_candidates(
+ 9, archive_store.dashboard_uuid, None, None, 10
+ )[0]
+ )
+ == 1
+ )
+
+
+@pytest.mark.parametrize(
+ "payload", [None, [], {}, {"entity_uuid": 1}, {"entity_uuid": "invalid"}]
+)
+def test_invalid_archive_identity_never_borrows_live_identity(payload: Any) -> None:
+ """Only validated UUID-bearing payloads can identify a historical chart."""
+ assert queries.archive_entity_uuid({"to_value": payload}) is None
+
+
+def test_archive_schema_and_summary_preserve_historical_verb() -> None:
+ """Archive headlines remain archives after the chart is recovered."""
+ assert ActivityRecordSchema().load({"kind": CHART_ARCHIVE_KIND}) == {
+ "kind": CHART_ARCHIVE_KIND
+ }
+ assert (
+ render._build_summary(
+ "Slice", {"kind": CHART_ARCHIVE_KIND, "entity_name": "Old name"}
+ )
+ == "Chart archived: Old name"
+ )
+
+
+def test_archive_payload_name_does_not_use_content_shadow(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """Capture-time name wins over a stale shadow or a later rename."""
+
+ def no_lookup(*args: Any) -> None:
+ raise AssertionError("Archive must not use content name lookup")
+
+ monkeypatch.setattr(queries, "_resolve_names_for_kind", no_lookup)
+ record = {
+ "entity_kind": "chart",
+ "entity_id": 7,
+ "transaction_id": 2,
+ "kind": CHART_ARCHIVE_KIND,
+ "to_value": {"entity_uuid": str(uuid4()), "entity_name": "Historical name"},
+ }
+ queries.apply_entity_name_denormalization([record])
+ assert record["entity_name"] == "Historical name"
+
+
+@pytest.mark.parametrize(
+ "state", ["active", "soft_deleted", "hard_deleted", "reused", "invalid"]
+)
+@pytest.mark.parametrize("can_edit", [False, True])
+def test_archive_decoration_redacts_deleted_identity_and_protected_detail(
+ monkeypatch: pytest.MonkeyPatch,
+ state: str,
+ can_edit: bool,
+) -> None:
+ """Historical identity wins, while deletion and editorship govern disclosure."""
+ identity = uuid4()
+ live_identity = uuid4() if state == "reused" else identity
+ monkeypatch.setattr(
+ render,
+ "check_entity_tombstones",
+ lambda _: {
+ ("Slice", 7): {
+ "deleted": state == "hard_deleted",
+ "deletion_state": "soft_deleted" if state == "soft_deleted" else None,
+ }
+ },
+ )
+ monkeypatch.setattr(
+ render, "_lookup_entity_uuids", lambda *_: {("Slice", 7): live_identity}
+ )
+ monkeypatch.setattr(render, "resolve_historical_entity_snapshots", lambda _: {})
+ monkeypatch.setattr(
+ render, "resolve_editorship", lambda _: {("Slice", 7): can_edit}
+ )
+ monkeypatch.setattr(render, "batch_chart_impacts", lambda *_: {})
+ monkeypatch.setattr(render, "impact_for_record", lambda *_: None)
+ record = {
+ "entity_kind": "chart",
+ "entity_id": 7,
+ "transaction_id": 2,
+ "kind": CHART_ARCHIVE_KIND,
+ "entity_name": "Archive-time name",
+ "to_value": {"entity_uuid": "invalid" if state == "invalid" else str(identity)},
+ "path": ["deleted_at"],
+ "from_value": None,
+ "changed_by_id": 12,
+ "first_name": "Archive",
+ "last_name": "Actor",
+ "first_tracked_save": False,
+ }
+ render.apply_record_decoration([record], "Dashboard", 9)
+ assert record["source"] == "related"
+ assert record["version_uuid"] is None
+ assert record["first_tracked_save"] is False
+ if state in {"hard_deleted", "reused", "invalid"}:
+ assert record["entity_deleted"] is True
+ assert record["entity_uuid"] is None
+ assert record["entity_name"] == ""
+ assert record["summary"] == "(deleted) Chart"
+ assert record["to_value"] is None
+ assert record["changed_by"] is None
+ else:
+ assert record["entity_uuid"] == str(identity)
+ assert record["summary"] == "Chart archived: Archive-time name"
+ assert (record["changed_by"] is not None) is can_edit
+ assert (record["to_value"] is not None) is can_edit
+
+
+@pytest.mark.parametrize("api_kind", ["Slice", "SqlaTable"])
+def test_related_visibility_includes_archived_rows_without_bypassing_access(
+ capture_session: sa.orm.Session,
+ monkeypatch: pytest.MonkeyPatch,
+ api_kind: str,
+) -> None:
+ """History includes archives under read policy without unhiding ordinary reads."""
+ from superset.charts.filters import ChartFilter
+ from superset.connectors.sqla.models import SqlaTable
+ from superset.models import helpers
+ from superset.models.core import Database
+ from superset.models.slice import Slice
+ from superset.versioning.activity import visibility
+ from superset.views.base import DatasourceFilter
+
+ model: type[Slice] | type[SqlaTable] = Slice if api_kind == "Slice" else SqlaTable
+ access_filter = ChartFilter if api_kind == "Slice" else DatasourceFilter
+ name_column = "slice_name" if api_kind == "Slice" else "table_name"
+ extra_fields: dict[str, Any] = {}
+ if api_kind == "SqlaTable":
+ capture_session.execute(
+ Database.__table__.insert().values(
+ id=900, database_name="Visibility test", sqlalchemy_uri="sqlite://"
+ )
+ )
+ extra_fields["database_id"] = 900
+ capture_session.execute(
+ model.__table__.insert(),
+ [
+ {
+ "id": entity_id,
+ name_column: f"Entity {entity_id}",
+ "deleted_at": deleted_at,
+ **extra_fields,
+ }
+ for entity_id, deleted_at in [
+ (901, datetime(2026, 1, 1)),
+ (902, datetime(2026, 1, 1)),
+ (904, None),
+ ]
+ ],
+ )
+ monkeypatch.setattr(helpers, "is_feature_enabled", lambda _: True)
+
+ def apply_access(
+ self: Any, query: sa.orm.Query[Any], value: Any
+ ) -> sa.orm.Query[Any]:
+ """Model a read grant for one archived row and one active row."""
+ return query.filter(model.id.in_([901, 904]))
+
+ monkeypatch.setattr(access_filter, "apply", apply_access)
+ assert visibility._resolve_visibility(
+ {(api_kind, entity_id) for entity_id in [901, 902, 903, 904]}
+ ) == {
+ (api_kind, 901): True, # readable archive
+ (api_kind, 902): False, # unreadable archive, not a tombstone
+ (api_kind, 903): True, # hard-deleted, redacted by decoration
+ (api_kind, 904): True, # readable active row
+ }
+ # A per-statement history bypass must never escape into ordinary reads.
+ assert capture_session.query(model.id).all() == [(904,)]
diff --git a/tests/unit_tests/versioning/test_archive_cleanup.py b/tests/unit_tests/versioning/test_archive_cleanup.py
new file mode 100644
index 000000000000..8cf08dc75b74
--- /dev/null
+++ b/tests/unit_tests/versioning/test_archive_cleanup.py
@@ -0,0 +1,310 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""Archive-only transaction cleanup and immutable scope identities."""
+
+from collections.abc import Iterator
+from datetime import datetime
+from types import SimpleNamespace
+from unittest.mock import patch
+from uuid import uuid4
+
+import pytest
+import sqlalchemy as sa
+from sqlalchemy.orm import Session
+from sqlalchemy_continuum import versioning_manager
+
+from superset.commands.deletion_retention import purge_cascade
+from superset.tasks import version_history_retention as retention
+from superset.versioning.lifecycle_table import version_chart_archive_scope_table
+
+
+@pytest.fixture
+def cleanup_db() -> Iterator[tuple[Session, sa.MetaData]]:
+ """Use real SQL tables without FK cascades, matching metadata-created schemas."""
+ metadata = sa.MetaData()
+ sa.Table(
+ "version_transaction",
+ metadata,
+ sa.Column("id", sa.Integer, primary_key=True),
+ sa.Column("issued_at", sa.DateTime),
+ )
+ for name in ("slices_version", "dashboards_version"):
+ sa.Table(
+ name,
+ metadata,
+ sa.Column("id", sa.Integer),
+ sa.Column("transaction_id", sa.Integer),
+ sa.Column("end_transaction_id", sa.Integer),
+ )
+ sa.Table(
+ "version_changes",
+ metadata,
+ sa.Column("transaction_id", sa.Integer),
+ sa.Column("entity_id", sa.Integer),
+ sa.Column("entity_kind", sa.String),
+ sa.Column("kind", sa.String),
+ )
+ version_chart_archive_scope_table.to_metadata(metadata)
+ engine = sa.create_engine("sqlite://")
+ metadata.create_all(engine)
+ session = Session(engine)
+ with patch.object(
+ versioning_manager,
+ "transaction_cls",
+ SimpleNamespace(__table__=metadata.tables["version_transaction"]),
+ ):
+ yield session, metadata
+ session.close()
+ engine.dispose()
+
+
+def _seed(
+ session: Session, metadata: sa.MetaData
+) -> tuple[SimpleNamespace, SimpleNamespace, SimpleNamespace]:
+ """Create two archives sharing a transaction and dashboard, with no shadows."""
+ chart_a = SimpleNamespace(id=1, uuid=uuid4())
+ chart_b = SimpleNamespace(id=2, uuid=uuid4())
+ dashboard = SimpleNamespace(id=3, uuid=uuid4())
+ session.execute(
+ metadata.tables["version_transaction"].insert(),
+ [{"id": 10, "issued_at": datetime(2020, 1, 1)}],
+ )
+ for chart in (chart_a, chart_b):
+ session.execute(
+ metadata.tables["version_changes"].insert(),
+ {
+ "transaction_id": 10,
+ "entity_id": chart.id,
+ "entity_kind": "chart",
+ "kind": "__archive__",
+ },
+ )
+ session.execute(
+ metadata.tables["version_chart_archive_scope"].insert(),
+ {
+ "id": uuid4(),
+ "transaction_id": 10,
+ "chart_id": chart.id,
+ "chart_uuid": chart.uuid,
+ "dashboard_id": dashboard.id,
+ "dashboard_uuid": dashboard.uuid,
+ },
+ )
+ session.commit()
+ return chart_a, chart_b, dashboard
+
+
+def _delete(
+ session: Session, metadata: sa.MetaData, entity: SimpleNamespace, kind: str
+) -> int:
+ """Exercise the cleanup against SQL tables while stubbing model registration."""
+ model_name, shadow_name = (
+ ("Slice", "slices_version")
+ if kind == "chart"
+ else ("Dashboard", "dashboards_version")
+ )
+ model = type(model_name, (), {})
+ asset = model()
+ asset.id, asset.uuid = entity.id, entity.uuid
+ policy = SimpleNamespace(
+ entity_type=kind, version_shadow_names=[(shadow_name, "id")]
+ )
+ with (
+ patch.object(purge_cascade, "_version_tables_present", return_value=True),
+ patch.object(purge_cascade, "get_purge_policy", return_value=policy),
+ patch(
+ "sqlalchemy_continuum.version_class",
+ return_value=SimpleNamespace(__table__=metadata.tables[shadow_name]),
+ ),
+ ):
+ return purge_cascade._delete_version_history(session, asset, asset.id)
+
+
+def _count(session: Session, metadata: sa.MetaData, name: str) -> int:
+ """Return the number of surviving rows in a cleanup table."""
+ return session.execute(
+ sa.select(sa.func.count()).select_from(metadata.tables[name])
+ ).scalar_one()
+
+
+def test_archive_only_partial_purge_keeps_shared_transaction(
+ cleanup_db: tuple[Session, sa.MetaData],
+) -> None:
+ """Purge counts scopes and changes and sweeps only the last orphan."""
+ session, metadata = cleanup_db
+ chart_a, chart_b, _ = _seed(session, metadata)
+ assert _delete(session, metadata, chart_a, "chart") == 2
+ assert _count(session, metadata, "version_transaction") == 1
+ assert _count(session, metadata, "version_changes") == 1
+ assert _count(session, metadata, "version_chart_archive_scope") == 1
+ assert _delete(session, metadata, chart_b, "chart") == 2
+ assert _count(session, metadata, "version_transaction") == 0
+ assert _count(session, metadata, "version_chart_archive_scope") == 0
+
+
+def test_dashboard_purge_only_removes_exact_identity_scopes(
+ cleanup_db: tuple[Session, sa.MetaData],
+) -> None:
+ """Same UUID with a different ID and same ID with a different UUID are distinct."""
+ session, metadata = cleanup_db
+ chart, _, dashboard = _seed(session, metadata)
+ scope = metadata.tables["version_chart_archive_scope"]
+ for dashboard_id, dashboard_uuid in ((4, dashboard.uuid), (dashboard.id, uuid4())):
+ session.execute(
+ scope.insert(),
+ {
+ "id": uuid4(),
+ "transaction_id": 10,
+ "chart_id": chart.id,
+ "chart_uuid": chart.uuid,
+ "dashboard_id": dashboard_id,
+ "dashboard_uuid": dashboard_uuid,
+ },
+ )
+ assert _delete(session, metadata, dashboard, "dashboard") == 2
+ assert _count(session, metadata, "version_chart_archive_scope") == 2
+ assert _count(session, metadata, "version_changes") == 2
+ assert _count(session, metadata, "version_transaction") == 1
+
+
+def test_archive_scope_keeps_a_transaction_referenced_during_purge(
+ cleanup_db: tuple[Session, sa.MetaData],
+) -> None:
+ """A remaining scope is a reference even when no change or shadow survives."""
+ session, metadata = cleanup_db
+ chart, _, dashboard = _seed(session, metadata)
+ session.execute(metadata.tables["version_changes"].delete())
+ scope = metadata.tables["version_chart_archive_scope"]
+ session.execute(scope.delete().where(scope.c.chart_id != chart.id))
+ purge_cascade._sweep_orphan_transactions(
+ session,
+ metadata,
+ metadata.tables["version_transaction"],
+ metadata.tables["version_changes"],
+ {10},
+ scope,
+ )
+ assert _count(session, metadata, "version_transaction") == 1
+ assert _delete(session, metadata, dashboard, "dashboard") == 1
+ assert _count(session, metadata, "version_transaction") == 0
+
+
+def test_shadow_closing_endpoint_keeps_shared_transaction(
+ cleanup_db: tuple[Session, sa.MetaData],
+) -> None:
+ """Surviving shadow endpoints remain references after archive scopes disappear."""
+ session, metadata = cleanup_db
+ chart_a, chart_b, _ = _seed(session, metadata)
+ session.execute(metadata.tables["version_transaction"].insert(), {"id": 9})
+ session.execute(
+ metadata.tables["slices_version"].insert(),
+ {"id": 99, "transaction_id": 9, "end_transaction_id": 10},
+ )
+ _delete(session, metadata, chart_a, "chart")
+ _delete(session, metadata, chart_b, "chart")
+ assert _count(session, metadata, "version_transaction") == 2
+
+
+def test_disabled_retention_does_not_disable_managed_purge(
+ cleanup_db: tuple[Session, sa.MetaData],
+) -> None:
+ """Retention=0 skips scheduled history expiry, but managed purge still sweeps."""
+ session, metadata = cleanup_db
+ chart_a, chart_b, _ = _seed(session, metadata)
+ with patch.object(retention, "stats_logger_manager"):
+ assert retention._prune_old_versions_impl(retention_days=0) == {"skipped": 1}
+ _delete(session, metadata, chart_a, "chart")
+ _delete(session, metadata, chart_b, "chart")
+ assert _count(session, metadata, "version_transaction") == 0
+
+
+def test_retention_deletes_scopes_without_using_them_as_live_anchors(
+ cleanup_db: tuple[Session, sa.MetaData],
+) -> None:
+ """Expired archives disappear on metadata schemas even without scope FK cascades."""
+ session, metadata = cleanup_db
+ _seed(session, metadata)
+ tx = metadata.tables["version_transaction"]
+ session.execute(tx.insert(), {"id": 11, "issued_at": datetime(2020, 1, 1)})
+ parent = metadata.tables["slices_version"]
+ session.execute(parent.insert(), {"id": 7, "transaction_id": 11})
+ session.commit()
+ tables = retention.ShadowTables(
+ parent=[parent],
+ child=[],
+ m2m=None,
+ transaction=tx,
+ archive_scope=metadata.tables["version_chart_archive_scope"],
+ )
+ with patch.object(retention, "db", SimpleNamespace(engine=session.get_bind())):
+ result = retention._run_prune_pass(datetime(2026, 1, 1), tables)
+ assert result["pruned_transactions"] == 1
+ assert result["pruned_archive_scopes"] == 2
+ assert _count(session, metadata, "version_chart_archive_scope") == 0
+ assert session.execute(sa.select(tx.c.id)).scalars().all() == [11]
+ assert _count(session, metadata, "slices_version") == 1
+
+
+def test_reused_chart_id_does_not_strand_deleted_archive_scopes(
+ cleanup_db: tuple[Session, sa.MetaData],
+) -> None:
+ """Purge also removes projections of older canonical events deleted by ID."""
+ session, metadata = cleanup_db
+ chart, _, dashboard = _seed(session, metadata)
+ session.execute(metadata.tables["version_transaction"].insert(), {"id": 9})
+ session.execute(
+ metadata.tables["version_changes"].insert(),
+ {
+ "transaction_id": 9,
+ "entity_kind": "chart",
+ "entity_id": chart.id,
+ "kind": "__archive__",
+ },
+ )
+ session.execute(
+ metadata.tables["version_chart_archive_scope"].insert(),
+ {
+ "id": uuid4(),
+ "transaction_id": 9,
+ "chart_id": chart.id,
+ "chart_uuid": uuid4(),
+ "dashboard_id": dashboard.id,
+ "dashboard_uuid": dashboard.uuid,
+ },
+ )
+ assert _delete(session, metadata, chart, "chart") == 4
+ assert _count(session, metadata, "version_chart_archive_scope") == 1
+ assert session.execute(
+ sa.select(metadata.tables["version_transaction"].c.id)
+ ).scalars().all() == [10]
+
+
+def test_purge_collects_closing_transaction_as_an_orphan_candidate(
+ cleanup_db: tuple[Session, sa.MetaData],
+) -> None:
+ """A transaction referenced only as the purged shadow's end must be swept."""
+ session, metadata = cleanup_db
+ chart = SimpleNamespace(id=1, uuid=uuid4())
+ session.execute(
+ metadata.tables["version_transaction"].insert(), [{"id": 10}, {"id": 11}]
+ )
+ session.execute(
+ metadata.tables["slices_version"].insert(),
+ {"id": chart.id, "transaction_id": 10, "end_transaction_id": 11},
+ )
+ assert _delete(session, metadata, chart, "chart") == 1
+ assert _count(session, metadata, "version_transaction") == 0
diff --git a/tests/unit_tests/versioning/test_capture_gap_restore.py b/tests/unit_tests/versioning/test_capture_gap_restore.py
index b1e9bea1e998..db3492909c63 100644
--- a/tests/unit_tests/versioning/test_capture_gap_restore.py
+++ b/tests/unit_tests/versioning/test_capture_gap_restore.py
@@ -63,7 +63,8 @@ def history_counts(session: Session) -> dict[str, int]:
table.name: session.scalar(sa.select(sa.func.count()).select_from(table))
for table in Model.metadata.tables.values()
if table.name.endswith("_version")
- or table.name in {"version_transaction", "version_changes"}
+ or table.name
+ in {"version_transaction", "version_changes", "version_chart_archive_scope"}
}
diff --git a/tests/unit_tests/versioning/test_db_errors.py b/tests/unit_tests/versioning/test_db_errors.py
index de6bdb170fd7..7d930fb20e37 100644
--- a/tests/unit_tests/versioning/test_db_errors.py
+++ b/tests/unit_tests/versioning/test_db_errors.py
@@ -92,6 +92,14 @@ def test_mysql_no_such_table_is_missing_table() -> None:
assert is_missing_table_error(error) is True
+def test_mysql_missing_table_with_sqlstate_uses_errno() -> None:
+ """MySQL drivers exposing both diagnostics retain their errno semantics."""
+ error = OperationalError(
+ "SELECT 1", {}, _FakeDriverError(1146, "missing table", sqlstate="42S02")
+ )
+ assert is_missing_table_error(error)
+
+
def test_mysql_lock_wait_timeout_is_not_missing_table() -> None:
error = _wrap(
OperationalError,
@@ -371,3 +379,75 @@ def test_foreign_key_phrase_in_sql_is_not_a_violation() -> None:
def test_foreign_key_violation_none_input() -> None:
assert is_foreign_key_violation(None) is False
+
+
+@pytest.mark.parametrize(
+ "args,attrs,expected",
+ [
+ ((1213, "transaction rolled back"), {"sqlstate": "40001"}, True),
+ ((1305, "savepoint missing"), {"sqlstate": "42000"}, True),
+ ((1205, "statement timeout"), {"sqlstate": "3B001"}, False),
+ ((1146, "missing table"), {}, False),
+ (("savepoint missing",), {"pgcode": "3B001"}, True),
+ (("savepoint missing",), {"sqlstate": "3B001"}, True),
+ (("deadlock",), {"pgcode": "40P01"}, False),
+ (("serialization failure",), {"pgcode": "40001"}, False),
+ (("1305 savepoint missing",), {}, False),
+ ],
+)
+def test_lost_transaction_uses_structured_driver_diagnostics(
+ args: tuple[object, ...], attrs: dict[str, str], expected: bool
+) -> None:
+ """Only transaction-loss evidence makes optional statement recovery fatal."""
+ from superset.versioning.db_errors import is_lost_transaction_error
+
+ error = _wrap(OperationalError, _FakeDriverError(*args, **attrs))
+ assert is_lost_transaction_error(error) is expected
+
+
+def test_lost_transaction_follows_exception_chains_without_looping() -> None:
+ """Context-manager cleanup can obscure the original transaction loss."""
+ from superset.versioning.db_errors import is_lost_transaction_error
+
+ original = _wrap(OperationalError, _FakeDriverError(1213, "deadlock"))
+ cleanup = RuntimeError("cleanup failed")
+ cleanup.__cause__ = original
+ original.__context__ = cleanup
+ assert is_lost_transaction_error(cleanup)
+ cleanup.__cause__ = ValueError("ordinary computation failure")
+ cleanup.__context__ = cleanup
+ assert not is_lost_transaction_error(cleanup)
+ assert not is_lost_transaction_error(None)
+
+
+def test_lost_transaction_invalidation_is_fatal_without_driver_code() -> None:
+ """A discarded connection cannot preserve the caller's transaction."""
+ from superset.versioning.db_errors import is_lost_transaction_error
+
+ error = OperationalError(
+ "SELECT 1", {}, Exception("disconnect"), connection_invalidated=True
+ )
+ assert is_lost_transaction_error(error)
+ outer = ValueError("recovery failed")
+ outer.__cause__ = error
+ assert is_lost_transaction_error(outer)
+
+
+@pytest.mark.parametrize(
+ "error",
+ [
+ KeyError(1213),
+ ValueError(1305),
+ _FakeDriverError(1213, sqlstate="40001"),
+ _FakeDriverError("missing savepoint", sqlstate="3B001"),
+ _FakeDriverError("not a DBAPI wrapper", orig=_FakeDriverError(1305)),
+ _FakeDriverError("not a DBAPI wrapper", connection_invalidated=True),
+ ],
+)
+def test_python_exception_arguments_are_not_transaction_loss(
+ error: BaseException,
+) -> None:
+ """Only a DBAPI wrapper can establish that numbers are driver error codes."""
+ from superset.versioning.db_errors import is_lost_transaction_error
+
+ assert not is_lost_transaction_error(error)
diff --git a/tests/unit_tests/versioning/test_lifecycle.py b/tests/unit_tests/versioning/test_lifecycle.py
new file mode 100644
index 000000000000..dd63208a6d31
--- /dev/null
+++ b/tests/unit_tests/versioning/test_lifecycle.py
@@ -0,0 +1,913 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""Chart archive capture through the application's native ORM listeners."""
+
+from datetime import datetime
+from typing import Any
+
+import pytest
+import sqlalchemy as sa
+from sqlalchemy.orm import Session
+from sqlalchemy_continuum import version_class
+
+from superset.app import SupersetApp
+from superset.models.dashboard import Dashboard
+from superset.models.slice import Slice
+from superset.versioning.changes.table import version_changes_table
+
+pytestmark = pytest.mark.parametrize(
+ "app", [{"SQLALCHEMY_DATABASE_URI": "sqlite://"}], indirect=True
+)
+
+
+def archives(session: Session) -> list[dict[str, Any]]:
+ """Read only canonical archive announcements."""
+ return [
+ dict(row)
+ for row in session.execute(
+ sa.select(version_changes_table).where(
+ version_changes_table.c.kind == "__archive__"
+ )
+ ).mappings()
+ ]
+
+
+def test_archive_without_content_transaction(capture_session: Session) -> None:
+ """Archive writes its own activity transaction without a content snapshot."""
+ chart = Slice(slice_name="original", viz_type="table", params="{}")
+ dashboard = Dashboard(dashboard_title="dashboard", slices=[chart])
+ capture_session.add(dashboard)
+ capture_session.commit()
+ before = capture_session.query(version_class(Slice)).count()
+ chart.deleted_at = datetime(2026, 1, 1)
+ capture_session.commit()
+ records = archives(capture_session)
+ assert len(records) == 1
+ assert records[0]["path"] == ["deleted_at"]
+ assert records[0]["to_value"] == {
+ "entity_uuid": str(chart.uuid),
+ "entity_name": "original",
+ }
+ assert capture_session.query(version_class(Slice)).count() == before
+
+
+@pytest.mark.parametrize("attach", [False, True])
+def test_capture_gap_membership(
+ capture_session: Session,
+ app: SupersetApp,
+ monkeypatch: pytest.MonkeyPatch,
+ attach: bool,
+) -> None:
+ """Live membership at archive time supersedes stale historical windows."""
+ chart = Slice(slice_name="chart", viz_type="table", params="{}")
+ dashboard = Dashboard(dashboard_title="dashboard", slices=[] if attach else [chart])
+ capture_session.add_all([chart, dashboard])
+ capture_session.commit()
+ monkeypatch.setitem(
+ app.config, "VERSIONING_CAPTURE_PREDICATE", lambda session: False
+ )
+ dashboard.slices = [chart] if attach else []
+ capture_session.commit()
+ monkeypatch.setitem(
+ app.config, "VERSIONING_CAPTURE_PREDICATE", lambda session: True
+ )
+ chart.deleted_at = datetime(2026, 1, 1)
+ capture_session.commit()
+ from superset.versioning.lifecycle_table import version_chart_archive_scope_table
+
+ scopes = (
+ capture_session.execute(sa.select(version_chart_archive_scope_table))
+ .mappings()
+ .all()
+ )
+ assert len(scopes) == int(attach)
+ assert len(archives(capture_session)) == 1
+
+
+@pytest.mark.parametrize(
+ "steps,expected",
+ [
+ ([True], 1),
+ ([True, True], 1),
+ ([True, False], 0),
+ ([True, False, True], 1),
+ ],
+)
+def test_net_archive_transitions(
+ capture_session: Session, steps: list[bool], expected: int
+) -> None:
+ """Only the initial-to-final transition survives repeated flushes."""
+ chart = Slice(slice_name="chart", viz_type="table", params="{}")
+ capture_session.add(chart)
+ capture_session.commit()
+ for archived in steps:
+ chart.deleted_at = datetime(2026, 1, 1) if archived else None
+ capture_session.flush()
+ capture_session.commit()
+ assert len(archives(capture_session)) == expected
+
+
+@pytest.mark.parametrize("initially_archived", [False, True])
+def test_insert_then_archive(
+ capture_session: Session, initially_archived: bool
+) -> None:
+ """An inserted active row is observed only after its first flush."""
+ chart = Slice(
+ slice_name="chart",
+ viz_type="table",
+ params="{}",
+ deleted_at=datetime(2026, 1, 1) if initially_archived else None,
+ )
+ capture_session.add(chart)
+ capture_session.flush()
+ chart.deleted_at = datetime(2026, 1, 2)
+ capture_session.commit()
+ assert len(archives(capture_session)) == int(not initially_archived)
+
+
+@pytest.mark.parametrize(
+ "nested,rollback", [(False, True), (True, True), (True, False)]
+)
+def test_archive_rollback(
+ capture_session: Session, nested: bool, rollback: bool
+) -> None:
+ """Nested rollback drops transitions while successful nested work is retained."""
+ chart = Slice(slice_name="chart", viz_type="table", params="{}")
+ capture_session.add(chart)
+ capture_session.commit()
+ transaction = capture_session.begin_nested() if nested else capture_session.begin()
+ chart.deleted_at = datetime(2026, 1, 1)
+ capture_session.flush()
+ if rollback:
+ transaction.rollback()
+ else:
+ transaction.commit()
+ capture_session.commit()
+ assert len(archives(capture_session)) == int(not rollback)
+
+
+@pytest.mark.parametrize("denied", [False, True])
+def test_untracked_dashboard_needs_no_baseline(
+ capture_session: Session,
+ app: SupersetApp,
+ monkeypatch: pytest.MonkeyPatch,
+ denied: bool,
+) -> None:
+ """Capture-disabled creation needs no dashboard baseline to record an archive."""
+ monkeypatch.setitem(
+ app.config, "VERSIONING_CAPTURE_PREDICATE", lambda session: False
+ )
+ chart = Slice(slice_name="chart", viz_type="table", params="{}")
+ dashboard = Dashboard(dashboard_title="dashboard", slices=[chart])
+ capture_session.add(dashboard)
+ capture_session.commit()
+ monkeypatch.setitem(
+ app.config, "VERSIONING_CAPTURE_PREDICATE", lambda session: not denied
+ )
+ chart.deleted_at = datetime(2026, 1, 1)
+ capture_session.commit()
+ assert len(archives(capture_session)) == int(not denied)
+ assert capture_session.query(version_class(Dashboard)).count() == 0
+
+
+def test_archive_membership_is_immutable(capture_session: Session) -> None:
+ """Archived dashboards participate; later detach/recovery cannot rewrite scope."""
+ from superset.versioning.lifecycle_table import version_chart_archive_scope_table
+
+ chart = Slice(slice_name="chart", viz_type="table", params="{}")
+ dashboard = Dashboard(dashboard_title="dashboard", slices=[chart])
+ detached = Dashboard(dashboard_title="detached", slices=[chart])
+ capture_session.add_all([dashboard, detached])
+ capture_session.commit()
+ detached.slices = []
+ dashboard.deleted_at = datetime(2026, 1, 1)
+ chart.deleted_at = datetime(2026, 1, 1)
+ capture_session.commit()
+ before = capture_session.execute(sa.select(version_chart_archive_scope_table)).all()
+ assert len(before) == 1
+ assert before[0].dashboard_id == dashboard.id
+ dashboard.deleted_at = None
+ chart.deleted_at = None
+ dashboard.slices = []
+ capture_session.commit()
+ assert (
+ capture_session.execute(sa.select(version_chart_archive_scope_table)).all()
+ == before
+ )
+
+
+@pytest.mark.parametrize("fail_all", [False, True])
+def test_chart_failure_isolation(
+ capture_session: Session,
+ monkeypatch: pytest.MonkeyPatch,
+ fail_all: bool,
+ caplog: pytest.LogCaptureFixture,
+) -> None:
+ """A rolled-back chart loses all scopes; all failures leave no transaction."""
+ from sqlalchemy_continuum import versioning_manager
+
+ from superset.versioning import lifecycle
+ from superset.versioning.lifecycle_table import version_chart_archive_scope_table
+
+ charts = [Slice(slice_name=str(i), viz_type="table", params="{}") for i in range(2)]
+ dashboard = Dashboard(dashboard_title="dashboard", slices=charts)
+ capture_session.add(dashboard)
+ capture_session.commit()
+ transaction_table = versioning_manager.transaction_cls.__table__
+ before = capture_session.scalar(
+ sa.select(sa.func.count()).select_from(transaction_table)
+ )
+ write = lifecycle._write_archive
+
+ def fail_after_insert(
+ connection: Any, transaction_id: int, archive: Any, memberships: Any
+ ) -> int:
+ """Exercise rollback after both the event and scope have been inserted."""
+ count = write(connection, transaction_id, archive, memberships)
+ if fail_all or archive.chart_id == charts[0].id:
+ raise ValueError("injected optional failure")
+ return count
+
+ monkeypatch.setattr(lifecycle, "_write_archive", fail_after_insert)
+ for chart in charts:
+ chart.deleted_at = datetime(2026, 1, 1)
+ capture_session.commit()
+ assert len(archives(capture_session)) == int(not fail_all)
+ assert "chart archive capture failed" in caplog.text
+ assert capture_session.scalar(
+ sa.select(sa.func.count()).select_from(version_chart_archive_scope_table)
+ ) == int(not fail_all)
+ assert capture_session.scalar(
+ sa.select(sa.func.count()).select_from(transaction_table)
+ ) == before + int(not fail_all)
+
+
+@pytest.mark.parametrize(
+ "dashboard_count,chart_count,archive_count", [(20, 30, 5), (100, 10, 10)]
+)
+def test_lifecycle_query_budget(
+ capture_session: Session, dashboard_count: int, chart_count: int, archive_count: int
+) -> None:
+ """Membership reads scale with archived charts rather than dashboard contents."""
+ charts = [
+ Slice(slice_name=str(i), viz_type="table", params="{}")
+ for i in range(chart_count)
+ ]
+ dashboards = [
+ Dashboard(dashboard_title=str(i), slices=charts) for i in range(dashboard_count)
+ ]
+ capture_session.add_all(dashboards)
+ capture_session.commit()
+ before = capture_session.query(version_class(Dashboard)).count()
+ for chart in charts[:archive_count]:
+ chart.deleted_at = datetime(2026, 1, 1)
+ capture_session.flush()
+ statements: list[str] = []
+ connection = capture_session.connection()
+
+ def track_statement(
+ _conn: Any,
+ _cursor: Any,
+ statement: str,
+ _parameters: Any,
+ _context: Any,
+ _executemany: bool,
+ ) -> None:
+ """Count lifecycle SQL after the application flush."""
+ statements.append(statement)
+
+ sa.event.listen(connection, "before_cursor_execute", track_statement)
+ capture_session.commit()
+ assert len(statements) < 100
+ assert len(archives(capture_session)) == archive_count
+ assert capture_session.query(version_class(Dashboard)).count() == before
+
+
+def test_mixed_content_and_archive_use_separate_transactions(
+ capture_session: Session,
+) -> None:
+ """Lifecycle announcements do not contaminate content snapshots or actions."""
+ chart = Slice(slice_name="chart", viz_type="table", params="{}")
+ capture_session.add(chart)
+ capture_session.commit()
+ chart.slice_name = "final"
+ chart.deleted_at = datetime(2026, 1, 1)
+ capture_session.commit()
+ record = archives(capture_session)[0]
+ assert record["to_value"]["entity_name"] == "final"
+ assert (
+ capture_session.query(version_class(Slice))
+ .filter_by(transaction_id=record["transaction_id"])
+ .count()
+ == 0
+ )
+ assert capture_session.query(version_class(Slice)).count() == 2
+
+
+def test_lifecycle_actor_and_capture_timestamp(
+ capture_session: Session, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """Lifecycle attribution uses the current actor and UTC capture time."""
+ from sqlalchemy_continuum import versioning_manager
+
+ from superset.versioning import lifecycle
+
+ chart = Slice(slice_name="chart", viz_type="table", params="{}")
+ capture_session.add(chart)
+ capture_session.commit()
+ timestamp = datetime(2026, 10, 1)
+ monkeypatch.setattr(
+ lifecycle,
+ "transaction_actor_args",
+ lambda: {"user_id": 42, "remote_addr": "127.0.0.1"},
+ )
+ monkeypatch.setattr(lifecycle, "naive_utcnow", lambda: timestamp)
+ chart.deleted_at = datetime(2026, 1, 1)
+ capture_session.commit()
+ transaction = versioning_manager.transaction_cls.__table__
+ row = capture_session.execute(
+ sa.select(transaction).where(
+ transaction.c.id == archives(capture_session)[0]["transaction_id"]
+ )
+ ).one()
+ assert row.user_id == 42
+ assert row.remote_addr == "127.0.0.1"
+ assert row.issued_at == timestamp
+ assert row.action_kind is None
+
+
+def test_missing_scope_table_preserves_archive(
+ capture_session: Session,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """A pre-migration write failure is quiet but counted and preserves user work."""
+ from unittest.mock import MagicMock
+
+ from superset.versioning import lifecycle
+ from superset.versioning.lifecycle_table import version_chart_archive_scope_table
+
+ chart = Slice(slice_name="chart", viz_type="table", params="{}")
+ dashboard = Dashboard(dashboard_title="dashboard", slices=[chart])
+ capture_session.add(dashboard)
+ capture_session.commit()
+ version_chart_archive_scope_table.drop(capture_session.connection())
+ log = MagicMock()
+ metric = MagicMock()
+ monkeypatch.setattr(lifecycle.logger, "exception", log)
+ monkeypatch.setattr(lifecycle, "incr_capture_error", metric)
+ chart.deleted_at = datetime(2026, 1, 1)
+ capture_session.commit()
+ assert chart.deleted_at == datetime(2026, 1, 1)
+ assert archives(capture_session) == []
+ log.assert_not_called()
+ metric.assert_called_once_with("lifecycle_chart")
+ version_chart_archive_scope_table.create(capture_session.connection())
+ capture_session.commit()
+
+
+@pytest.mark.parametrize("failure", ["invalidated", "rollback", "begin", "release"])
+def test_uncertain_savepoints_are_fatal(failure: str) -> None:
+ """Unsafe connection boundaries fail instead of permitting later lifecycle SQL."""
+ from unittest.mock import MagicMock
+
+ from superset.versioning.lifecycle import (
+ begin_capture_savepoint,
+ LifecycleCaptureFatalError,
+ release_capture_savepoint,
+ rollback_capture_savepoint,
+ )
+
+ connection = MagicMock(invalidated=False, closed=False)
+ outer = MagicMock(is_active=True)
+ savepoint = MagicMock(is_active=True)
+ connection.get_transaction.return_value = outer
+ original = ValueError("optional metadata failure")
+ if failure == "invalidated":
+ connection.invalidated = True
+ elif failure == "rollback":
+ savepoint.rollback.side_effect = RuntimeError("missing savepoint")
+ elif failure == "begin":
+ connection.begin_nested.side_effect = RuntimeError("missing transaction")
+ else:
+ savepoint.commit.side_effect = RuntimeError("missing savepoint")
+
+ def recover() -> None:
+ """Exercise the selected boundary failure."""
+ if failure == "begin":
+ begin_capture_savepoint(connection, outer)
+ elif failure == "release":
+ release_capture_savepoint(connection, savepoint, outer)
+ else:
+ rollback_capture_savepoint(connection, savepoint, outer, original)
+
+ with pytest.raises(LifecycleCaptureFatalError):
+ recover()
+ if failure == "invalidated":
+ savepoint.rollback.assert_not_called()
+
+
+def test_manager_kill_switch_prevents_lifecycle(
+ capture_session: Session, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """The finalizer obeys the process-wide Continuum shutdown switch."""
+ from sqlalchemy_continuum import versioning_manager
+
+ chart = Slice(slice_name="chart", viz_type="table", params="{}")
+ capture_session.add(chart)
+ capture_session.commit()
+ monkeypatch.setitem(versioning_manager.options, "versioning", False)
+ chart.deleted_at = datetime(2026, 1, 1)
+ capture_session.commit()
+ assert archives(capture_session) == []
+
+
+def test_archived_marker_rewrite_is_not_an_archive(capture_session: Session) -> None:
+ """An already archived chart has no active-to-archived transition."""
+ chart = Slice(
+ slice_name="chart",
+ viz_type="table",
+ params="{}",
+ deleted_at=datetime(2026, 1, 1),
+ )
+ capture_session.add(chart)
+ capture_session.commit()
+ chart.deleted_at = datetime(2026, 1, 2)
+ capture_session.commit()
+ assert archives(capture_session) == []
+
+
+@pytest.mark.parametrize("deferred", [False, True])
+def test_archive_baseline_attribution(
+ capture_session: Session,
+ app: SupersetApp,
+ monkeypatch: pytest.MonkeyPatch,
+ deferred: bool,
+) -> None:
+ """A deferred baseline credits stored archived attribution without backfill."""
+ from sqlalchemy_continuum import versioning_manager
+
+ monkeypatch.setitem(
+ app.config, "VERSIONING_CAPTURE_PREDICATE", lambda session: False
+ )
+ chart = Slice(slice_name="chart", viz_type="table", params="{}")
+ capture_session.add(chart)
+ capture_session.commit()
+ from flask_appbuilder.security.sqla.models import User
+
+ capture_session.add_all(
+ [
+ User(
+ id=11,
+ username="editor",
+ first_name="Content",
+ last_name="Editor",
+ email="editor@example.com",
+ ),
+ User(
+ id=22,
+ username="archiver",
+ first_name="Chart",
+ last_name="Archiver",
+ email="archiver@example.com",
+ ),
+ ]
+ )
+ capture_session.commit()
+ capture_session.execute(
+ sa.update(Slice.__table__).where(Slice.id == chart.id).values(changed_by_fk=11)
+ )
+ capture_session.commit()
+ capture_session.expire_all()
+ monkeypatch.setitem(
+ app.config, "VERSIONING_CAPTURE_PREDICATE", lambda session: not deferred
+ )
+ chart.deleted_at = datetime(2026, 1, 1)
+ chart.changed_by_fk = 22
+ capture_session.commit()
+ if deferred:
+ monkeypatch.setitem(
+ app.config, "VERSIONING_CAPTURE_PREDICATE", lambda session: True
+ )
+ chart.slice_name = "first captured edit"
+ capture_session.commit()
+ transaction = versioning_manager.transaction_cls.__table__
+ actor = capture_session.scalar(
+ sa.select(transaction.c.user_id).where(transaction.c.action_kind == "baseline")
+ )
+ assert actor == (22 if deferred else 11)
+ assert len(archives(capture_session)) == int(not deferred)
+
+
+def test_membership_chunk_failure_skips_complete_chunk(
+ capture_session: Session,
+ monkeypatch: pytest.MonkeyPatch,
+ caplog: pytest.LogCaptureFixture,
+) -> None:
+ """Partially read destinations never produce a misleading canonical event."""
+ from superset.versioning import lifecycle
+
+ charts = [Slice(slice_name=str(i), viz_type="table", params="{}") for i in range(3)]
+ dashboard = Dashboard(dashboard_title="dashboard", slices=charts)
+ capture_session.add(dashboard)
+ capture_session.commit()
+ monkeypatch.setattr(lifecycle, "_BATCH_SIZE", 2)
+ memberships = lifecycle._memberships
+ calls = 0
+
+ def fail_first_chunk(connection: Any, chart_ids: list[int]) -> Any:
+ """Fail after reading an entire chunk to exercise atomic discard."""
+ nonlocal calls
+ calls += 1
+ result = memberships(connection, chart_ids)
+ if calls == 1:
+ raise ValueError("injected membership read failure")
+ return result
+
+ monkeypatch.setattr(lifecycle, "_memberships", fail_first_chunk)
+ for chart in charts:
+ chart.deleted_at = datetime(2026, 1, 1)
+ capture_session.commit()
+ assert len(archives(capture_session)) == 1
+ assert calls == 2
+ assert "archive membership capture failed" in caplog.text
+
+
+@pytest.mark.parametrize("detached", [False, True])
+def test_nonpersistent_archive_is_not_captured(
+ capture_session: Session, detached: bool
+) -> None:
+ """Deleted and detached instances cannot produce surviving archive events."""
+ chart = Slice(slice_name="chart", viz_type="table", params="{}")
+ capture_session.add(chart)
+ capture_session.commit()
+ chart.deleted_at = datetime(2026, 1, 1)
+ capture_session.flush()
+ if detached:
+ capture_session.expunge(chart)
+ else:
+ capture_session.delete(chart)
+ capture_session.commit()
+ assert archives(capture_session) == []
+
+
+@pytest.mark.parametrize("boundary", ["rollback", "release"])
+def test_fatal_chart_boundary_stops_the_capture_loop(
+ monkeypatch: pytest.MonkeyPatch, boundary: str
+) -> None:
+ """No later chart is attempted after a lost savepoint, preserving both errors."""
+ from unittest.mock import MagicMock
+ from uuid import uuid4
+
+ from superset.versioning import lifecycle
+
+ connection = MagicMock(invalidated=False, closed=False)
+ outer = MagicMock(is_active=True)
+ connection.get_transaction.return_value = outer
+ membership_savepoint = MagicMock(is_active=True)
+ chart_savepoint = MagicMock(is_active=True)
+ connection.begin_nested.side_effect = [membership_savepoint, chart_savepoint]
+ monkeypatch.setattr(
+ lifecycle, "_memberships", lambda connection, chart_ids: {1: [], 2: []}
+ )
+ original = ValueError("chart insert failed")
+ failed_boundary = RuntimeError("savepoint lost")
+ write = MagicMock(return_value=0)
+ monkeypatch.setattr(lifecycle, "_write_archive", write)
+ if boundary == "rollback":
+ write.side_effect = original
+ chart_savepoint.rollback.side_effect = failed_boundary
+ else:
+ chart_savepoint.commit.side_effect = failed_boundary
+ charts = [lifecycle.ChartArchive(i, uuid4(), "chart") for i in (1, 2)]
+ with pytest.raises(lifecycle.LifecycleCaptureFatalError) as error:
+ lifecycle._capture_chunk(connection, outer, 1, charts)
+ assert write.call_count == 1
+ assert connection.begin_nested.call_count == 2
+ assert error.value.__cause__ is failed_boundary
+ if boundary == "rollback":
+ assert failed_boundary.__cause__ is original
+
+
+def test_lifecycle_import_before_app_initialization() -> None:
+ """Standalone migration and backend tooling can import capture without a cycle."""
+ import subprocess
+ import sys
+
+ subprocess.run( # noqa: S603 — fixed interpreter and import-only command
+ [sys.executable, "-c", "import superset.versioning.lifecycle"],
+ check=True,
+ capture_output=True,
+ timeout=30,
+ )
+
+
+@pytest.mark.parametrize("site", ["stamp", "persist"])
+def test_lost_content_savepoint_prevents_lifecycle_capture(
+ capture_session: Session, monkeypatch: pytest.MonkeyPatch, site: str
+) -> None:
+ """Mixed content/archive commits stop before lifecycle SQL after MySQL1305."""
+ from unittest.mock import MagicMock
+
+ from superset.versioning import lifecycle
+ from superset.versioning.changes import listener
+
+ chart = Slice(slice_name="before", viz_type="table", params="{}")
+ capture_session.add(chart)
+ capture_session.commit()
+ error = sa.exc.OperationalError(
+ "SAVEPOINT", {}, Exception(1305, "missing savepoint")
+ )
+ monkeypatch.setattr(
+ listener,
+ "_write_action_kind" if site == "stamp" else "bulk_insert_records",
+ MagicMock(side_effect=error),
+ )
+ capture = MagicMock()
+ monkeypatch.setattr(lifecycle, "capture_chart_archives", capture)
+ chart.slice_name = "after"
+ chart.deleted_at = datetime(2026, 1, 1)
+ capture_session.info[listener.ACTION_KIND_KEY] = listener.ACTION_KIND_RESTORE
+ with pytest.raises(sa.exc.OperationalError) as raised:
+ capture_session.commit()
+ assert raised.value is error
+ capture.assert_not_called()
+ capture_session.rollback()
+ assert chart.slice_name == "before"
+ assert chart.deleted_at is None
+ assert archives(capture_session) == []
+
+
+@pytest.mark.parametrize("code", [1305, "3B001"])
+def test_missing_savepoint_backstop_after_successful_rollback(code: int | str) -> None:
+ """A successful rollback cannot override a driver-reported missing savepoint."""
+ from unittest.mock import MagicMock
+
+ from superset.versioning.lifecycle import (
+ LifecycleCaptureFatalError,
+ rollback_capture_savepoint,
+ )
+
+ connection = MagicMock(invalidated=False, closed=False)
+ outer = MagicMock(is_active=True)
+ savepoint = MagicMock(is_active=True)
+ connection.get_transaction.return_value = outer
+ diagnostic = Exception(code)
+ if isinstance(code, str):
+ diagnostic.sqlstate = code # type: ignore[attr-defined]
+ original = sa.exc.OperationalError("SELECT", {}, diagnostic)
+ with pytest.raises(LifecycleCaptureFatalError) as raised:
+ rollback_capture_savepoint(connection, savepoint, outer, original)
+ savepoint.rollback.assert_called_once()
+ assert raised.value.__cause__ is original
+
+
+def test_finalizer_manager_kill_switch_does_not_evaluate_capture_policy(
+ capture_session: Session, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """Direct finalization stops even when a retained unit would allow capture."""
+ from unittest.mock import MagicMock
+
+ from sqlalchemy_continuum import versioning_manager
+
+ from superset.versioning.changes import listener
+
+ monkeypatch.setitem(versioning_manager.options, "versioning", False)
+ policy = MagicMock(return_value=True)
+ flush = MagicMock()
+ lifecycle = MagicMock()
+ monkeypatch.setattr(listener, "capture_for_write", policy)
+ monkeypatch.setattr(capture_session, "flush", flush)
+ monkeypatch.setattr(listener, "_capture_lifecycle", lifecycle)
+ listener.finalize_change_records(capture_session)
+ policy.assert_not_called()
+ flush.assert_not_called()
+ lifecycle.assert_not_called()
+
+
+def test_expired_hard_deleted_chart_does_not_break_commit(
+ capture_session: Session,
+ caplog: pytest.LogCaptureFixture,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """A Core deletion after retained archive state drops optional collection."""
+ from unittest.mock import MagicMock
+
+ from superset.versioning.changes import listener
+
+ chart = Slice(slice_name="chart", viz_type="table", params="{}")
+ capture_session.add(chart)
+ capture_session.commit()
+ chart_id = chart.id
+ chart.deleted_at = datetime(2026, 1, 1)
+ capture_session.flush()
+ capture_session.expire(chart)
+ capture_session.connection().execute(
+ sa.delete(Slice.__table__).where(Slice.__table__.c.id == chart_id)
+ )
+ metric = MagicMock()
+ monkeypatch.setattr(listener, "incr_capture_error", metric)
+ capture_session.commit()
+ assert archives(capture_session) == []
+ metric.assert_any_call("lifecycle_collect")
+ assert "archive transition collection failed" in caplog.text
+
+
+@pytest.mark.parametrize("failure", ["lost", "invalidated", "statement", "fatal"])
+def test_unsafe_collection_failures_propagate(
+ capture_session: Session, monkeypatch: pytest.MonkeyPatch, failure: str
+) -> None:
+ """Collection has no savepoint, so database failures cannot be swallowed."""
+ from unittest.mock import MagicMock
+
+ from superset.versioning import lifecycle
+ from superset.versioning.changes import listener
+
+ if failure == "fatal":
+ error = lifecycle.LifecycleCaptureFatalError("failed rollback")
+ else:
+ error = sa.exc.OperationalError(
+ "SELECT",
+ {},
+ Exception(1305 if failure == "lost" else "failed read"),
+ connection_invalidated=failure == "invalidated",
+ )
+ monkeypatch.setattr(
+ lifecycle, "collect_chart_archives", MagicMock(side_effect=error)
+ )
+ capture = MagicMock()
+ monkeypatch.setattr(lifecycle, "capture_chart_archives", capture)
+ with pytest.raises(type(error)) as raised:
+ listener._capture_lifecycle(capture_session, {})
+ assert raised.value is error
+ capture.assert_not_called()
+
+
+def test_fatal_capture_is_handled_by_chart_command_transaction(
+ capture_session: Session, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """Fatal capture rolls back and maps to the chart command's public error."""
+ from superset.commands.chart.delete import DeleteChartCommand
+ from superset.commands.chart.exceptions import ChartDeleteFailedError
+ from superset.daos.chart import ChartDAO
+ from superset.versioning.lifecycle import LifecycleCaptureFatalError
+
+ chart = Slice(slice_name="chart", viz_type="table", params="{}")
+ capture_session.add(chart)
+ capture_session.commit()
+ command = DeleteChartCommand([chart.id])
+
+ def validate() -> None:
+ """Use the persisted chart without unrelated authorization setup."""
+ command._models = [chart]
+
+ def delete(_models: list[Slice]) -> None:
+ """Mutate caller data before the failed metadata boundary."""
+ chart.deleted_at = datetime(2026, 1, 1)
+
+ def fail_commit() -> None:
+ """Model the fatal database boundary raised during commit finalization."""
+ raise LifecycleCaptureFatalError("private savepoint state")
+
+ monkeypatch.setattr(command, "validate", validate)
+ monkeypatch.setattr(ChartDAO, "delete", delete)
+ from superset.extensions import db
+
+ monkeypatch.setattr(db.session, "commit", fail_commit)
+ with pytest.raises(ChartDeleteFailedError) as raised:
+ command.run()
+ assert isinstance(raised.value.__cause__, LifecycleCaptureFatalError)
+ assert chart.deleted_at is None
+ assert "private savepoint" not in str(raised.value)
+
+
+def test_recoverable_lifecycle_allocation_failure_is_logged(
+ capture_session: Session,
+ monkeypatch: pytest.MonkeyPatch,
+ caplog: pytest.LogCaptureFixture,
+) -> None:
+ """Optional allocation failures remain visible without a metrics backend."""
+ from unittest.mock import MagicMock
+
+ from superset.versioning import lifecycle
+
+ chart = Slice(slice_name="chart", viz_type="table", params="{}")
+ capture_session.add(chart)
+ capture_session.commit()
+ monkeypatch.setattr(
+ lifecycle,
+ "transaction_actor_args",
+ MagicMock(side_effect=ValueError("invalid actor")),
+ )
+ metric = MagicMock()
+ monkeypatch.setattr(lifecycle, "incr_capture_error", metric)
+ chart.deleted_at = datetime(2026, 1, 1)
+ capture_session.commit()
+ assert chart.deleted_at is not None
+ assert archives(capture_session) == []
+ metric.assert_called_once_with("lifecycle")
+ assert "archive transaction capture failed" in caplog.text
+
+
+@pytest.mark.parametrize("stage", ["scalar", "child", "lookup"])
+@pytest.mark.parametrize("archive", [False, True])
+def test_unisolated_content_read_failure_stops_before_lifecycle(
+ capture_session: Session, monkeypatch: pytest.MonkeyPatch, stage: str, archive: bool
+) -> None:
+ """An unisolated failed read is not made safe by a recoverable SQLSTATE."""
+ from unittest.mock import MagicMock
+
+ from superset.versioning import lifecycle
+ from superset.versioning.changes import listener
+
+ chart = Slice(slice_name="before", viz_type="table", params="{}")
+ capture_session.add(chart)
+ capture_session.commit()
+ diagnostic = Exception("deadlock during unisolated read")
+ diagnostic.sqlstate = "40P01" # type: ignore[attr-defined]
+ error = sa.exc.OperationalError("SELECT", {}, diagnostic)
+ helpers = {
+ "scalar": "compute_records_from_state",
+ "child": "_dataset_child_records_for_tx_from_shadows",
+ "lookup": "_current_transaction_id",
+ }
+ monkeypatch.setattr(listener, helpers[stage], MagicMock(side_effect=error))
+ capture = MagicMock()
+ monkeypatch.setattr(lifecycle, "capture_chart_archives", capture)
+ chart.slice_name = "after"
+ if archive:
+ chart.deleted_at = datetime(2026, 1, 1)
+ with pytest.raises(sa.exc.OperationalError) as raised:
+ capture_session.commit()
+ assert raised.value is error
+ capture.assert_not_called()
+ capture_session.rollback()
+ assert chart.slice_name == "before"
+ assert chart.deleted_at is None
+
+
+def test_null_dashboard_uuid_does_not_drop_other_archive_memberships(
+ capture_session: Session,
+) -> None:
+ """An invalid dashboard identity cannot suppress valid scopes for the chart."""
+ from superset.versioning.lifecycle_table import version_chart_archive_scope_table
+
+ chart = Slice(slice_name="chart", viz_type="table", params="{}")
+ invalid = Dashboard(dashboard_title="missing UUID", slices=[chart])
+ valid = Dashboard(dashboard_title="valid UUID", slices=[chart])
+ capture_session.add_all([invalid, valid])
+ capture_session.commit()
+ capture_session.connection().execute(
+ sa.update(Dashboard.__table__)
+ .where(Dashboard.__table__.c.id == invalid.id)
+ .values(uuid=None)
+ )
+ chart.deleted_at = datetime(2026, 1, 1)
+ capture_session.commit()
+ assert len(archives(capture_session)) == 1
+ scopes = capture_session.execute(sa.select(version_chart_archive_scope_table)).all()
+ assert len(scopes) == 1
+ assert scopes[0].dashboard_id == valid.id
+ assert scopes[0].dashboard_uuid == valid.uuid
+
+
+def test_fatal_lifecycle_capture_is_logged_and_counted_once(
+ capture_session: Session, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """Fatal metadata failures stay observable when the API returns a public error."""
+ from unittest.mock import MagicMock
+
+ from superset.versioning import lifecycle
+ from superset.versioning.changes import listener
+
+ chart = Slice(slice_name="chart", viz_type="table", params="{}")
+ capture_session.add(chart)
+ capture_session.commit()
+ failure = lifecycle.LifecycleCaptureFatalError("lost transaction")
+ monkeypatch.setattr(lifecycle, "_write_archive", MagicMock(side_effect=failure))
+ log = MagicMock()
+ metric = MagicMock()
+ monkeypatch.setattr(listener.logger, "exception", log)
+ monkeypatch.setattr(listener, "incr_capture_error", metric)
+ chart.deleted_at = datetime(2026, 1, 1)
+ with pytest.raises(lifecycle.LifecycleCaptureFatalError) as raised:
+ capture_session.commit()
+ assert raised.value is failure
+ log.assert_called_once_with("version_changes: fatal archive capture failure")
+ metric.assert_called_once_with("lifecycle_fatal")
+ capture_session.rollback()
+ assert chart.deleted_at is None
+ assert archives(capture_session) == []
diff --git a/tests/unit_tests/versioning/test_listener.py b/tests/unit_tests/versioning/test_listener.py
index 4dbad34690b4..8a3ca35707fd 100644
--- a/tests/unit_tests/versioning/test_listener.py
+++ b/tests/unit_tests/versioning/test_listener.py
@@ -584,13 +584,11 @@ def test_capture_latency_metric_fires_once_on_the_versioned_write_path(
def test_transaction_lookup_failure_does_not_break_the_commit(
lifecycle_session: Session, mocker: Any, monkeypatch: pytest.MonkeyPatch
) -> None:
- """The module's invariant — a versioning bug must never break a user's
- save — holds at ``_current_transaction_id`` too. With the lookup raising
- (a dropped connection, a Continuum internal error), the commit still
- succeeds and the user's row is persisted; the failure is counted, not
- propagated (fitzee finding on #44009, confirmed by aminghadersohi's probe:
- before this guard the RuntimeError unwound out of before_commit and 0 rows
- persisted)."""
+ """A non-database internal lookup error skips optional capture.
+
+ The RuntimeError leaves the transaction usable, so user work persists and
+ capture loss is counted. Database errors in this unisolated lookup propagate.
+ """
sa.event.listen(
lifecycle_session, "before_commit", listener.finalize_change_records
)
diff --git a/tests/unit_tests/versioning/test_runtime_capture.py b/tests/unit_tests/versioning/test_runtime_capture.py
index 4728e4bf09ac..9d8e6cac7679 100644
--- a/tests/unit_tests/versioning/test_runtime_capture.py
+++ b/tests/unit_tests/versioning/test_runtime_capture.py
@@ -44,25 +44,14 @@
)
-@pytest.fixture
-def capture_session(app: SupersetApp) -> Iterator[Session]:
- """Create only disposable in-memory tables; retain native listener wiring."""
- assert db.engine.url.get_backend_name() == "sqlite"
- assert not db.engine.url.database
- Model.metadata.create_all(db.engine)
- session: Session = db.session()
- yield session
- db.session.remove()
- Model.metadata.drop_all(db.engine)
-
-
def history_counts(session: Session) -> dict[str, int]:
"""Count every shadow, association, transaction and semantic-change table."""
return {
table.name: session.scalar(sa.select(sa.func.count()).select_from(table))
for table in Model.metadata.tables.values()
if table.name.endswith("_version")
- or table.name in {"version_transaction", "version_changes"}
+ or table.name
+ in {"version_transaction", "version_changes", "version_chart_archive_scope"}
}