fix(migration): compare only obtainable fields in dry-run diff + archive key mapping
- archive_parser: canonical compare-field specs (position->position_json), presence-checked `fields`, shared normalization; keep backward-compat signature - dry_run_orchestrator: intersection-based object diff — no false "update" on 6.x LIST exposure; 4.1.2 create-only limitation documented and pinned - translate: unshadow fastapi.status in job list route (ValueError now 400) + unskip regression test - tests: real-container migration plugin PARTIAL_SUCCESS/dry-run e2e, Superset LIST column-exposure characterization, translate malformed-LLM e2e + pg_e2e split (<800-line cap), dict_snapshot_hash DATABASE_URL poisoning fix, dead BINDS_TO/edge repairs
This commit is contained in:
@@ -44,7 +44,9 @@ from ._router import router
|
||||
async def list_jobs(
|
||||
page: int = Query(1, ge=1),
|
||||
page_size: int = Query(20, ge=1, le=100),
|
||||
status: str | None = Query(None),
|
||||
# alias keeps the public ?status= query param; the local name must not shadow
|
||||
# `fastapi.status`, otherwise the ValueError handler below raises AttributeError (500).
|
||||
status_filter: str | None = Query(None, alias="status"),
|
||||
current_user: User = Depends(get_current_user),
|
||||
_ = Depends(has_permission("translate.job", "VIEW")),
|
||||
db: Session = Depends(get_db),
|
||||
@@ -57,7 +59,7 @@ async def list_jobs(
|
||||
total, jobs = service.list_jobs(
|
||||
page=page,
|
||||
page_size=page_size,
|
||||
status_filter=status,
|
||||
status_filter=status_filter,
|
||||
)
|
||||
results = []
|
||||
for job in jobs:
|
||||
|
||||
@@ -27,6 +27,74 @@ import yaml
|
||||
from ..logger import belief_scope, logger
|
||||
|
||||
|
||||
# #region Core.ArchiveParser.CompareFieldSpecs [C:1] [TYPE Block] [SEMANTICS migration,transform,superset]
|
||||
# @BRIEF Canonical compare-field specs per object type: canonical field name -> ordered payload keys.
|
||||
# @RATIONALE Archives and Superset LIST items name the same logical field differently
|
||||
# (`position` vs `position_json`, `slice_name`/`dashboard_title`/`table_name` vs `title`,
|
||||
# `dataset_uuid` vs `datasource_uuid`). ONE spec shared by both descriptor producers
|
||||
# (Core.ArchiveParser.NormalizeObjectPayload and
|
||||
# Core.DryRunOrchestrator.BuildTargetSignatures) guarantees the intersection comparison
|
||||
# in Core.DryRunOrchestrator.BuildObjectDiff sees semantically identical field names.
|
||||
COMPARE_FIELD_SPECS: dict[str, tuple[tuple[str, tuple[str, ...]], ...]] = {
|
||||
"dashboards": (
|
||||
("title", ("dashboard_title", "title")),
|
||||
("slug", ("slug",)),
|
||||
("position_json", ("position", "position_json")),
|
||||
("json_metadata", ("json_metadata",)),
|
||||
("description", ("description",)),
|
||||
("owners", ("owners",)),
|
||||
),
|
||||
"charts": (
|
||||
("title", ("slice_name", "name")),
|
||||
("viz_type", ("viz_type",)),
|
||||
("params", ("params",)),
|
||||
("query_context", ("query_context",)),
|
||||
("dataset_uuid", ("dataset_uuid", "datasource_uuid")),
|
||||
),
|
||||
"datasets": (
|
||||
("title", ("table_name", "name")),
|
||||
("schema", ("schema",)),
|
||||
("database_uuid", ("database_uuid",)),
|
||||
("sql", ("sql",)),
|
||||
("columns", ("columns",)),
|
||||
("metrics", ("metrics",)),
|
||||
),
|
||||
}
|
||||
# #endregion Core.ArchiveParser.CompareFieldSpecs
|
||||
|
||||
|
||||
# #region Core.ArchiveParser.NormalizeCompareValue [C:2] [TYPE Function] [SEMANTICS migration,transform]
|
||||
# @BRIEF Normalize one compare value: dict/list become sorted JSON strings, everything else stays as-is.
|
||||
# @POST Returns a ==-comparable stable value for both descriptor producers (single shared function).
|
||||
# @RATIONALE Superset 4.1.2 LIST returns position_json/json_metadata as parsed dicts while export
|
||||
# archives carry dicts too — both sides land on identical sorted JSON. params arrives as a
|
||||
# JSON *string* on both sides and MUST NOT be re-parsed: presence-check + as-is string
|
||||
# comparison keeps it stable across builds (no double-parse divergence).
|
||||
def normalize_compare_value(value: Any) -> Any:
|
||||
if isinstance(value, (dict, list)):
|
||||
return json.dumps(value, sort_keys=True, default=str)
|
||||
return value
|
||||
# #endregion Core.ArchiveParser.NormalizeCompareValue
|
||||
|
||||
|
||||
# #region Core.ArchiveParser.BuildCompareFields [C:2] [TYPE Function] [SEMANTICS migration,transform,superset]
|
||||
# @RELATION DEPENDS_ON -> [Core.ArchiveParser.CompareFieldSpecs]
|
||||
# @RELATION DEPENDS_ON -> [Core.ArchiveParser.NormalizeCompareValue]
|
||||
# @BRIEF Build presence-checked canonical compare fields from a raw payload (archive YAML or LIST item).
|
||||
# @PRE payload is a dict; object_type is a key of COMPARE_FIELD_SPECS (unknown types yield {}).
|
||||
# @POST Returns ONLY canonical fields whose source key is actually present in payload
|
||||
# (`key in payload`, presence != non-None), each normalized by NormalizeCompareValue.
|
||||
def build_compare_fields(payload: dict[str, Any], object_type: str) -> dict[str, Any]:
|
||||
fields: dict[str, Any] = {}
|
||||
for canonical, source_keys in COMPARE_FIELD_SPECS.get(object_type, ()):
|
||||
for source_key in source_keys:
|
||||
if source_key in payload:
|
||||
fields[canonical] = normalize_compare_value(payload[source_key])
|
||||
break
|
||||
return fields
|
||||
# #endregion Core.ArchiveParser.BuildCompareFields
|
||||
|
||||
|
||||
# #region Core.ArchiveParser.MigrationArchiveParser [TYPE Class]
|
||||
# @defgroup Migration Module group.
|
||||
# @BRIEF Extract normalized dashboards/charts/datasets metadata from ZIP archives.
|
||||
@@ -89,9 +157,24 @@ class MigrationArchiveParser:
|
||||
return objects
|
||||
# #endregion Core.ArchiveParser.CollectYamlObjects
|
||||
# #region Core.ArchiveParser.NormalizeObjectPayload [TYPE Function]
|
||||
# @BRIEF: Convert raw YAML payload to stable diff signature shape.
|
||||
# @BRIEF: Convert raw YAML payload to normalized diff descriptor with presence-checked fields.
|
||||
# @RELATION DEPENDS_ON -> [Core.ArchiveParser.BuildCompareFields]
|
||||
# @PRE payload is parsed YAML mapping.
|
||||
# @POST Returns normalized descriptor with `uuid`, `title`, and `signature`.
|
||||
# @POST Returns normalized descriptor with `uuid`, `title`, `fields` (canonical compare
|
||||
# fields, ONLY keys actually present in payload) and the backward-compat serialized
|
||||
# `signature` (json of `fields` — consumed by tests/test_core/test_archive_parser.py).
|
||||
# @RATIONALE Superset export YAMLs carry dashboard layout under key `position` while LIST
|
||||
# endpoints expose `position_json`; the previous code read payload.get("position_json")
|
||||
# from archives, so the source field was permanently None and never matched the
|
||||
# target. Fields are now presence-checked (`key in payload`) and mapped to canonical
|
||||
# names via Core.ArchiveParser.CompareFieldSpecs so
|
||||
# Core.DryRunOrchestrator.BuildObjectDiff can compare the intersection of fields
|
||||
# obtainable on BOTH sides.
|
||||
# @REJECTED Opaque full-field signature equality over pre-serialized JSON — silently
|
||||
# false-positives because Superset LIST columns are version-dependent (4.1.2 drops
|
||||
# uuid; 6.x drops position_json/json_metadata/description/owners). Reading
|
||||
# `position_json` without the archive `position` key was rejected — export YAMLs
|
||||
# never carry `position_json`, so the field was unconditionally None.
|
||||
def _normalize_object_payload(
|
||||
self, payload: dict[str, Any], object_type: str
|
||||
) -> dict[str, Any] | None:
|
||||
@@ -101,56 +184,29 @@ class MigrationArchiveParser:
|
||||
uuid = payload.get("uuid")
|
||||
if not uuid:
|
||||
return None
|
||||
if object_type not in COMPARE_FIELD_SPECS:
|
||||
return None
|
||||
fields = build_compare_fields(payload, object_type)
|
||||
descriptor: dict[str, Any] = {
|
||||
"uuid": str(uuid),
|
||||
"fields": fields,
|
||||
"signature": json.dumps(fields, sort_keys=True, default=str),
|
||||
}
|
||||
if object_type == "dashboards":
|
||||
title = payload.get("dashboard_title") or payload.get("title")
|
||||
signature = {
|
||||
"title": title,
|
||||
"slug": payload.get("slug"),
|
||||
"position_json": payload.get("position_json"),
|
||||
"json_metadata": payload.get("json_metadata"),
|
||||
"description": payload.get("description"),
|
||||
"owners": payload.get("owners"),
|
||||
}
|
||||
return {
|
||||
"uuid": str(uuid),
|
||||
"title": title or f"Dashboard {uuid}",
|
||||
"signature": json.dumps(signature, sort_keys=True, default=str),
|
||||
"owners": payload.get("owners") or [],
|
||||
}
|
||||
if object_type == "charts":
|
||||
descriptor["title"] = title or f"Dashboard {uuid}"
|
||||
descriptor["owners"] = payload.get("owners") or []
|
||||
elif object_type == "charts":
|
||||
title = payload.get("slice_name") or payload.get("name")
|
||||
signature = {
|
||||
"title": title,
|
||||
"viz_type": payload.get("viz_type"),
|
||||
"params": payload.get("params"),
|
||||
"query_context": payload.get("query_context"),
|
||||
"datasource_uuid": payload.get("datasource_uuid"),
|
||||
"dataset_uuid": payload.get("dataset_uuid"),
|
||||
}
|
||||
return {
|
||||
"uuid": str(uuid),
|
||||
"title": title or f"Chart {uuid}",
|
||||
"signature": json.dumps(signature, sort_keys=True, default=str),
|
||||
"dataset_uuid": payload.get("datasource_uuid")
|
||||
or payload.get("dataset_uuid"),
|
||||
}
|
||||
if object_type == "datasets":
|
||||
descriptor["title"] = title or f"Chart {uuid}"
|
||||
descriptor["dataset_uuid"] = payload.get("datasource_uuid") or payload.get(
|
||||
"dataset_uuid"
|
||||
)
|
||||
else:
|
||||
title = payload.get("table_name") or payload.get("name")
|
||||
signature = {
|
||||
"title": title,
|
||||
"schema": payload.get("schema"),
|
||||
"database_uuid": payload.get("database_uuid"),
|
||||
"sql": payload.get("sql"),
|
||||
"columns": payload.get("columns"),
|
||||
"metrics": payload.get("metrics"),
|
||||
}
|
||||
return {
|
||||
"uuid": str(uuid),
|
||||
"title": title or f"Dataset {uuid}",
|
||||
"signature": json.dumps(signature, sort_keys=True, default=str),
|
||||
"database_uuid": payload.get("database_uuid"),
|
||||
}
|
||||
return None
|
||||
descriptor["title"] = title or f"Dataset {uuid}"
|
||||
descriptor["database_uuid"] = payload.get("database_uuid")
|
||||
return descriptor
|
||||
# #endregion Core.ArchiveParser.NormalizeObjectPayload
|
||||
# #endregion Core.ArchiveParser.MigrationArchiveParser
|
||||
# #endregion Core.ArchiveParser.MigrationArchiveParserModule
|
||||
|
||||
@@ -26,7 +26,7 @@ from ..mapping_service import IdMappingService
|
||||
from ..migration_engine import MigrationEngine
|
||||
from ..superset_client import SupersetClient
|
||||
from ..utils.fileio import create_temp_file
|
||||
from .archive_parser import MigrationArchiveParser
|
||||
from .archive_parser import MigrationArchiveParser, build_compare_fields
|
||||
from .risk_assessor import build_risks, score_risks
|
||||
|
||||
|
||||
@@ -314,8 +314,22 @@ class MigrationDryRunService:
|
||||
return indexed
|
||||
# #endregion Core.DryRunOrchestrator.IndexByUuid
|
||||
# #region Core.DryRunOrchestrator.BuildObjectDiff [C:3] [TYPE Function]
|
||||
# @BRIEF: Compute create/update/delete buckets by UUID+signature.
|
||||
# @BRIEF: Compute create/update/delete buckets by UUID + intersection of comparable fields.
|
||||
# @RELATION DEPENDS_ON -> [Core.DryRunOrchestrator.IndexByUuid]
|
||||
# @POST uuid absent from target index -> create; uuid matched with a differing COMMON field ->
|
||||
# update (shape: uuid/title/target_title); uuid matched with no common-field difference
|
||||
# (including empty intersection) -> no bucket. delete stays empty (source-scoped diff).
|
||||
# @RATIONALE Only fields obtainable on BOTH sides carry comparison evidence: source archives and
|
||||
# target LIST responses expose version-dependent field sets (4.1.2 LIST has no uuid;
|
||||
# 6.x LIST has no position_json/json_metadata/description/owners). Comparing the
|
||||
# intersection of the presence-checked `fields` dicts means one-sided fields can never
|
||||
# manufacture a false "update". Empty intersection = NO evidence of change = not an
|
||||
# update.
|
||||
# @REJECTED Full-field signature equality over pre-serialized JSON — silently false-positives
|
||||
# because Superset LIST columns are version-dependent (None-filled dropped columns
|
||||
# never equal archive values, so every existing dashboard was reported as update).
|
||||
# Treating an empty intersection as "changed" was rejected — it would recreate the
|
||||
# same false-update regression on builds with disjoint field exposure.
|
||||
def _build_object_diff(
|
||||
self, source_objects: list[dict[str, Any]], target_objects: list[dict[str, Any]]
|
||||
) -> dict[str, list[dict[str, Any]]]:
|
||||
@@ -329,7 +343,11 @@ class MigrationDryRunService:
|
||||
if not target_obj:
|
||||
created.append({"uuid": source_uuid, "title": source_obj.get("title")})
|
||||
continue
|
||||
if source_obj.get("signature") != target_obj.get("signature"):
|
||||
source_fields = source_obj.get("fields") or {}
|
||||
target_fields = target_obj.get("fields") or {}
|
||||
common = sorted(set(source_fields) & set(target_fields))
|
||||
changed = any(source_fields[key] != target_fields[key] for key in common)
|
||||
if changed:
|
||||
updated.append(
|
||||
{
|
||||
"uuid": source_uuid,
|
||||
@@ -340,7 +358,27 @@ class MigrationDryRunService:
|
||||
return {"create": created, "update": updated, "delete": deleted}
|
||||
# #endregion Core.DryRunOrchestrator.BuildObjectDiff
|
||||
# #region Core.DryRunOrchestrator.BuildTargetSignatures [C:3] [TYPE Function]
|
||||
# @BRIEF: Pull target metadata and normalize it into comparable signatures.
|
||||
# @BRIEF: Pull target LIST metadata and normalize it into presence-checked field descriptors.
|
||||
# @RELATION DEPENDS_ON -> [Core.ArchiveParser.BuildCompareFields]
|
||||
# @POST Per object type: descriptors with `uuid`, `title`, presence-checked canonical `fields`
|
||||
# (shared spec with archives), backward-compat serialized `signature`, plus the
|
||||
# convenience keys consumed by Core.RiskAssessor.BuildRisks (`owners` for dashboards,
|
||||
# `database_uuid` for datasets, `dataset_uuid` for charts). Items without uuid are
|
||||
# filtered out — pinned Superset 4.1.2 LIST drops uuid, so the target set is EMPTY there
|
||||
# and the diff degrades to create-only
|
||||
# (tests/integration/test_superset_list_column_exposure.py).
|
||||
# @RATIONALE Superset LIST endpoints silently drop requested columns not allowed on the build,
|
||||
# so fields MUST be presence-checked (`key in item` via BuildCompareFields), never
|
||||
# None-filled: 4.1.2 returns dashboard_title/json_metadata/position_json/slug (no
|
||||
# uuid); 6.x returns uuid/dashboard_title/slug (no position_json/json_metadata/
|
||||
# description/owners). Requesting the union column set is harmless on both versions —
|
||||
# the drops are handled by presence-check + the intersection comparison in
|
||||
# Core.DryRunOrchestrator.BuildObjectDiff.
|
||||
# @REJECTED Full-field signature equality over pre-serialized JSON — silently false-positives
|
||||
# because Superset LIST columns are version-dependent (None-filled dropped columns
|
||||
# never equal archive values). Dropping requested columns to the lowest common
|
||||
# denominator was rejected — the exposure is build-dependent and unknowable at
|
||||
# request time; presence-check is the version-agnostic mechanism.
|
||||
async def _build_target_signatures(
|
||||
self, client: SupersetClient
|
||||
) -> dict[str, list[dict[str, Any]]]:
|
||||
@@ -383,72 +421,36 @@ class MigrationDryRunService:
|
||||
],
|
||||
}
|
||||
)
|
||||
return {
|
||||
"dashboards": [
|
||||
{
|
||||
"uuid": str(item.get("uuid")),
|
||||
"title": item.get("dashboard_title"),
|
||||
"owners": item.get("owners") or [],
|
||||
"signature": json.dumps(
|
||||
{
|
||||
"title": item.get("dashboard_title"),
|
||||
"slug": item.get("slug"),
|
||||
"position_json": item.get("position_json"),
|
||||
"json_metadata": item.get("json_metadata"),
|
||||
"description": item.get("description"),
|
||||
"owners": item.get("owners"),
|
||||
},
|
||||
sort_keys=True,
|
||||
default=str,
|
||||
),
|
||||
}
|
||||
for item in dashboards
|
||||
if item.get("uuid")
|
||||
],
|
||||
"datasets": [
|
||||
{
|
||||
"uuid": str(item.get("uuid")),
|
||||
"title": item.get("table_name"),
|
||||
"database_uuid": item.get("database_uuid"),
|
||||
"signature": json.dumps(
|
||||
{
|
||||
"title": item.get("table_name"),
|
||||
"schema": item.get("schema"),
|
||||
"database_uuid": item.get("database_uuid"),
|
||||
"sql": item.get("sql"),
|
||||
"columns": item.get("columns"),
|
||||
"metrics": item.get("metrics"),
|
||||
},
|
||||
sort_keys=True,
|
||||
default=str,
|
||||
),
|
||||
}
|
||||
for item in datasets
|
||||
if item.get("uuid")
|
||||
],
|
||||
"charts": [
|
||||
{
|
||||
"uuid": str(item.get("uuid")),
|
||||
"title": item.get("slice_name") or item.get("name"),
|
||||
"dataset_uuid": item.get("datasource_uuid")
|
||||
or item.get("dataset_uuid"),
|
||||
"signature": json.dumps(
|
||||
{
|
||||
"title": item.get("slice_name") or item.get("name"),
|
||||
"viz_type": item.get("viz_type"),
|
||||
"params": item.get("params"),
|
||||
"query_context": item.get("query_context"),
|
||||
"datasource_uuid": item.get("datasource_uuid"),
|
||||
"dataset_uuid": item.get("dataset_uuid"),
|
||||
},
|
||||
sort_keys=True,
|
||||
default=str,
|
||||
),
|
||||
}
|
||||
for item in charts
|
||||
if item.get("uuid")
|
||||
],
|
||||
descriptors: dict[str, list[dict[str, Any]]] = {
|
||||
"dashboards": [],
|
||||
"datasets": [],
|
||||
"charts": [],
|
||||
}
|
||||
for object_type, items in (
|
||||
("dashboards", dashboards),
|
||||
("datasets", datasets),
|
||||
("charts", charts),
|
||||
):
|
||||
for item in items:
|
||||
if not item.get("uuid"):
|
||||
continue
|
||||
fields = build_compare_fields(item, object_type)
|
||||
descriptor: dict[str, Any] = {
|
||||
"uuid": str(item.get("uuid")),
|
||||
"title": fields.get("title"),
|
||||
"fields": fields,
|
||||
"signature": json.dumps(fields, sort_keys=True, default=str),
|
||||
}
|
||||
if object_type == "dashboards":
|
||||
descriptor["owners"] = item.get("owners") or []
|
||||
elif object_type == "datasets":
|
||||
descriptor["database_uuid"] = item.get("database_uuid")
|
||||
else:
|
||||
descriptor["dataset_uuid"] = item.get("datasource_uuid") or item.get(
|
||||
"dataset_uuid"
|
||||
)
|
||||
descriptors[object_type].append(descriptor)
|
||||
return descriptors
|
||||
# #endregion Core.DryRunOrchestrator.BuildTargetSignatures
|
||||
# #region Core.DryRunOrchestrator.BuildRisks [C:3] [TYPE Function]
|
||||
# @BRIEF: Build risk items for missing datasource, broken refs, overwrite, owner mismatch.
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# #region Test.Tests.TestBatchInsert [C:3] [TYPE Module] [SEMANTICS test,translate,batch,insert]
|
||||
# @BRIEF Tests for _batch_insert.py — column building, row building, context keys.
|
||||
# @RELATION BINDS_TO -> [_batch_insert_module]
|
||||
# @RELATION BINDS_TO -> [Plugin.BatchInsert.BatchInsertService]
|
||||
import pytest
|
||||
from unittest.mock import AsyncMock, MagicMock
|
||||
import uuid
|
||||
|
||||
@@ -5,9 +5,12 @@
|
||||
|
||||
import os
|
||||
|
||||
# Must set DATABASE_URL before importing any src modules
|
||||
os.environ["DATABASE_URL"] = "sqlite:///:memory:"
|
||||
os.environ["DATABASE_URL"] = "sqlite:///:memory:"
|
||||
# Ensure DATABASE_URL exists before importing src modules. MUST be setdefault:
|
||||
# an unconditional clobber poisons the session-wide `alembic upgrade head` in
|
||||
# tests/conftest.py::ensure_db_tables when this module is collected together
|
||||
# with the tests/ tree (global SQLite file stays schema-less -> cross-suite
|
||||
# "no such table" failures). This module uses its own in-memory engine below.
|
||||
os.environ.setdefault("DATABASE_URL", "sqlite:///:memory:")
|
||||
|
||||
from datetime import UTC, datetime, timedelta
|
||||
import hashlib
|
||||
|
||||
@@ -237,13 +237,11 @@ class TestCheckTargetSchema:
|
||||
class TestListJobsErrors:
|
||||
"""GET /api/translate/jobs — error paths"""
|
||||
|
||||
def test_list_jobs_value_error_crashes(self):
|
||||
"""Known source bug: `status` param shadows `fastapi.status` import.
|
||||
ValueError → `status.HTTP_400_BAD_REQUEST` fails (status=None) → AttributeError.
|
||||
The exception handler is broken due to name shadowing; fix is to rename the
|
||||
`status` query parameter. This test documents the known source bug.
|
||||
def test_list_jobs_value_error_returns_400(self):
|
||||
"""Regression: the `status` query param used to shadow `fastapi.status`,
|
||||
so the ValueError handler crashed with AttributeError (500). The param is
|
||||
now `status_filter` with `alias="status"`; ValueError maps to 400.
|
||||
"""
|
||||
pytest.skip("Source bug: `status` param shadows fastapi.status — error path untestable without source mod")
|
||||
mock_service = MagicMock()
|
||||
mock_service.list_jobs.side_effect = ValueError("Invalid filter")
|
||||
with patch(
|
||||
@@ -251,7 +249,13 @@ class TestListJobsErrors:
|
||||
return_value=mock_service,
|
||||
):
|
||||
client = _make_client()
|
||||
_ = client.get("/api/translate/jobs")
|
||||
resp = client.get("/api/translate/jobs", params={"status": "bogus"})
|
||||
assert resp.status_code == 400
|
||||
assert "Invalid filter" in resp.text
|
||||
# alias wiring: public ?status= reaches the service as status_filter=
|
||||
mock_service.list_jobs.assert_called_once_with(
|
||||
page=1, page_size=20, status_filter="bogus"
|
||||
)
|
||||
|
||||
|
||||
# =============================================================================
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
# @LAYER Domain
|
||||
# @RELATION DEPENDS_ON -> [Core.ArchiveParser.MigrationArchiveParserModule]
|
||||
#
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import sys
|
||||
@@ -75,4 +76,69 @@ def test_extract_objects_from_zip_collects_all_types():
|
||||
|
||||
|
||||
# #endregion Test.Migration.TestExtractObjectsFromZipCollectsAllTypes
|
||||
|
||||
|
||||
# #region Test.Migration.TestDashboardPositionKeyMapsToPositionJsonField [C:2] [TYPE Function]
|
||||
# @RELATION BINDS_TO -> [Core.ArchiveParser.NormalizeObjectPayload]
|
||||
# @PURPOSE: Regression — export YAML key `position` maps to canonical fields["position_json"]
|
||||
# (the old code read payload["position_json"], which archives never carry → always None).
|
||||
# @TEST_SCENARIO: archive_position_key -> fields["position_json"] holds the sorted-JSON normalized dict.
|
||||
# @TEST_FIXTURE: dashboard_yaml_with_position -> INLINE
|
||||
def test_dashboard_position_key_maps_to_position_json_field():
|
||||
parser = MigrationArchiveParser()
|
||||
payload = {
|
||||
"uuid": "dash-pos-1",
|
||||
"dashboard_title": "D1",
|
||||
"position": {"B": {"type": "ROW"}, "A": {"type": "HEADER"}},
|
||||
}
|
||||
result = parser._normalize_object_payload(payload, "dashboards")
|
||||
|
||||
# Hardcoded expected value of json.dumps(sort_keys=True) — never recomputed in-test.
|
||||
expected = '{"A": {"type": "HEADER"}, "B": {"type": "ROW"}}'
|
||||
if result["fields"]["position_json"] != expected:
|
||||
raise AssertionError("archive `position` key was not mapped into fields[position_json]")
|
||||
# Backward-compat: `signature` is the serialized `fields` dict.
|
||||
if json.loads(result["signature"]) != result["fields"]:
|
||||
raise AssertionError("signature must serialize the fields dict (backward compat)")
|
||||
|
||||
|
||||
# #endregion Test.Migration.TestDashboardPositionKeyMapsToPositionJsonField
|
||||
|
||||
|
||||
# #region Test.Migration.TestPositionJsonFallbackKey [C:2] [TYPE Function]
|
||||
# @RELATION BINDS_TO -> [Core.ArchiveParser.CompareFieldSpecs]
|
||||
# @PURPOSE: `position_json` remains a fallback source key for the canonical position_json field.
|
||||
def test_dashboard_position_json_key_is_fallback():
|
||||
parser = MigrationArchiveParser()
|
||||
payload = {"uuid": "dash-pos-2", "position_json": {"X": 1}}
|
||||
result = parser._normalize_object_payload(payload, "dashboards")
|
||||
|
||||
if result["fields"]["position_json"] != '{"X": 1}':
|
||||
raise AssertionError("position_json fallback key was not normalized into fields")
|
||||
|
||||
|
||||
# #endregion Test.Migration.TestPositionJsonFallbackKey
|
||||
|
||||
|
||||
# #region Test.Migration.TestAbsentPayloadKeysMissingFromFields [C:2] [TYPE Function]
|
||||
# @RELATION BINDS_TO -> [Core.ArchiveParser.BuildCompareFields]
|
||||
# @PURPOSE: Presence-check semantics — keys absent from the YAML are ABSENT from fields (not None),
|
||||
# so the dry-run intersection comparison never sees one-sided None placeholders.
|
||||
# @TEST_SCENARIO: archive_yaml_without_description_owners -> fields exposes only present keys.
|
||||
# @TEST_EDGE: missing_field -> absent description/owners never appear in fields, not even as None.
|
||||
def test_absent_payload_keys_are_missing_from_fields():
|
||||
parser = MigrationArchiveParser()
|
||||
payload = {"uuid": "dash-pres-1", "dashboard_title": "D2", "slug": "d2"}
|
||||
result = parser._normalize_object_payload(payload, "dashboards")
|
||||
|
||||
if set(result["fields"]) != {"title", "slug"}:
|
||||
raise AssertionError(f"fields must contain only present keys, got {sorted(result['fields'])}")
|
||||
if "description" in result["fields"] or "owners" in result["fields"]:
|
||||
raise AssertionError("absent payload keys must not appear in fields")
|
||||
# Descriptor `owners` convenience key keeps its pre-existing default for risk assessment.
|
||||
if result["owners"] != []:
|
||||
raise AssertionError("descriptor owners convenience key must default to []")
|
||||
|
||||
|
||||
# #endregion Test.Migration.TestAbsentPayloadKeysMissingFromFields
|
||||
# #endregion Test.Migration.TestArchiveParser
|
||||
|
||||
@@ -18,6 +18,7 @@ backend_dir = str(Path(__file__).parent.parent.parent.parent.resolve())
|
||||
if backend_dir not in sys.path:
|
||||
sys.path.insert(0, backend_dir)
|
||||
|
||||
from src.core.migration.archive_parser import MigrationArchiveParser
|
||||
from src.core.migration.dry_run_orchestrator import MigrationDryRunService
|
||||
from src.models.dashboard import DashboardSelection
|
||||
from src.models.mapping import Base
|
||||
@@ -194,4 +195,211 @@ async def test_dry_run_incomplete_mapping_uses_identity_fallback():
|
||||
assert call_kwargs_mapping == {}
|
||||
assert result["summary"]["selected_dashboards"] == 1
|
||||
# #endregion Test.Migration.TestDryRunIncompleteMappingUsesIdentityFallback
|
||||
|
||||
|
||||
# #region Test.Migration.TestTarget412ListShapeDegradesToCreateOnly [C:2] [TYPE Function]
|
||||
# @RELATION BINDS_TO -> [Core.DryRunOrchestrator.BuildTargetSignatures]
|
||||
# @PURPOSE: Pin the documented Superset 4.1.2 limitation — LIST items without uuid are filtered
|
||||
# out, the target descriptor set is empty, and the diff degrades to create-only.
|
||||
# @TEST_SCENARIO: target_list_4_1_2_shape -> uuid-less items dropped; source object lands in create.
|
||||
# @TEST_EDGE: missing_field -> 4.1.2 LIST silently drops uuid; descriptor producer must not invent it.
|
||||
# @TEST_FIXTURE: superset_4_1_2_dashboard_list_item -> INLINE (measured exposure, see
|
||||
# tests/integration/test_superset_list_column_exposure.py)
|
||||
@pytest.mark.asyncio
|
||||
async def test_target_list_4_1_2_shape_degrades_to_create_only():
|
||||
service = MigrationDryRunService()
|
||||
client = AsyncMock()
|
||||
# Hardcoded Superset 4.1.2 /dashboard/ LIST exposure: allowed columns only, uuid silently dropped.
|
||||
client.get_dashboards.return_value = (
|
||||
1,
|
||||
[
|
||||
{
|
||||
"dashboard_title": "Sales",
|
||||
"json_metadata": {"refresh_frequency": 0},
|
||||
"position_json": {"CHART-1": {"type": "CHART"}},
|
||||
"slug": "sales",
|
||||
}
|
||||
],
|
||||
)
|
||||
client.get_datasets.return_value = (0, [])
|
||||
client.get_charts.return_value = (0, [])
|
||||
|
||||
targets = await service._build_target_signatures(client)
|
||||
if targets["dashboards"] != []:
|
||||
raise AssertionError("uuid-less 4.1.2 LIST items must be filtered out of the target set")
|
||||
|
||||
source = MigrationArchiveParser()._normalize_object_payload(
|
||||
{
|
||||
"uuid": "dash-412",
|
||||
"dashboard_title": "Sales",
|
||||
"slug": "sales",
|
||||
"position": {"CHART-1": {"type": "CHART"}},
|
||||
},
|
||||
"dashboards",
|
||||
)
|
||||
diff = service._build_object_diff([source], targets["dashboards"])
|
||||
if [entry["uuid"] for entry in diff["create"]] != ["dash-412"]:
|
||||
raise AssertionError("source dashboard must land in the create bucket on 4.1.2")
|
||||
if diff["update"] != [] or diff["delete"] != []:
|
||||
raise AssertionError("create-only degradation must leave update/delete empty")
|
||||
# #endregion Test.Migration.TestTarget412ListShapeDegradesToCreateOnly
|
||||
|
||||
|
||||
# #region Test.Migration.TestTarget6xListShapeIntersectionComparison [C:2] [TYPE Function]
|
||||
# @RELATION BINDS_TO -> [Core.DryRunOrchestrator.BuildObjectDiff]
|
||||
# @PURPOSE: False-update regression — a 6.x LIST item (uuid/dashboard_title/slug only) matching the
|
||||
# archive title+slug is NOT an update; one-sided position_json/json_metadata are excluded.
|
||||
# @TEST_SCENARIO: identical_common_fields -> no bucket. differing_slug -> update bucket.
|
||||
# @TEST_EDGE: invalid_type -> archive dicts (position/json_metadata) never reach the comparison
|
||||
# when the target build cannot provide them (intersection is empty for those keys).
|
||||
@pytest.mark.asyncio
|
||||
async def test_target_6x_shape_compares_only_common_fields():
|
||||
service = MigrationDryRunService()
|
||||
source = MigrationArchiveParser()._normalize_object_payload(
|
||||
{
|
||||
"uuid": "dash-6x",
|
||||
"dashboard_title": "Sales",
|
||||
"slug": "sales",
|
||||
"position": {"CHART-1": {"type": "CHART"}},
|
||||
"json_metadata": {"refresh_frequency": 0},
|
||||
},
|
||||
"dashboards",
|
||||
)
|
||||
|
||||
client = AsyncMock()
|
||||
client.get_datasets.return_value = (0, [])
|
||||
client.get_charts.return_value = (0, [])
|
||||
# Hardcoded Superset 6.x /dashboard/ LIST exposure: uuid/dashboard_title/slug only
|
||||
# (NO position_json/json_metadata/description/owners — live probe documented in
|
||||
# tests/integration/test_superset_list_column_exposure.py @RATIONALE).
|
||||
client.get_dashboards.return_value = (
|
||||
1,
|
||||
[{"uuid": "dash-6x", "dashboard_title": "Sales", "slug": "sales"}],
|
||||
)
|
||||
targets = await service._build_target_signatures(client)
|
||||
diff = service._build_object_diff([source], targets["dashboards"])
|
||||
if diff["update"] != []:
|
||||
raise AssertionError("source-only position_json/json_metadata must not cause an update")
|
||||
if diff["create"] != []:
|
||||
raise AssertionError("uuid-matched dashboard must never land in create")
|
||||
|
||||
client.get_dashboards.return_value = (
|
||||
1,
|
||||
[{"uuid": "dash-6x", "dashboard_title": "Sales", "slug": "sales-old"}],
|
||||
)
|
||||
targets = await service._build_target_signatures(client)
|
||||
diff = service._build_object_diff([source], targets["dashboards"])
|
||||
if [entry["uuid"] for entry in diff["update"]] != ["dash-6x"]:
|
||||
raise AssertionError("differing common field (slug) must be reported as update")
|
||||
if diff["update"][0]["target_title"] != "Sales":
|
||||
raise AssertionError("update entry must keep uuid/title/target_title shape")
|
||||
# #endregion Test.Migration.TestTarget6xListShapeIntersectionComparison
|
||||
|
||||
|
||||
# #region Test.Migration.TestChartParamsComparedQueryContextExcluded [C:2] [TYPE Function]
|
||||
# @RELATION BINDS_TO -> [Core.DryRunOrchestrator.BuildObjectDiff]
|
||||
# @PURPOSE: Chart params compare as raw strings on both sides; source-only query_context is never
|
||||
# compared (6.x LIST does not expose it).
|
||||
# @TEST_SCENARIO: equal_params_strings -> no update. differing_params_strings -> update.
|
||||
@pytest.mark.asyncio
|
||||
async def test_chart_params_string_compared_query_context_excluded():
|
||||
service = MigrationDryRunService()
|
||||
source = MigrationArchiveParser()._normalize_object_payload(
|
||||
{
|
||||
"uuid": "chart-6x",
|
||||
"slice_name": "Revenue",
|
||||
"viz_type": "table",
|
||||
"params": '{"row_limit": 100}',
|
||||
"query_context": {"result_format": "json"},
|
||||
},
|
||||
"charts",
|
||||
)
|
||||
if "query_context" not in source["fields"]:
|
||||
raise AssertionError("archive query_context must be present in source fields")
|
||||
|
||||
client = AsyncMock()
|
||||
client.get_dashboards.return_value = (0, [])
|
||||
client.get_datasets.return_value = (0, [])
|
||||
# Hardcoded Superset 6.x /chart/ LIST exposure: no query_context/datasource_uuid/dataset_uuid.
|
||||
client.get_charts.return_value = (
|
||||
1,
|
||||
[
|
||||
{
|
||||
"uuid": "chart-6x",
|
||||
"slice_name": "Revenue",
|
||||
"viz_type": "table",
|
||||
"params": '{"row_limit": 100}',
|
||||
}
|
||||
],
|
||||
)
|
||||
targets = await service._build_target_signatures(client)
|
||||
diff = service._build_object_diff([source], targets["charts"])
|
||||
if diff["update"] != []:
|
||||
raise AssertionError("equal params strings + one-sided query_context must not update")
|
||||
|
||||
client.get_charts.return_value = (
|
||||
1,
|
||||
[
|
||||
{
|
||||
"uuid": "chart-6x",
|
||||
"slice_name": "Revenue",
|
||||
"viz_type": "table",
|
||||
"params": '{"row_limit": 50}',
|
||||
}
|
||||
],
|
||||
)
|
||||
targets = await service._build_target_signatures(client)
|
||||
diff = service._build_object_diff([source], targets["charts"])
|
||||
if [entry["uuid"] for entry in diff["update"]] != ["chart-6x"]:
|
||||
raise AssertionError("differing params string must be reported as update")
|
||||
# #endregion Test.Migration.TestChartParamsComparedQueryContextExcluded
|
||||
|
||||
|
||||
# #region Test.Migration.TestDatasetIntersectionExcludesOneSidedFields [C:2] [TYPE Function]
|
||||
# @RELATION BINDS_TO -> [Core.DryRunOrchestrator.BuildObjectDiff]
|
||||
# @PURPOSE: Dataset diff compares the {title, schema, sql} intersection; one-sided
|
||||
# database_uuid/columns/metrics (never LIST-exposed on 6.x) are excluded.
|
||||
# @TEST_SCENARIO: equal_common_fields -> no update. differing_sql -> update.
|
||||
@pytest.mark.asyncio
|
||||
async def test_dataset_one_sided_fields_excluded_from_diff():
|
||||
service = MigrationDryRunService()
|
||||
source = MigrationArchiveParser()._normalize_object_payload(
|
||||
{
|
||||
"uuid": "ds-6x",
|
||||
"table_name": "orders",
|
||||
"schema": "public",
|
||||
"sql": "SELECT 1",
|
||||
"database_uuid": "db-1",
|
||||
"columns": [{"column_name": "id"}],
|
||||
"metrics": [{"metric_name": "count"}],
|
||||
},
|
||||
"datasets",
|
||||
)
|
||||
if set(source["fields"]) != {"title", "schema", "sql", "database_uuid", "columns", "metrics"}:
|
||||
raise AssertionError(f"unexpected source fields: {sorted(source['fields'])}")
|
||||
|
||||
client = AsyncMock()
|
||||
client.get_dashboards.return_value = (0, [])
|
||||
client.get_charts.return_value = (0, [])
|
||||
# Hardcoded Superset 6.x /dataset/ LIST exposure: uuid/table_name/schema/sql only.
|
||||
client.get_datasets.return_value = (
|
||||
1,
|
||||
[{"uuid": "ds-6x", "table_name": "orders", "schema": "public", "sql": "SELECT 1"}],
|
||||
)
|
||||
targets = await service._build_target_signatures(client)
|
||||
diff = service._build_object_diff([source], targets["datasets"])
|
||||
if diff["update"] != []:
|
||||
raise AssertionError("one-sided database_uuid/columns/metrics must not cause an update")
|
||||
if diff["create"] != []:
|
||||
raise AssertionError("uuid-matched dataset must never land in create")
|
||||
|
||||
client.get_datasets.return_value = (
|
||||
1,
|
||||
[{"uuid": "ds-6x", "table_name": "orders", "schema": "public", "sql": "SELECT 2"}],
|
||||
)
|
||||
targets = await service._build_target_signatures(client)
|
||||
diff = service._build_object_diff([source], targets["datasets"])
|
||||
if [entry["uuid"] for entry in diff["update"]] != ["ds-6x"]:
|
||||
raise AssertionError("differing common field (sql) must be reported as update")
|
||||
# #endregion Test.Migration.TestDatasetIntersectionExcludesOneSidedFields
|
||||
# #endregion Test.Migration.TestDryRunOrchestrator
|
||||
|
||||
@@ -30,7 +30,10 @@
|
||||
{
|
||||
"uuid": "dash-1",
|
||||
"title": "Sales New",
|
||||
"signature": "{\"title\":\"Sales New\"}",
|
||||
"fields": {
|
||||
"title": "Sales New"
|
||||
},
|
||||
"signature": "{\"title\": \"Sales New\"}",
|
||||
"owners": [
|
||||
{
|
||||
"username": "owner-b"
|
||||
@@ -42,7 +45,10 @@
|
||||
{
|
||||
"uuid": "chart-1",
|
||||
"title": "Chart A",
|
||||
"signature": "{\"title\":\"Chart A\"}",
|
||||
"fields": {
|
||||
"title": "Chart A"
|
||||
},
|
||||
"signature": "{\"title\": \"Chart A\"}",
|
||||
"dataset_uuid": "dataset-404"
|
||||
}
|
||||
],
|
||||
@@ -50,7 +56,10 @@
|
||||
{
|
||||
"uuid": "dataset-1",
|
||||
"title": "orders",
|
||||
"signature": "{\"title\":\"orders\"}",
|
||||
"fields": {
|
||||
"title": "orders"
|
||||
},
|
||||
"signature": "{\"title\": \"orders\"}",
|
||||
"database_uuid": "db-missing"
|
||||
}
|
||||
]
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
# #region Test.Conftest.IntegrationTestConftest [C:3] [TYPE Module] [SEMANTICS test, conftest, fixtures, integration]
|
||||
# @BRIEF Thin gating layer for integration test fixtures and skip logic.
|
||||
# @RELATION DISPATCHES -> [fixtures.network]
|
||||
# @RELATION DISPATCHES -> [fixtures.postgres]
|
||||
# @RELATION DISPATCHES -> [fixtures.pki]
|
||||
# @RELATION DISPATCHES -> [fixtures.config]
|
||||
# @RELATION DISPATCHES -> [fixtures.superset]
|
||||
# @RELATION DISPATCHES -> [Test.Network.Fixtures]
|
||||
# @RELATION DISPATCHES -> [Test.Postgres.Fixtures]
|
||||
# @RELATION DISPATCHES -> [Test.Pki.PKIFixtures]
|
||||
# @RELATION DISPATCHES -> [Test.Config.Fixtures]
|
||||
# @RELATION DISPATCHES -> [Test.Superset.Fixtures]
|
||||
# @RATIONALE
|
||||
# This file is intentionally thin. All fixture definitions have been moved
|
||||
# to the fixtures/ package modules, loaded via pytest_plugins.
|
||||
|
||||
@@ -9,7 +9,9 @@
|
||||
# @TEST_EDGE identity_mapping -> covered by TestMigrationEngine.test_transform_zip_allows_empty_mapping_as_identity.
|
||||
# @TEST_INVARIANT MigrationPlugin.strict_db_isolation -> VERIFIED_BY: test_dashboard_import_replaces_source_database.
|
||||
# @PRE Docker daemon is available and the shared Superset/PostgreSQL fixtures are healthy.
|
||||
# @POST The imported dataset references the target database ID and no longer references the source database ID.
|
||||
# @POST The imported dataset references the target database ID and no longer references the source
|
||||
# database ID; a new chart bound to the imported dataset is created; the dashboard is updated in
|
||||
# place (slug match under overwrite=true, no duplicate) and its layout references the new chart.
|
||||
# @SIDE_EFFECT Creates and removes Superset database, dataset, chart, and dashboard resources.
|
||||
# @RATIONALE A real export/import cycle is required because mocked orchestration cannot prove Superset resolves the rewritten database UUID during import.
|
||||
# @REJECTED Asserting only transform_zip call arguments was rejected — it cannot detect an archive that Superset imports against the source database.
|
||||
@@ -94,6 +96,7 @@ async def test_dashboard_import_replaces_source_database(
|
||||
dataset_id = None
|
||||
imported_dataset_id = None
|
||||
chart_id = None
|
||||
imported_chart_id = None
|
||||
dashboard_id = None
|
||||
imported_dashboard_id = None
|
||||
|
||||
@@ -229,8 +232,49 @@ async def test_dashboard_import_replaces_source_database(
|
||||
for item in imported_dashboards
|
||||
if int(item["id"]) != dashboard_id
|
||||
]
|
||||
if imported_dashboard_ids:
|
||||
imported_dashboard_id = imported_dashboard_ids[0]
|
||||
# Observed Superset 4.1.2 semantics (pinned 2026-09-07): although resource UUIDs are
|
||||
# isolated, the dashboard import matches the EXISTING dashboard by slug under
|
||||
# overwrite=true and updates it in place — no second dashboard with the same title
|
||||
# is created.
|
||||
assert imported_dashboard_ids == [], (
|
||||
f"Slug-matched overwrite must not duplicate the dashboard, got extra ids "
|
||||
f"{imported_dashboard_ids}"
|
||||
)
|
||||
assert len(imported_dashboards) == 1
|
||||
imported_dashboard_id = dashboard_id
|
||||
|
||||
# Chart chain: the imported chart is a NEW chart (isolated UUID) bound to the
|
||||
# imported dataset (which itself is bound to the target database).
|
||||
_, all_charts = await superset_client.get_charts()
|
||||
imported_chart_ids = [
|
||||
int(item["id"])
|
||||
for item in all_charts
|
||||
if item.get("slice_name") == f"Migration Chart {suffix}"
|
||||
and int(item["id"]) != chart_id
|
||||
]
|
||||
assert len(imported_chart_ids) == 1, (
|
||||
f"Expected exactly one imported chart, got {imported_chart_ids}"
|
||||
)
|
||||
imported_chart_id = imported_chart_ids[0]
|
||||
imported_chart = await superset_client.get_chart(imported_chart_id)
|
||||
imported_chart_result = imported_chart.get("result", imported_chart)
|
||||
# Superset 4.1.2 chart show has no datasource_id field; the dataset binding lives in
|
||||
# params.datasource ("{id}__table") and is rewritten by update_id_refs during import
|
||||
# (boundary evidence: Test.ExtSuperset.ListColumnExposure).
|
||||
imported_chart_params = json.loads(imported_chart_result["params"])
|
||||
assert imported_chart_params["datasource"] == f"{imported_dataset_id}__table", (
|
||||
f"Imported chart params.datasource not remapped to the imported dataset: "
|
||||
f"{imported_chart_params['datasource']}"
|
||||
)
|
||||
|
||||
# Dashboard graph: the in-place updated dashboard layout must reference the
|
||||
# imported chart (Superset rewrites chart ids via update_id_refs during import).
|
||||
imported_dashboard = await superset_client.get_dashboard(imported_dashboard_id)
|
||||
imported_dashboard_result = imported_dashboard.get("result", imported_dashboard)
|
||||
position_json = imported_dashboard_result.get("position_json") or ""
|
||||
assert str(imported_chart_id) in position_json, (
|
||||
"Updated dashboard layout does not reference the imported chart"
|
||||
)
|
||||
finally:
|
||||
if imported_dashboard_id is not None:
|
||||
with suppress(Exception):
|
||||
@@ -241,6 +285,9 @@ async def test_dashboard_import_replaces_source_database(
|
||||
if chart_id is not None:
|
||||
with suppress(Exception):
|
||||
await superset_client.delete_chart(chart_id)
|
||||
if imported_chart_id is not None:
|
||||
with suppress(Exception):
|
||||
await superset_client.delete_chart(imported_chart_id)
|
||||
if dataset_id is not None:
|
||||
with suppress(Exception):
|
||||
await superset_client.delete_dataset(dataset_id)
|
||||
|
||||
426
backend/tests/integration/test_migration_plugin_e2e.py
Normal file
426
backend/tests/integration/test_migration_plugin_e2e.py
Normal file
@@ -0,0 +1,426 @@
|
||||
# #region Test.Migration.PluginE2E [C:5] [TYPE Module] [SEMANTICS test,migration,plugin,superset,testcontainers,e2e]
|
||||
# @BRIEF Real-plugin migration E2E on live Superset: an unmapped source database blocks exactly one
|
||||
# dashboard (PARTIAL_SUCCESS batch invariant, phase=transform, no ingestion), the mapped dashboard
|
||||
# imports successfully without Superset creating any new database (UUID rewrite hits the existing
|
||||
# target DB), and an identity dry-run mutates zero target resources.
|
||||
# @RELATION BINDS_TO -> [Plugin.Migration.MigrationPlugin]
|
||||
# @RELATION BINDS_TO -> [Core.MigrationEngine.MigrationEngineModule]
|
||||
# @RELATION BINDS_TO -> [Core.DryRunOrchestrator.MigrationDryRunService]
|
||||
# @RELATION DEPENDS_ON -> [Test.Conftest.IntegrationTestConftest]
|
||||
# @TEST_CONTRACT MigrationPlugin.execute(2 selected dashboards, db_mappings covering only one source
|
||||
# DB UUID) -> {status: PARTIAL_SUCCESS, migrated: [mapped dashboard], failed: [unmapped dashboard,
|
||||
# phase=transform]} AND the rejected dashboard's dataset is untouched AND the total Superset
|
||||
# database count is unchanged (same-UUID overwrite updates in place without creating databases).
|
||||
# @TEST_FIXTURE Real Superset 4.1.2 + PostgreSQL 16 session fixtures. The single container acts as
|
||||
# both source and target; the client import always sends overwrite=true, so a same-UUID import
|
||||
# updates resources in place — that is what makes the database rebind observable without a second
|
||||
# Superset instance.
|
||||
# @TEST_EDGE: unmapped_source_database -> MigrationEngine.transform_zip rejects the archive
|
||||
# (failed entry phase=transform); Superset import is never attempted for that dashboard.
|
||||
# @TEST_EDGE: partial_batch_failure -> one failed dashboard never aborts the batch; the other is
|
||||
# still migrated (plugin @INVARIANT: per-dashboard failure -> PARTIAL_SUCCESS).
|
||||
# @TEST_EDGE: dry_run_read_only -> MigrationDryRunService.run over a real target mutates nothing.
|
||||
# @TEST_EDGE: dry_run_create_only_on_4_1_2 -> the pinned 4.1.2 LIST drops uuid for dashboards/
|
||||
# datasets/charts, so the diff target index is empty and the selected dashboard appears in
|
||||
# diff.dashboards.create (deterministic version-scoped behavior, pinned by
|
||||
# Test.ExtSuperset.ListColumnExposure; the intersection comparison fix in
|
||||
# Core.DryRunOrchestrator.BuildObjectDiff is unit-proven in tests/core/migration/).
|
||||
# @TEST_INVARIANT MigrationPlugin.strict_db_isolation -> VERIFIED_BY: [test_partial_mapping_yields_partial_success]
|
||||
# (unmapped archive never reaches Superset ingestion — rejected at transform; unmapped dataset
|
||||
# keeps its source database binding; no database is created behind the mapping. The fresh-object
|
||||
# rebind to the target database is proven by Test.Migration.DatabaseReplacementE2E with isolated
|
||||
# UUIDs — the cross-instance migration shape.)
|
||||
# @TEST_INVARIANT Core.DryRunOrchestrator.dry_run_never_mutates_target -> VERIFIED_BY: [test_dry_run_reports_diff_without_mutating_target]
|
||||
# @TEST_INVARIANT Core.MigrationEngine.TransformDatabaseYaml.no_database_creation_on_uuid_match ->
|
||||
# VERIFIED_BY: [test_partial_mapping_yields_partial_success] (database count before == after;
|
||||
# regression-guards the @REJECTED strip_databases=True GENERIC_COMMAND_ERROR cascade by proving
|
||||
# the UUID-rewrite path hits the existing target DB instead of creating one)
|
||||
# @PRE Docker daemon available; shared Superset/PostgreSQL fixtures healthy; global DATABASE_URL is
|
||||
# the migrated integration PG (the plugin opens real SessionLocal / IdMappingService sessions and
|
||||
# runs its real fail-safe post-migration hooks).
|
||||
# @POST Plugin returns PARTIAL_SUCCESS with exactly one migrated and one failed dashboard; Superset
|
||||
# state reflects the rebind for the mapped graph only; dry-run returns a structured pre-flight
|
||||
# payload with a bounded risk score and leaves all target resource counts unchanged.
|
||||
# @SIDE_EFFECT Creates/deletes Superset databases, datasets, charts, dashboards; creates/drops
|
||||
# physical PG tables; plugin post-hooks may write ResourceMapping rows into the integration DB
|
||||
# (each hook is fail-safe wrapped in production code and cannot alter the returned status).
|
||||
# @RATIONALE Plugin-level invariants (batch isolation on per-dashboard failure, rejection of unmapped
|
||||
# DBs BEFORE ingestion, dry-run read-only-ness) were previously verified only with mocked
|
||||
# SupersetClients (tests/plugins/test_migration_plugin*.py). This file removes the mock from the
|
||||
# Superset boundary so Superset's real import/overwrite and match-database-by-UUID behavior are
|
||||
# part of the proof — the exact behavior the production @RATIONALE of TransformDatabaseYaml relies on.
|
||||
# @REJECTED Mocking SupersetClient here was rejected — it cannot prove Superset resolves rewritten
|
||||
# database UUIDs or that a rejected archive truly never reaches ingestion. Patching
|
||||
# get_task_manager was rejected — TaskManager construction is passive and the unit suite already
|
||||
# exercises execute() without patching it.
|
||||
# NOTE (mocked boundary): only the environment CATALOG (src.plugins.migration.get_config_manager) is
|
||||
# stubbed — the same seam the unit suite uses. It supplies two real config_models.Environment
|
||||
# records pointing at the live container. Every HTTP call, ZIP transform, DB session, error
|
||||
# classification and post-hook runs unmocked.
|
||||
from contextlib import suppress
|
||||
import json
|
||||
from urllib.parse import urlparse
|
||||
from unittest.mock import patch
|
||||
from uuid import uuid4
|
||||
|
||||
import pytest
|
||||
from sqlalchemy import text
|
||||
|
||||
from src.core.config_models import Environment
|
||||
from src.core.migration.dry_run_orchestrator import MigrationDryRunService
|
||||
from src.models.dashboard import DashboardSelection
|
||||
from src.plugins.migration import MigrationPlugin
|
||||
|
||||
|
||||
# #region Test.Migration.PluginE2E.EnvCatalog [C:1] [TYPE Class]
|
||||
class _EnvCatalog:
|
||||
"""Minimal environment-catalog stub: get_environments()/get_environment() over real Environment objects."""
|
||||
|
||||
def __init__(self, envs: list[Environment]):
|
||||
self._envs = envs
|
||||
|
||||
def get_environments(self) -> list[Environment]:
|
||||
return list(self._envs)
|
||||
|
||||
def get_environment(self, env_id: str) -> Environment | None:
|
||||
return next(
|
||||
(e for e in self._envs if e.id == env_id or e.name == env_id), None
|
||||
)
|
||||
# #endregion Test.Migration.PluginE2E.EnvCatalog
|
||||
|
||||
|
||||
# #region Test.Migration.PluginE2E.ResourceId [C:1] [TYPE Function]
|
||||
def _resource_id(response: dict) -> int:
|
||||
resource_id = response.get("id")
|
||||
if resource_id is None:
|
||||
result = response.get("result", {})
|
||||
resource_id = result.get("id") if isinstance(result, dict) else None
|
||||
if resource_id is None:
|
||||
raise AssertionError(f"Superset create response has no resource id: {response}")
|
||||
return int(resource_id)
|
||||
# #endregion Test.Migration.PluginE2E.ResourceId
|
||||
|
||||
|
||||
# #region Test.Migration.PluginE2E.DatabaseUuid [C:1] [TYPE Function]
|
||||
async def _database_uuid(client, database_id: int) -> str:
|
||||
response = await client.get_database(database_id)
|
||||
result = response.get("result", response)
|
||||
return str(result["uuid"])
|
||||
# #endregion Test.Migration.PluginE2E.DatabaseUuid
|
||||
|
||||
|
||||
# #region Test.Migration.PluginE2E.ProvisionGraph [C:2] [TYPE Function]
|
||||
# @BRIEF Provision one full dashboard graph (PG table -> Superset database -> dataset -> dashboard -> chart).
|
||||
# @POST Returns a dict with every created id plus the database UUID and physical table name.
|
||||
async def _provision_dashboard_graph(
|
||||
superset_client, pg_engine, database_uri: str, suffix: str, tag: str
|
||||
) -> dict:
|
||||
table_name = f"mig_plugin_{tag}_{suffix}"
|
||||
with pg_engine.begin() as conn:
|
||||
conn.execute(
|
||||
text(f'CREATE TABLE "{table_name}" (id INTEGER PRIMARY KEY, label VARCHAR(32))')
|
||||
)
|
||||
conn.execute(
|
||||
text(f'INSERT INTO "{table_name}" (id, label) VALUES (1, \'{tag}-row\')')
|
||||
)
|
||||
|
||||
db_resp = await superset_client.create_database(
|
||||
database_name=f"MigPlugin {tag} {suffix}",
|
||||
sqlalchemy_uri=database_uri,
|
||||
)
|
||||
database_id = _resource_id(db_resp)
|
||||
|
||||
ds_resp = await superset_client.create_dataset(
|
||||
table_name=table_name,
|
||||
database=database_id,
|
||||
schema_name="public",
|
||||
)
|
||||
dataset_id = _resource_id(ds_resp)
|
||||
|
||||
dash_resp = await superset_client.create_dashboard(
|
||||
dashboard_title=f"MigPlugin {tag} {suffix}",
|
||||
slug=f"mig-plugin-{tag}-{suffix}",
|
||||
published=True,
|
||||
)
|
||||
dashboard_id = _resource_id(dash_resp)
|
||||
|
||||
chart_resp = await superset_client.client.request(
|
||||
method="POST",
|
||||
endpoint="/chart/",
|
||||
data={
|
||||
"dashboards": [dashboard_id],
|
||||
"datasource_id": dataset_id,
|
||||
"datasource_type": "table",
|
||||
"slice_name": f"MigPlugin Chart {tag} {suffix}",
|
||||
"viz_type": "table",
|
||||
"params": json.dumps(
|
||||
{
|
||||
"datasource": f"{dataset_id}__table",
|
||||
"viz_type": "table",
|
||||
"all_columns": ["id", "label"],
|
||||
"row_limit": 100,
|
||||
}
|
||||
),
|
||||
},
|
||||
)
|
||||
chart_id = _resource_id(chart_resp)
|
||||
|
||||
return {
|
||||
"table_name": table_name,
|
||||
"database_id": database_id,
|
||||
"database_uuid": await _database_uuid(superset_client, database_id),
|
||||
"dataset_id": dataset_id,
|
||||
"dashboard_id": dashboard_id,
|
||||
"chart_id": chart_id,
|
||||
"title": f"MigPlugin {tag} {suffix}",
|
||||
}
|
||||
# #endregion Test.Migration.PluginE2E.ProvisionGraph
|
||||
|
||||
|
||||
# #region Test.Migration.PluginE2E.CleanupGraph [C:1] [TYPE Function]
|
||||
async def _cleanup_dashboard_graph(superset_client, pg_engine, graph: dict | None) -> None:
|
||||
if not graph:
|
||||
return
|
||||
for key, method in (
|
||||
("chart_id", superset_client.delete_chart),
|
||||
("dashboard_id", superset_client.delete_dashboard),
|
||||
("dataset_id", superset_client.delete_dataset),
|
||||
("database_id", superset_client.delete_database),
|
||||
):
|
||||
resource_id = graph.get(key)
|
||||
if resource_id is not None:
|
||||
with suppress(Exception):
|
||||
await method(resource_id)
|
||||
with pg_engine.begin() as conn:
|
||||
conn.execute(text(f'DROP TABLE IF EXISTS "{graph["table_name"]}"'))
|
||||
# #endregion Test.Migration.PluginE2E.CleanupGraph
|
||||
|
||||
|
||||
# #region Test.Migration.PluginE2E.Test [C:4] [TYPE Class] [SEMANTICS test,migration,plugin,e2e]
|
||||
# @ingroup Test.Migration.PluginE2E
|
||||
# @BRIEF Plugin batch + engine rejection + dry-run read-only E2E against live Superset.
|
||||
@pytest.mark.integration
|
||||
class TestMigrationPluginE2E:
|
||||
|
||||
# #region Test.Migration.PluginE2E.PartialMappingPartialSuccess [C:4] [TYPE Function]
|
||||
# @BRIEF Two real dashboards, mapping covers only one source DB: unmapped graph is rejected at
|
||||
# transform (never ingested), mapped graph is imported and re-bound to the target DB, batch
|
||||
# returns PARTIAL_SUCCESS, and Superset creates no new database (UUID-rewrite hits existing).
|
||||
# @TEST_EDGE: unmapped_source_database -> VERIFIED_BY: this test (phase=transform assertion)
|
||||
# @TEST_EDGE: partial_batch_failure -> VERIFIED_BY: this test (migrated contains the mapped graph)
|
||||
@pytest.mark.asyncio
|
||||
async def test_partial_mapping_yields_partial_success(
|
||||
self,
|
||||
superset_client,
|
||||
superset_url,
|
||||
superset_admin_password,
|
||||
superset_db_url,
|
||||
pg_engine,
|
||||
):
|
||||
suffix = uuid4().hex[:10]
|
||||
parsed = urlparse(superset_db_url)
|
||||
database_uri = (
|
||||
f"postgresql://test:test@{parsed.hostname}:{parsed.port}/test_translate"
|
||||
)
|
||||
|
||||
graph_a = None
|
||||
graph_b = None
|
||||
target_db_id = None
|
||||
try:
|
||||
graph_a = await _provision_dashboard_graph(
|
||||
superset_client, pg_engine, database_uri, suffix, "a"
|
||||
)
|
||||
graph_b = await _provision_dashboard_graph(
|
||||
superset_client, pg_engine, database_uri, suffix, "b"
|
||||
)
|
||||
tgt_resp = await superset_client.create_database(
|
||||
database_name=f"MigPlugin Target {suffix}",
|
||||
sqlalchemy_uri=database_uri,
|
||||
)
|
||||
target_db_id = _resource_id(tgt_resp)
|
||||
target_db_uuid = await _database_uuid(superset_client, target_db_id)
|
||||
|
||||
databases_before, _ = await superset_client.get_databases()
|
||||
|
||||
env_src = Environment(
|
||||
id=f"mig-e2e-src-{suffix}",
|
||||
name=f"MigE2E Source {suffix}",
|
||||
url=superset_url,
|
||||
username="admin",
|
||||
password=superset_admin_password,
|
||||
verify_ssl=False,
|
||||
timeout=30,
|
||||
)
|
||||
env_tgt = Environment(
|
||||
id=f"mig-e2e-tgt-{suffix}",
|
||||
name=f"MigE2E Target {suffix}",
|
||||
url=superset_url,
|
||||
username="admin",
|
||||
password=superset_admin_password,
|
||||
verify_ssl=False,
|
||||
timeout=30,
|
||||
)
|
||||
|
||||
params = {
|
||||
"source_env_id": env_src.id,
|
||||
"target_env_id": env_tgt.id,
|
||||
"selected_ids": [graph_a["dashboard_id"], graph_b["dashboard_id"]],
|
||||
# Only graph A's source database is mapped; B is intentionally left out.
|
||||
"db_mappings": {graph_a["database_uuid"]: target_db_uuid},
|
||||
"replace_db_config": False,
|
||||
# Deterministic scope: cross-filter patching and composite-key sync are
|
||||
# separate contracts with their own unit coverage; this E2E proves the
|
||||
# export -> transform-gate -> import -> PARTIAL_SUCCESS pipeline.
|
||||
"fix_cross_filters": False,
|
||||
"sync_dataset_composite_keys": False,
|
||||
}
|
||||
|
||||
with patch(
|
||||
"src.plugins.migration.get_config_manager",
|
||||
return_value=_EnvCatalog([env_src, env_tgt]),
|
||||
):
|
||||
result = await MigrationPlugin().execute(params)
|
||||
|
||||
# ── Batch invariant: per-dashboard failure never aborts the batch ──
|
||||
assert result["status"] == "PARTIAL_SUCCESS", f"Unexpected status: {result}"
|
||||
assert result["selected_dashboards"] == 2
|
||||
assert [d["id"] for d in result["migrated_dashboards"]] == [graph_a["dashboard_id"]]
|
||||
|
||||
# ── Rejection edge: unmapped DB blocks exactly graph B, at transform phase ──
|
||||
failed = result["failed_dashboards"]
|
||||
assert [d["id"] for d in failed] == [graph_b["dashboard_id"]]
|
||||
assert failed[0]["phase"] == "transform"
|
||||
assert failed[0]["error"], "failed entry must carry a non-empty error"
|
||||
|
||||
# ── strict_db_isolation (single-container mode): observed Superset 4.1.2 semantics
|
||||
# are pinned below. The same-UUID import runs with overwrite=true and updates the
|
||||
# existing graph IN PLACE; dataset overwrite does NOT rebind database_id, so the
|
||||
# mapped dataset keeps its existing binding while the rejected graph B is provably
|
||||
# never ingested. The fresh-object rebind (a NEW dataset created bound to the
|
||||
# target database) is proven by test_dashboard_migration_db_replacement.py with
|
||||
# isolated UUIDs — the cross-instance migration shape. ──
|
||||
ds_a_after = await superset_client.get_dataset(graph_a["dataset_id"])
|
||||
ds_a_result = ds_a_after.get("result", ds_a_after)
|
||||
ds_a_db_id = int(
|
||||
ds_a_result.get("database_id")
|
||||
or (ds_a_result.get("database") or {}).get("id")
|
||||
)
|
||||
assert ds_a_db_id == graph_a["database_id"], (
|
||||
"same-UUID overwrite is expected to keep dataset A's existing binding; "
|
||||
f"observed database {ds_a_db_id}"
|
||||
)
|
||||
|
||||
ds_b_after = await superset_client.get_dataset(graph_b["dataset_id"])
|
||||
ds_b_result = ds_b_after.get("result", ds_b_after)
|
||||
ds_b_db_id = int(
|
||||
ds_b_result.get("database_id")
|
||||
or (ds_b_result.get("database") or {}).get("id")
|
||||
)
|
||||
assert ds_b_db_id == graph_b["database_id"], (
|
||||
"rejected dashboard's dataset must keep its source database binding"
|
||||
)
|
||||
|
||||
# ── UUID-rewrite path: Superset matched the existing target DB by UUID and
|
||||
# created NO new database (the strip_databases cascade stays rejected) ──
|
||||
databases_after, _ = await superset_client.get_databases()
|
||||
assert databases_after == databases_before, (
|
||||
f"Superset database count changed during migration: "
|
||||
f"{databases_before} -> {databases_after}"
|
||||
)
|
||||
finally:
|
||||
await _cleanup_dashboard_graph(superset_client, pg_engine, graph_a)
|
||||
await _cleanup_dashboard_graph(superset_client, pg_engine, graph_b)
|
||||
if target_db_id is not None:
|
||||
with suppress(Exception):
|
||||
await superset_client.delete_database(target_db_id)
|
||||
# #endregion Test.Migration.PluginE2E.PartialMappingPartialSuccess
|
||||
|
||||
# #region Test.Migration.PluginE2E.DryRunReadOnly [C:3] [TYPE Function]
|
||||
# @BRIEF Identity dry-run over a real target: structured pre-flight payload, bounded risk score,
|
||||
# zero mutations of any target resource class.
|
||||
# @TEST_EDGE: dry_run_read_only -> VERIFIED_BY: this test
|
||||
# @TEST_EDGE: dry_run_create_only_on_4_1_2 -> VERIFIED_BY: this test (create-bucket pin for
|
||||
# the uuid-less 4.1.2 LIST exposure)
|
||||
@pytest.mark.asyncio
|
||||
async def test_dry_run_reports_diff_without_mutating_target(
|
||||
self,
|
||||
superset_client,
|
||||
superset_db_url,
|
||||
pg_engine,
|
||||
db_session,
|
||||
):
|
||||
suffix = uuid4().hex[:10]
|
||||
parsed = urlparse(superset_db_url)
|
||||
database_uri = (
|
||||
f"postgresql://test:test@{parsed.hostname}:{parsed.port}/test_translate"
|
||||
)
|
||||
|
||||
graph = None
|
||||
try:
|
||||
graph = await _provision_dashboard_graph(
|
||||
superset_client, pg_engine, database_uri, suffix, "dry"
|
||||
)
|
||||
|
||||
async def _resource_counts() -> tuple[int, int, int, int]:
|
||||
dbs, _ = await superset_client.get_databases()
|
||||
dss, _ = await superset_client.get_datasets()
|
||||
chs, _ = await superset_client.get_charts()
|
||||
dsh, _ = await superset_client.get_dashboards()
|
||||
return dbs, dss, chs, dsh
|
||||
|
||||
counts_before = await _resource_counts()
|
||||
|
||||
selection = DashboardSelection(
|
||||
selected_ids=[graph["dashboard_id"]],
|
||||
source_env_id="dry-run-src",
|
||||
target_env_id="dry-run-tgt",
|
||||
replace_db_config=False,
|
||||
fix_cross_filters=False,
|
||||
)
|
||||
|
||||
payload = await MigrationDryRunService().run(
|
||||
selection, superset_client, superset_client, db_session
|
||||
)
|
||||
|
||||
# ── Read-only invariant: nothing was created/updated/deleted on the target ──
|
||||
counts_after = await _resource_counts()
|
||||
assert counts_after == counts_before, (
|
||||
f"dry-run mutated target resources: {counts_before} -> {counts_after}"
|
||||
)
|
||||
|
||||
# ── Structured pre-flight payload (hardcoded expectations from provisioned state) ──
|
||||
assert payload["summary"]["selected_dashboards"] == 1
|
||||
assert payload["selected_dashboard_titles"] == [graph["title"]]
|
||||
for object_type in ("dashboards", "charts", "datasets"):
|
||||
assert set(payload["diff"][object_type]) == {"create", "update", "delete"}
|
||||
assert payload["summary"][object_type]["create"] == len(
|
||||
payload["diff"][object_type]["create"]
|
||||
)
|
||||
# ── Diff-bucket semantics (VERSION-SCOPED to the pinned 4.1.2 container) ──
|
||||
# The false-update degradation is FIXED: Core.DryRunOrchestrator.BuildObjectDiff now
|
||||
# compares only the intersection of presence-checked canonical `fields` produced by
|
||||
# Core.ArchiveParser.NormalizeObjectPayload (archive side, incl. the `position` ->
|
||||
# position_json key mapping) and Core.DryRunOrchestrator.BuildTargetSignatures (LIST
|
||||
# side) — unit-proven in tests/core/migration/test_dry_run_orchestrator.py.
|
||||
# On the pinned 4.1.2 container, LIST still does not expose uuid for dashboards/
|
||||
# datasets/charts (pinned by tests/integration/test_superset_list_column_exposure.py),
|
||||
# so the target index is EMPTY and the diff deterministically degrades to create-only:
|
||||
# the selected dashboard appears in diff.dashboards.create with its archive uuid.
|
||||
create_entries = payload["diff"]["dashboards"]["create"]
|
||||
selected = [e for e in create_entries if e["title"] == graph["title"]]
|
||||
assert len(selected) == 1, (
|
||||
f"selected dashboard missing from the create-only 4.1.2 diff: {create_entries}"
|
||||
)
|
||||
assert selected[0]["uuid"], "create entry must carry the archive-sourced uuid"
|
||||
assert payload["diff"]["dashboards"]["update"] == [], (
|
||||
"4.1.2 has an empty target index — nothing can be bucketed as update"
|
||||
)
|
||||
|
||||
risk = payload["risk"]
|
||||
assert isinstance(risk["score"], int) and 0 <= risk["score"] <= 100
|
||||
assert risk["level"] in ("low", "medium", "high")
|
||||
finally:
|
||||
await _cleanup_dashboard_graph(superset_client, pg_engine, graph)
|
||||
# #endregion Test.Migration.PluginE2E.DryRunReadOnly
|
||||
# #endregion Test.Migration.PluginE2E.Test
|
||||
# #endregion Test.Migration.PluginE2E
|
||||
194
backend/tests/integration/test_superset_list_column_exposure.py
Normal file
194
backend/tests/integration/test_superset_list_column_exposure.py
Normal file
@@ -0,0 +1,194 @@
|
||||
# #region Test.ExtSuperset.ListColumnExposure [C:3] [TYPE Module] [SEMANTICS test,superset,external-boundary,columns,integration]
|
||||
# @BRIEF Characterization test pinning what the Superset 4.1.2 testcontainer LIST/SHOW endpoints
|
||||
# return for explicit `columns` queries — uuid/database_uuid/datasource_uuid/owners/description
|
||||
# are silently dropped from /dashboard/, /dataset/ and /chart/ list responses, and 4.1.2 SHOW
|
||||
# responses omit uuid for dashboards/datasets/charts (newer builds re-expose several of these —
|
||||
# see @RATIONALE and docs/openapi/superset).
|
||||
# @RELATION BINDS_TO -> [Core.Init.SupersetClient]
|
||||
# @RELATION DEPENDS_ON -> [EXT:Superset:REST API v1]
|
||||
# @TEST_CONTRACT SupersetClient.get_dashboards/get_datasets/get_charts with explicit columns ->
|
||||
# Superset intersects requested columns with the endpoint's allowed list columns and silently
|
||||
# omits the rest (no error, no warning). Show/detail endpoints likewise omit uuid for
|
||||
# dashboards/datasets/charts; only database show exposes uuid.
|
||||
# @TEST_EDGE: uuid_requested_on_list -> column silently absent from every item (dashboards,
|
||||
# datasets, charts) — REST consumers cannot resolve these UUIDs at all on 4.1.2.
|
||||
# @TEST_EDGE: uuid_on_show -> on the pinned 4.1.2 build, dashboard/dataset/chart detail responses
|
||||
# contain no uuid key; newer builds expose uuid on both LIST and SHOW (live prod probe
|
||||
# 2026-09-07 + docs/openapi/superset schemas), so this whole file is 4.1.2-scoped by design.
|
||||
# @TEST_EDGE: nested_fk_uuid_requested -> database_uuid / datasource_uuid / dataset_uuid silently
|
||||
# absent from dataset/chart list items; chart detail carries the dataset ref only inside
|
||||
# params.datasource ("{id}__table").
|
||||
# @RATIONALE This pins an [EXT:Superset] boundary fact discovered on 2026-09-07 while building the
|
||||
# migration dry-run E2E, VERSION-SCOPED to the pinned 4.1.2 testcontainer:
|
||||
# Core.DryRunOrchestrator.BuildTargetSignatures requests uuid columns via LIST endpoints,
|
||||
# receives items WITHOUT uuid, and filters them out (`if item.get("uuid")`) — so on Superset
|
||||
# 4.1.2 the dry-run target signature set is EMPTY and the diff degrades to create-only.
|
||||
# Unit tests mocked the column exposure and never caught it.
|
||||
# CROSS-VERSION EVIDENCE (docs/openapi/superset snapshot == live ss-prod build spec, schemas
|
||||
# identical; live read-only probe 2026-09-07): newer builds expose `uuid` on LIST for ALL four
|
||||
# resources (runtime `list_columns` includes uuid; 6.x-generation markers: catalog/kind on
|
||||
# datasets, allow_multi_catalog on databases, theme on dashboards) AND on SHOW
|
||||
# (dashboard uuid; chart uuid+datasource_id+datasource_uuid; dataset uuid + nested database.uuid;
|
||||
# database uuid). So the create-only degradation below is a 4.1.2-generation defect. On newer
|
||||
# builds the dry-run UUID bucketing works. Dashboard comparison fidelity WAS broken there
|
||||
# (position_json/json_metadata/description/owners are not LIST columns, so target signatures
|
||||
# carried None against archive-sourced non-None values -> every existing dashboard was
|
||||
# over-reported as "update"); it is FIXED: Core.ArchiveParser.NormalizeObjectPayload now maps
|
||||
# the archive `position` key into the canonical position_json field and emits presence-checked
|
||||
# canonical `fields`, and Core.DryRunOrchestrator.BuildObjectDiff compares only the
|
||||
# intersection of fields obtainable on both sides (unit-proven in
|
||||
# tests/core/migration/test_dry_run_orchestrator.py). Export archives and SHOW endpoints are
|
||||
# both viable UUID sources on newer builds; export archives remain the version-independent one.
|
||||
# If the container is upgraded and the assertions here fail — intentionally — re-evaluate this
|
||||
# file against the new build's column exposure.
|
||||
# @REJECTED Asserting the dry-run diff semantics here was rejected — this file pins only the
|
||||
# external boundary behavior; dry-run diff semantics are pinned in tests/core/migration/
|
||||
# (intersection comparison) and the 4.1.2-scoped create-only pin in
|
||||
# tests/integration/test_migration_plugin_e2e.py.
|
||||
# @PRE Docker daemon available; shared Superset fixture healthy; one provisioned resource graph.
|
||||
# @POST All three list endpoints return items containing only the intersection of requested and
|
||||
# API-allowed columns; uuid-family fields are absent.
|
||||
# @SIDE_EFFECT Creates and removes one PG table plus Superset database/dataset/dashboard/chart.
|
||||
from contextlib import suppress
|
||||
import json
|
||||
from urllib.parse import urlparse
|
||||
from uuid import uuid4
|
||||
|
||||
import pytest
|
||||
from sqlalchemy import text
|
||||
|
||||
|
||||
# #region Test.ExtSuperset.ListColumnExposure.Test [C:3] [TYPE Function]
|
||||
# @ingroup Test.ExtSuperset.ListColumnExposure
|
||||
# @BRIEF Provision one graph, request uuid-family columns on all three list endpoints, pin absence.
|
||||
@pytest.mark.integration
|
||||
@pytest.mark.asyncio
|
||||
async def test_list_endpoints_silently_drop_uuid_columns(
|
||||
superset_client, superset_db_url, pg_engine
|
||||
):
|
||||
suffix = uuid4().hex[:10]
|
||||
parsed = urlparse(superset_db_url)
|
||||
database_uri = (
|
||||
f"postgresql://test:test@{parsed.hostname}:{parsed.port}/test_translate"
|
||||
)
|
||||
table_name = f"ext_cols_probe_{suffix}"
|
||||
with pg_engine.begin() as conn:
|
||||
conn.execute(text(f'CREATE TABLE "{table_name}" (id INTEGER PRIMARY KEY)'))
|
||||
|
||||
db_resp = await superset_client.create_database(
|
||||
database_name=f"ExtColsProbe {suffix}", sqlalchemy_uri=database_uri
|
||||
)
|
||||
db_id = int(db_resp.get("id") or db_resp.get("result", {}).get("id"))
|
||||
ds_resp = await superset_client.create_dataset(
|
||||
table_name=table_name, database=db_id, schema_name="public"
|
||||
)
|
||||
ds_id = int(ds_resp.get("id") or ds_resp.get("result", {}).get("id"))
|
||||
dash_resp = await superset_client.create_dashboard(
|
||||
dashboard_title=f"ExtColsProbe {suffix}", slug=f"ext-cols-probe-{suffix}"
|
||||
)
|
||||
dash_id = int(dash_resp.get("id") or dash_resp.get("result", {}).get("id"))
|
||||
chart_resp = await superset_client.client.request(
|
||||
method="POST",
|
||||
endpoint="/chart/",
|
||||
data={
|
||||
"dashboards": [dash_id],
|
||||
"datasource_id": ds_id,
|
||||
"datasource_type": "table",
|
||||
"slice_name": f"ExtColsProbe Chart {suffix}",
|
||||
"viz_type": "table",
|
||||
"params": json.dumps(
|
||||
{"datasource": f"{ds_id}__table", "viz_type": "table"}
|
||||
),
|
||||
},
|
||||
)
|
||||
chart_id = int(chart_resp.get("id") or chart_resp.get("result", {}).get("id"))
|
||||
|
||||
try:
|
||||
# Requested columns mirror Core.DryRunOrchestrator.BuildTargetSignatures exactly.
|
||||
_, dashboards = await superset_client.get_dashboards(
|
||||
query={
|
||||
"columns": [
|
||||
"uuid", "dashboard_title", "slug", "position_json",
|
||||
"json_metadata", "description", "owners",
|
||||
]
|
||||
}
|
||||
)
|
||||
probe_dash = next(
|
||||
item for item in dashboards if item.get("slug") == f"ext-cols-probe-{suffix}"
|
||||
)
|
||||
# Allowed list columns come back; the uuid family is silently dropped.
|
||||
assert probe_dash.get("dashboard_title") == f"ExtColsProbe {suffix}"
|
||||
assert "uuid" not in probe_dash
|
||||
assert "owners" not in probe_dash
|
||||
assert "description" not in probe_dash
|
||||
|
||||
_, datasets = await superset_client.get_datasets(
|
||||
query={
|
||||
"columns": [
|
||||
"uuid", "table_name", "schema", "database_uuid",
|
||||
"sql", "columns", "metrics",
|
||||
]
|
||||
}
|
||||
)
|
||||
probe_ds = next(
|
||||
item for item in datasets if item.get("table_name") == table_name
|
||||
)
|
||||
assert probe_ds.get("schema") == "public"
|
||||
assert "uuid" not in probe_ds
|
||||
assert "database_uuid" not in probe_ds
|
||||
|
||||
_, charts = await superset_client.get_charts(
|
||||
query={
|
||||
"columns": [
|
||||
"uuid", "slice_name", "viz_type", "params",
|
||||
"query_context", "datasource_uuid", "dataset_uuid",
|
||||
]
|
||||
}
|
||||
)
|
||||
probe_chart = next(
|
||||
item
|
||||
for item in charts
|
||||
if item.get("slice_name") == f"ExtColsProbe Chart {suffix}"
|
||||
)
|
||||
assert probe_chart.get("viz_type") == "table"
|
||||
assert "uuid" not in probe_chart
|
||||
assert "datasource_uuid" not in probe_chart
|
||||
assert "dataset_uuid" not in probe_chart
|
||||
|
||||
# Detail (show) endpoints — observed Superset 4.1.2 exposure, pinned: dashboards,
|
||||
# datasets and charts do NOT expose uuid on show either (only GET /database/{id}
|
||||
# does — see _database_uuid consumers). Dataset show carries a nested `database`
|
||||
# object; chart show carries the dataset reference ONLY inside the params JSON
|
||||
# ("datasource": "{id}__table"). Consumers needing resource UUIDs must use export
|
||||
# archives, not REST list/show.
|
||||
dash_detail = await superset_client.get_dashboard(dash_id)
|
||||
dash_result = dash_detail.get("result", dash_detail)
|
||||
assert "uuid" not in dash_result
|
||||
assert dash_result.get("slug") == f"ext-cols-probe-{suffix}"
|
||||
assert "position_json" in dash_result
|
||||
|
||||
ds_detail = await superset_client.get_dataset(ds_id)
|
||||
ds_result = ds_detail.get("result", ds_detail)
|
||||
assert "uuid" not in ds_result
|
||||
assert ds_result.get("table_name") == table_name
|
||||
assert ds_result["database"]["id"] == db_id
|
||||
|
||||
chart_detail = await superset_client.get_chart(chart_id)
|
||||
chart_result = chart_detail.get("result", chart_detail)
|
||||
assert "uuid" not in chart_result
|
||||
assert "datasource_id" not in chart_result
|
||||
chart_params = json.loads(chart_result["params"])
|
||||
assert chart_params["datasource"] == f"{ds_id}__table"
|
||||
finally:
|
||||
with suppress(Exception):
|
||||
await superset_client.delete_chart(chart_id)
|
||||
with suppress(Exception):
|
||||
await superset_client.delete_dashboard(dash_id)
|
||||
with suppress(Exception):
|
||||
await superset_client.delete_dataset(ds_id)
|
||||
with suppress(Exception):
|
||||
await superset_client.delete_database(db_id)
|
||||
with pg_engine.begin() as conn:
|
||||
conn.execute(text(f'DROP TABLE IF EXISTS "{table_name}"'))
|
||||
# #endregion Test.ExtSuperset.ListColumnExposure.Test
|
||||
# #endregion Test.ExtSuperset.ListColumnExposure
|
||||
@@ -1,6 +1,6 @@
|
||||
# #region Test.TranslateClickhouse.TestTranslateClickHouseIntegration [C:3] [TYPE Module] [SEMANTICS test,translate,clickhouse,integration]
|
||||
# @BRIEF Integration tests for ClickHouse insert path using testcontainers.
|
||||
# @RELATION BINDS_TO -> [_batch_insert_module]
|
||||
# @RELATION BINDS_TO -> [Plugin.BatchInsert.BatchInsertService]
|
||||
# @RELATION BINDS_TO -> [Plugin.SqlGenerator.SQLGenerator]
|
||||
#
|
||||
# @TEST_CONTRACT ClickHouseInsert ->
|
||||
|
||||
@@ -1,33 +1,30 @@
|
||||
# #region Test.Integration.TranslatePgE2E [C:5] [TYPE Module] [SEMANTICS test,integration,translate,e2e,postgres,llm-stub,testcontainers,resource-projection]
|
||||
# #region Test.Integration.TranslatePgE2E [C:5] [TYPE Module] [SEMANTICS test,integration,translate,e2e,postgres,llm-stub,testcontainers]
|
||||
# @BRIEF PostgreSQL translation pipeline E2E: seed source table, register in Superset,
|
||||
# execute translation with fake LLM stub, verify TranslationRecord content (target_sql
|
||||
# with translated text), physical rows written via Superset SQL Lab, incremental rerun,
|
||||
# and Superset resource projection (dashboard/dataset list/detail).
|
||||
# with translated text), physical rows written via Superset SQL Lab, and LLM 429 retry
|
||||
# without duplicate rows.
|
||||
# @RELATION BINDS_TO -> [Plugin.Orchestrator.TranslationOrchestrator]
|
||||
# @RELATION BINDS_TO -> [Plugin.OrchestratorExec.TranslationExecutionEngine]
|
||||
# @RELATION BINDS_TO -> [Plugin.Executor.TranslationExecutor]
|
||||
# @RELATION BINDS_TO -> [Plugin.LlmCall.LLMTranslationService]
|
||||
# @RELATION BINDS_TO -> [TranslationModels]
|
||||
# @RELATION BINDS_TO -> [Services.ResourceService]
|
||||
# @RELATION BINDS_TO -> [Models.Translate.TranslateModels]
|
||||
# @RELATION DEPENDS_ON -> [Test.Conftest.IntegrationTestConftest]
|
||||
# Sibling scenario files (split for the 800-line integration cap):
|
||||
# test_translate_pg_e2e_recovery.py — malformed LLM response + incremental rerun
|
||||
# test_translate_pg_e2e_projection.py — ResourceService dashboard/dataset projection
|
||||
#
|
||||
# @TEST_CONTRACT TranslatePgE2E ->
|
||||
# {
|
||||
# scenarios: [
|
||||
# "happy path: source PG rows produce TranslationRecord with target_sql containing translated text, "
|
||||
# "physical rows written to target PG table via Superset SQL Lab",
|
||||
# "429 retry: LLM returns 429 then 200; retry succeeds without duplicate rows",
|
||||
# "incremental rerun: second run only processes new/changed rows, physical table has no duplicates",
|
||||
# "resource projection: Superset dashboard/dataset list/detail via ResourceService"
|
||||
# "429 retry: LLM returns 429 then 200; retry succeeds without duplicate rows"
|
||||
# ]
|
||||
# }
|
||||
# @TEST_EDGE: llm_429_retry -> call_openai_compatible returns 429 then 200; retry succeeds
|
||||
# @TEST_EDGE: malformed_response -> LLM returns malformed JSON; gracefully handled
|
||||
# @TEST_EDGE: incremental_rerun -> second run only processes rows not in first run's output
|
||||
# @TEST_EDGE: target_table_columns_match_sql -> target table has columns matching build_columns output
|
||||
# @TEST_INVARIANT target_no_duplicates -> VERIFIED_BY: [Test.Integration.TestHappyPathTranslatesSourceToTarget]
|
||||
# @TEST_INVARIANT incremental_only_new -> VERIFIED_BY: [Test.Integration.TestIncrementalRerunOnlyNewRows]
|
||||
# @TEST_INVARIANT physical_rows_written -> VERIFIED_BY: [test_happy_path_translates_source_to_target, test_incremental_rerun_only_new_rows]
|
||||
# @TEST_INVARIANT target_no_duplicates -> VERIFIED_BY: [Test.Integration.TestHappyPathTranslatesSourceToTarget, Test.Integration.TestLlmRetryOn429]
|
||||
# @TEST_INVARIANT physical_rows_written -> VERIFIED_BY: [test_happy_path_translates_source_to_target, test_llm_retry_on_429]
|
||||
#
|
||||
# @RATIONALE
|
||||
# Previous integration tests verify TranslationOrchestrator start_run/cancel_run (state machine)
|
||||
@@ -597,441 +594,6 @@ class TestTranslatePgE2E:
|
||||
db_session.commit()
|
||||
# #endregion Test.Integration.TestLlmRetryOn429
|
||||
|
||||
# #region Test.Integration.TestIncrementalRerunOnlyNewRows [C:3] [TYPE Function]
|
||||
# @BRIEF After a successful run, second run only processes rows not in first run's output.
|
||||
# @TEST_EDGE: incremental_rerun -> VERIFIED_BY: test_incremental_rerun_only_new_rows
|
||||
@pytest.mark.integration
|
||||
@pytest.mark.asyncio
|
||||
async def test_incremental_rerun_only_new_rows(
|
||||
self,
|
||||
superset_client,
|
||||
superset_db_url,
|
||||
pg_engine,
|
||||
db_session,
|
||||
):
|
||||
suffix = uuid4().hex[:10]
|
||||
source_table = f"translate_incr_source_{suffix}"
|
||||
target_table = f"translate_incr_target_{suffix}"
|
||||
|
||||
database_id = target_db_id = dataset_id = job_id = run1_id = None
|
||||
|
||||
# ── Step 1: Seed source with 2 rows ──
|
||||
with pg_engine.begin() as conn:
|
||||
conn.execute(text(f"""
|
||||
CREATE TABLE public."{source_table}" (
|
||||
id INTEGER PRIMARY KEY, product_name VARCHAR(128), description TEXT
|
||||
)
|
||||
"""))
|
||||
conn.execute(text(f"""
|
||||
INSERT INTO public."{source_table}" VALUES
|
||||
(1, 'First Product', 'Description for first product'),
|
||||
(2, 'Second Product', 'Description for second product')
|
||||
"""))
|
||||
|
||||
# ── Step 2: Create target table (columns matching build_columns output) ──
|
||||
with pg_engine.begin() as conn:
|
||||
conn.execute(text(f"""
|
||||
CREATE TABLE public."{target_table}" (
|
||||
id INTEGER PRIMARY KEY,
|
||||
product_name_ru TEXT,
|
||||
context TEXT,
|
||||
is_original INTEGER DEFAULT 0
|
||||
)
|
||||
"""))
|
||||
|
||||
try:
|
||||
from urllib.parse import urlparse
|
||||
parsed = urlparse(superset_db_url)
|
||||
database_uri = f"postgresql://test:test@{parsed.hostname}:{parsed.port}/test_translate"
|
||||
|
||||
db_resp = await superset_client.create_database(
|
||||
database_name=f"Translate Incr {suffix}", sqlalchemy_uri=database_uri,
|
||||
)
|
||||
database_id = int(db_resp.get("id") or db_resp.get("result", {}).get("id", 0))
|
||||
|
||||
ds_resp = await superset_client.create_dataset(
|
||||
table_name=source_table, database=database_id, schema_name="public",
|
||||
)
|
||||
dataset_id = int(ds_resp.get("id") or ds_resp.get("result", {}).get("id", 0))
|
||||
|
||||
# Register target database in Superset for SQL Lab write (allow DML for INSERT)
|
||||
tgt_db_resp = await superset_client.create_database(
|
||||
database_name=f"Translate Incr Target {suffix}", sqlalchemy_uri=database_uri,
|
||||
allow_dml=True,
|
||||
)
|
||||
target_db_id = int(tgt_db_resp.get("id") or tgt_db_resp.get("result", {}).get("id", 0))
|
||||
|
||||
# Create provider
|
||||
provider = LLMProvider(
|
||||
id=f"e2e-llm-incr-{suffix}",
|
||||
provider_type="openai",
|
||||
name="E2E Test LLM Provider (Incremental)",
|
||||
base_url="http://fake-llm-localhost:9999",
|
||||
api_key="test-key",
|
||||
default_model="gpt-4o-mini",
|
||||
is_active=True,
|
||||
)
|
||||
db_session.add(provider)
|
||||
db_session.flush()
|
||||
|
||||
# Create job
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
from src.core.config_models import Environment as EnvConfig
|
||||
from src.plugins.translate.service import TranslateJobService
|
||||
from src.schemas.translate import TranslateJobCreate
|
||||
|
||||
config_manager = MagicMock()
|
||||
env_config = EnvConfig(
|
||||
id="test_env", name="Test", url=superset_client.client.base_url,
|
||||
username="admin", password="admin123", verify_ssl=False, timeout=30,
|
||||
)
|
||||
config_manager.get_environments.return_value = [env_config]
|
||||
config_manager.get_environment.return_value = env_config
|
||||
|
||||
job_service = TranslateJobService(db_session, config_manager, "e2e-test-user")
|
||||
job_payload = TranslateJobCreate(
|
||||
name=f"Incremental Test {suffix}",
|
||||
source_dialect="postgresql", target_dialect="postgresql",
|
||||
source_datasource_id=str(dataset_id),
|
||||
target_table=target_table, target_schema="public",
|
||||
translation_column="product_name", target_column="product_name_ru",
|
||||
source_key_cols=["id"], target_key_cols=["id"],
|
||||
target_languages=["ru"], batch_size=50,
|
||||
upsert_strategy="MERGE", provider_id=provider.id,
|
||||
target_database_id=str(target_db_id),
|
||||
)
|
||||
job = await job_service.create_job(job_payload)
|
||||
job_id = job.id
|
||||
job.status = "ACTIVE"
|
||||
job.environment_id = "test_env"
|
||||
db_session.commit()
|
||||
|
||||
# ── Run 1: translate 2 rows ──
|
||||
from src.services.llm_provider import LLMProviderService
|
||||
|
||||
rows_run1 = [
|
||||
{"row_index": "0", "source_text": "First Product", "source_data": {"id": 1, "product_name": "First Product"}},
|
||||
{"row_index": "1", "source_text": "Second Product", "source_data": {"id": 2, "product_name": "Second Product"}},
|
||||
]
|
||||
mock_response_1 = self._make_llm_response(rows_run1)
|
||||
mock_openai_1 = AsyncMock(return_value=(mock_response_1, "stop"))
|
||||
|
||||
from src.plugins.translate.events import TranslationEventLog
|
||||
from src.plugins.translate.orchestrator import TranslationOrchestrator
|
||||
from src.plugins.translate.orchestrator_runner import TranslationStageRunner
|
||||
|
||||
orch = TranslationOrchestrator(db_session, config_manager, "e2e-test-user")
|
||||
run1 = orch.start_run(job_id=job_id)
|
||||
run1_id = run1.id
|
||||
db_session.commit()
|
||||
|
||||
event_log = TranslationEventLog(db_session)
|
||||
runner = TranslationStageRunner(db_session, config_manager, event_log, "e2e-test-user")
|
||||
|
||||
with patch.object(LLMProviderService, "get_decrypted_api_key", return_value="test-key"), patch("src.plugins.translate._llm_call.call_openai_compatible", mock_openai_1):
|
||||
try:
|
||||
completed_run1 = await runner.execute_run(run1)
|
||||
db_session.commit()
|
||||
except Exception:
|
||||
db_session.rollback()
|
||||
raise
|
||||
|
||||
# ── Verify run 1 ──
|
||||
# Run 1 with 2 source records should produce 2 TranslationRecords
|
||||
recs1 = db_session.query(TranslationRecord).filter(
|
||||
TranslationRecord.run_id == run1_id,
|
||||
TranslationRecord.status == "SUCCESS",
|
||||
).all()
|
||||
assert len(recs1) >= 1, f"Run 1 expected >=1 successful records, got {len(recs1)}"
|
||||
|
||||
# Run 1 status should be COMPLETED with successful insert
|
||||
assert completed_run1.status == "COMPLETED" or run1.status == "COMPLETED", \
|
||||
f"Run 1 expected COMPLETED, got {completed_run1.status if hasattr(completed_run1, 'status') else run1.status}"
|
||||
|
||||
# Run 1 should have written 2 physical rows to target table (2 source records, MERGE collapses by key)
|
||||
with pg_engine.begin() as conn:
|
||||
r1_rows = conn.execute(
|
||||
text(f'SELECT COUNT(*) FROM public."{target_table}"')
|
||||
).scalar()
|
||||
assert r1_rows == 2, \
|
||||
f"Run 1 expected 2 physical rows in target table, got {r1_rows}"
|
||||
|
||||
# ── Step 3: Add a new row to source ──
|
||||
with pg_engine.begin() as conn:
|
||||
conn.execute(text(f"""
|
||||
INSERT INTO public."{source_table}" VALUES
|
||||
(3, 'Third Product', 'Description for third product')
|
||||
"""))
|
||||
|
||||
# Refresh the Superset dataset cache so the new row is visible
|
||||
# in the chart data API query. Without refresh, Superset returns
|
||||
# the stale cached result (2 rows instead of 3).
|
||||
await superset_client.refresh_dataset_schema(dataset_id)
|
||||
|
||||
# ── Run 2: should only process the new row ──
|
||||
# The incremental filter preserves row_index from the unfiltered fetch.
|
||||
# With 3 total rows (2 original + 1 new), the new row (id=3) gets row_index="2".
|
||||
rows_run2 = [
|
||||
{"row_index": "2", "source_text": "Third Product", "source_data": {"id": 3, "product_name": "Third Product"}},
|
||||
]
|
||||
mock_response_2 = self._make_llm_response(rows_run2)
|
||||
mock_openai_2 = AsyncMock(return_value=(mock_response_2, "stop"))
|
||||
|
||||
run2 = orch.start_run(job_id=job_id)
|
||||
db_session.commit()
|
||||
with patch.object(LLMProviderService, "get_decrypted_api_key", return_value="test-key"), patch("src.plugins.translate._llm_call.call_openai_compatible", mock_openai_2):
|
||||
try:
|
||||
completed_run2 = await runner.execute_run(run2)
|
||||
db_session.commit()
|
||||
except Exception:
|
||||
db_session.rollback()
|
||||
raise
|
||||
|
||||
# ── Verify run 2 incremental behavior ──
|
||||
|
||||
# Run 2 should have exactly 1 TranslationRecord (only the new row id=3)
|
||||
recs2 = db_session.query(TranslationRecord).filter(
|
||||
TranslationRecord.run_id == run2.id,
|
||||
TranslationRecord.status == "SUCCESS",
|
||||
).all()
|
||||
assert len(recs2) == 1, \
|
||||
f"Run 2 (incremental) expected exactly 1 TranslationRecord (new row only), got {len(recs2)}"
|
||||
|
||||
# Run 2 status should be COMPLETED
|
||||
assert completed_run2.status == "COMPLETED" or run2.status == "COMPLETED", \
|
||||
f"Run 2 expected COMPLETED, got {completed_run2.status if hasattr(completed_run2, 'status') else run2.status}"
|
||||
|
||||
# Run 2 with 1 new source record: build_rows() produces original+translated (2 rows),
|
||||
# but the MERGE path deduplicates by key to prevent PostgreSQL "ON CONFLICT DO UPDATE
|
||||
# command cannot affect row a second time" — so insert_rows_prepared = 1.
|
||||
r2_prepared = getattr(completed_run2, 'insert_rows_prepared', run2.insert_rows_prepared if hasattr(run2, 'insert_rows_prepared') else None)
|
||||
r2_affected = getattr(completed_run2, 'insert_rows_affected', run2.insert_rows_affected if hasattr(run2, 'insert_rows_affected') else None)
|
||||
assert r2_prepared == 1, \
|
||||
f"Run 2 expected insert_rows_prepared=1, got {r2_prepared}"
|
||||
# rows_affected may vary by Superset response (sometimes 0 for DML);
|
||||
# the physical row count assertions below are the real validator.
|
||||
if r2_affected is not None and r2_affected > 0:
|
||||
pass # Superset returned a row count — informative but not required
|
||||
|
||||
# Physical target table should have 3 rows (no duplicates, 2 from run 1 + 1 new from run 2)
|
||||
with pg_engine.begin() as conn:
|
||||
total_rows = conn.execute(
|
||||
text(f'SELECT COUNT(*) FROM public."{target_table}"')
|
||||
).scalar()
|
||||
assert total_rows == 3, \
|
||||
f"Expected 3 total physical rows after run 2, got {total_rows}"
|
||||
|
||||
# Verify the new row (id=3) has the translated text
|
||||
with pg_engine.begin() as conn:
|
||||
row3 = conn.execute(
|
||||
text(f'SELECT product_name_ru FROM public."{target_table}" WHERE id = 3')
|
||||
).fetchone()
|
||||
assert row3 is not None, "Row id=3 should exist in target table"
|
||||
assert row3[0] is not None and "[RU]" in str(row3[0]), \
|
||||
f"Row id=3 should contain '[RU]' translated text, got '{row3[0]}'"
|
||||
|
||||
# Verify unchanged rows (id=1, id=2) still have translations from run 1
|
||||
with pg_engine.begin() as conn:
|
||||
row1 = conn.execute(
|
||||
text(f'SELECT product_name_ru FROM public."{target_table}" WHERE id = 1')
|
||||
).fetchone()
|
||||
row2 = conn.execute(
|
||||
text(f'SELECT product_name_ru FROM public."{target_table}" WHERE id = 2')
|
||||
).fetchone()
|
||||
assert row1 is not None and "[RU]" in str(row1[0]), \
|
||||
f"Row id=1 should still have translated text, got '{row1[0]}'"
|
||||
assert row2 is not None and "[RU]" in str(row2[0]), \
|
||||
f"Row id=2 should still have translated text, got '{row2[0]}'"
|
||||
|
||||
# Verify counter persistence: run2 counters are persisted in the DB
|
||||
db_session.refresh(run2)
|
||||
assert run2.insert_rows_prepared == 1, \
|
||||
f"Persisted insert_rows_prepared for run2 should be 1 (1 deduped row), got {run2.insert_rows_prepared}"
|
||||
assert run2.insert_status == "success", \
|
||||
f"Persisted insert_status for run2 should be 'success', got {run2.insert_status}"
|
||||
|
||||
finally:
|
||||
with suppress(Exception):
|
||||
await superset_client.delete_database(database_id) if database_id else None
|
||||
with suppress(Exception):
|
||||
await superset_client.delete_dataset(dataset_id) if dataset_id else None
|
||||
with suppress(Exception):
|
||||
if target_db_id:
|
||||
await superset_client.delete_database(target_db_id)
|
||||
if job_id:
|
||||
with suppress(Exception):
|
||||
p = db_session.query(LLMProvider).filter(
|
||||
LLMProvider.id == f"e2e-llm-incr-{suffix}"
|
||||
).first()
|
||||
if p:
|
||||
db_session.delete(p)
|
||||
db_session.commit()
|
||||
with pg_engine.begin() as conn:
|
||||
conn.execute(text(f'DROP TABLE IF EXISTS public."{source_table}"'))
|
||||
conn.execute(text(f'DROP TABLE IF EXISTS public."{target_table}"'))
|
||||
# #endregion Test.Integration.TestIncrementalRerunOnlyNewRows
|
||||
# #region Test.Integration.TestResourceProjection [C:3] [TYPE Function]
|
||||
# @BRIEF Seed physical dataset, chart, dashboard; drive ResourceService list/detail entrypoints;
|
||||
# assert response shape and linked counts from real Superset response shapes.
|
||||
@pytest.mark.integration
|
||||
@pytest.mark.asyncio
|
||||
async def test_resource_projection(
|
||||
self,
|
||||
superset_client,
|
||||
superset_env,
|
||||
superset_db_url,
|
||||
pg_engine,
|
||||
):
|
||||
suffix = uuid4().hex[:10]
|
||||
source_table = f"res_proj_source_{suffix}"
|
||||
database_id = dataset_id = chart_id = dashboard_id = None
|
||||
|
||||
# ── Step 1: Seed physical table ──
|
||||
with pg_engine.begin() as conn:
|
||||
conn.execute(text(f"""
|
||||
CREATE TABLE public."{source_table}" (
|
||||
id INTEGER PRIMARY KEY,
|
||||
name VARCHAR(128),
|
||||
value INTEGER
|
||||
)
|
||||
"""))
|
||||
conn.execute(text(f"""
|
||||
INSERT INTO public."{source_table}" VALUES
|
||||
(1, 'Alpha', 100),
|
||||
(2, 'Beta', 200)
|
||||
"""))
|
||||
|
||||
try:
|
||||
# ── Step 2: Register database and dataset in Superset ──
|
||||
from urllib.parse import urlparse
|
||||
parsed = urlparse(superset_db_url)
|
||||
database_uri = f"postgresql://test:test@{parsed.hostname}:{parsed.port}/test_translate"
|
||||
|
||||
db_resp = await superset_client.create_database(
|
||||
database_name=f"ResProj Source {suffix}",
|
||||
sqlalchemy_uri=database_uri,
|
||||
)
|
||||
database_id = int(
|
||||
db_resp.get("id") or db_resp.get("result", {}).get("id", 0)
|
||||
)
|
||||
|
||||
ds_resp = await superset_client.create_dataset(
|
||||
table_name=source_table,
|
||||
database=database_id,
|
||||
schema_name="public",
|
||||
)
|
||||
dataset_id = int(
|
||||
ds_resp.get("id") or ds_resp.get("result", {}).get("id", 0)
|
||||
)
|
||||
|
||||
# ── Step 3: Create dashboard ──
|
||||
dash_resp = await superset_client.create_dashboard(
|
||||
dashboard_title=f"ResProj Dashboard {suffix}",
|
||||
slug=f"resproj-{suffix}",
|
||||
published=True,
|
||||
)
|
||||
dashboard_id = int(
|
||||
dash_resp.get("id") or dash_resp.get("result", {}).get("id", 0)
|
||||
)
|
||||
|
||||
# ── Step 4: Create chart linked to dashboard and dataset ──
|
||||
chart_resp = await superset_client.client.request(
|
||||
method="POST", endpoint="/chart/",
|
||||
data={
|
||||
"dashboards": [dashboard_id],
|
||||
"datasource_id": dataset_id,
|
||||
"datasource_type": "table",
|
||||
"slice_name": f"ResProj Chart {suffix}",
|
||||
"viz_type": "table",
|
||||
"params": json.dumps({
|
||||
"datasource": f"{dataset_id}__table",
|
||||
"viz_type": "table",
|
||||
"all_columns": ["id", "name", "value"],
|
||||
"row_limit": 50,
|
||||
}),
|
||||
},
|
||||
)
|
||||
chart_id = int(
|
||||
chart_resp.get("id") or chart_resp.get("result", {}).get("id", 0)
|
||||
)
|
||||
|
||||
# ── Step 5: Drive ResourceService list entrypoints ──
|
||||
from src.services.resource_service import ResourceService
|
||||
|
||||
resource_service = ResourceService()
|
||||
# Mock GitService to avoid repo dependency in integration test
|
||||
from unittest.mock import MagicMock
|
||||
resource_service.git_service = MagicMock()
|
||||
resource_service.git_service.get_repo = MagicMock(return_value=None)
|
||||
|
||||
# 5a: get_dashboards_with_status — verify our dashboard is listed
|
||||
dashboards = await resource_service.get_dashboards_with_status(
|
||||
env=superset_env, tasks=None, include_git_status=False,
|
||||
)
|
||||
# Find our dashboard by title
|
||||
our_dash = next(
|
||||
(d for d in dashboards if d.get("id") == dashboard_id),
|
||||
None,
|
||||
)
|
||||
assert our_dash is not None, \
|
||||
f"Dashboard id={dashboard_id} not found in dashboards list. " \
|
||||
f"Available: {[d.get('id') for d in dashboards[:10]]}"
|
||||
# Required shape: id, slug, dashboard_title, published, last_task
|
||||
assert "id" in our_dash, "Dashboard response missing 'id'"
|
||||
assert "slug" in our_dash, "Dashboard response missing 'slug'"
|
||||
assert "title" in our_dash, "Dashboard response missing 'title'"
|
||||
assert our_dash.get("title") == f"ResProj Dashboard {suffix}"
|
||||
# When include_git_status=False, git_status should be None
|
||||
assert our_dash.get("git_status") is None, \
|
||||
f"Expected git_status=None, got {our_dash.get('git_status')}"
|
||||
# last_task should be None (no tasks passed)
|
||||
assert our_dash.get("last_task") is None, \
|
||||
f"Expected last_task=None, got {our_dash.get('last_task')}"
|
||||
|
||||
# 5b: get_datasets_with_status — verify our dataset is listed with linked_dashboard_count
|
||||
datasets = await resource_service.get_datasets_with_status(
|
||||
env=superset_env, tasks=None,
|
||||
)
|
||||
our_ds = next(
|
||||
(d for d in datasets if d.get("id") == dataset_id),
|
||||
None,
|
||||
)
|
||||
assert our_ds is not None, \
|
||||
f"Dataset id={dataset_id} not found in datasets list. " \
|
||||
f"Available: {[d.get('id') for d in datasets[:10]]}"
|
||||
# Required shape: id, table_name, schema, linked_dashboard_count, last_task
|
||||
assert "id" in our_ds, "Dataset response missing 'id'"
|
||||
assert "table_name" in our_ds, "Dataset response missing 'table_name'"
|
||||
assert our_ds.get("table_name") == source_table
|
||||
# Our dataset has 1 dashboard and 1 chart linked to it.
|
||||
# linked_dashboard_count should be >= 1 (the chart is linked to the dashboard).
|
||||
linked_count = our_ds.get("linked_dashboard_count", 0)
|
||||
assert linked_count >= 1, \
|
||||
f"Expected linked_dashboard_count >=1 for our dataset, got {linked_count}"
|
||||
# last_task should be None (no tasks passed)
|
||||
assert our_ds.get("last_task") is None, \
|
||||
f"Expected last_task=None, got {our_ds.get('last_task')}"
|
||||
|
||||
finally:
|
||||
# Cleanup Superset resources
|
||||
for cid in ([chart_id] if chart_id else []):
|
||||
with suppress(Exception):
|
||||
await superset_client.delete_chart(cid)
|
||||
for did in ([dashboard_id] if dashboard_id else []):
|
||||
with suppress(Exception):
|
||||
await superset_client.delete_dashboard(did)
|
||||
for dsid in ([dataset_id] if dataset_id else []):
|
||||
with suppress(Exception):
|
||||
await superset_client.delete_dataset(dsid)
|
||||
for dbid in ([database_id] if database_id else []):
|
||||
with suppress(Exception):
|
||||
await superset_client.delete_database(dbid)
|
||||
# Cleanup physical table
|
||||
with pg_engine.begin() as conn:
|
||||
conn.execute(text(f'DROP TABLE IF EXISTS public."{source_table}"'))
|
||||
# #endregion Test.Integration.TestResourceProjection
|
||||
|
||||
# #endregion Test.Integration.TranslatePgE2E.Test
|
||||
|
||||
# #endregion Test.Integration.TranslatePgE2E
|
||||
|
||||
192
backend/tests/integration/test_translate_pg_e2e_projection.py
Normal file
192
backend/tests/integration/test_translate_pg_e2e_projection.py
Normal file
@@ -0,0 +1,192 @@
|
||||
# #region Test.Integration.TranslatePgE2EProjection [C:4] [TYPE Module] [SEMANTICS test,integration,translate,e2e,resource-projection,superset,testcontainers]
|
||||
# @BRIEF Superset resource projection E2E: seed physical dataset/chart/dashboard, drive the
|
||||
# ResourceService list entrypoints against real Superset responses, assert response shape
|
||||
# (id/slug/title, table_name, linked counts) with git status disabled.
|
||||
# @RELATION BINDS_TO -> [Services.ResourceService]
|
||||
# @RELATION DEPENDS_ON -> [Test.Conftest.IntegrationTestConftest]
|
||||
# @RELATION DEPENDS_ON -> [Test.Integration.TranslatePgE2E]
|
||||
# @TEST_CONTRACT ResourceService.get_dashboards_with_status / get_datasets_with_status ->
|
||||
# projected dicts keyed by real Superset ids with title/table_name echo and
|
||||
# linked_dashboard_count >= 1 for a chart-linked dataset; git_status=None and last_task=None
|
||||
# when git status is disabled and no tasks are supplied.
|
||||
# @TEST_EDGE: no_tasks_supplied -> last_task is None on both projections
|
||||
# @TEST_EDGE: git_status_disabled -> git_status is None (GitService is never consulted)
|
||||
# @RATIONALE Split from test_translate_pg_e2e.py (parent exceeded the 800-line integration cap):
|
||||
# resource projection binds to a different production contract (Services.ResourceService) than
|
||||
# the translation pipeline scenarios, so it owns its module here.
|
||||
# @PRE Docker daemon running; shared Superset/PostgreSQL fixtures healthy.
|
||||
# @SIDE_EFFECT Creates/removes Superset database, dataset, chart, dashboard and one physical PG table.
|
||||
from contextlib import suppress
|
||||
import json
|
||||
import pytest
|
||||
from unittest.mock import MagicMock
|
||||
from uuid import uuid4
|
||||
|
||||
from sqlalchemy import text
|
||||
|
||||
|
||||
# #region Test.Integration.TranslatePgE2EProjection.Test [C:3] [TYPE Class]
|
||||
# @BRIEF ResourceService projection tests against the live Superset container.
|
||||
class TestTranslatePgE2EProjection:
|
||||
|
||||
# #region Test.Integration.TestResourceProjection [C:3] [TYPE Function]
|
||||
# @BRIEF Seed physical dataset, chart, dashboard; drive ResourceService list/detail entrypoints;
|
||||
# assert response shape and linked counts from real Superset response shapes.
|
||||
@pytest.mark.integration
|
||||
@pytest.mark.asyncio
|
||||
async def test_resource_projection(
|
||||
self,
|
||||
superset_client,
|
||||
superset_env,
|
||||
superset_db_url,
|
||||
pg_engine,
|
||||
):
|
||||
suffix = uuid4().hex[:10]
|
||||
source_table = f"res_proj_source_{suffix}"
|
||||
database_id = dataset_id = chart_id = dashboard_id = None
|
||||
|
||||
# ── Step 1: Seed physical table ──
|
||||
with pg_engine.begin() as conn:
|
||||
conn.execute(text(f"""
|
||||
CREATE TABLE public."{source_table}" (
|
||||
id INTEGER PRIMARY KEY,
|
||||
name VARCHAR(128),
|
||||
value INTEGER
|
||||
)
|
||||
"""))
|
||||
conn.execute(text(f"""
|
||||
INSERT INTO public."{source_table}" VALUES
|
||||
(1, 'Alpha', 100),
|
||||
(2, 'Beta', 200)
|
||||
"""))
|
||||
|
||||
try:
|
||||
# ── Step 2: Register database and dataset in Superset ──
|
||||
from urllib.parse import urlparse
|
||||
parsed = urlparse(superset_db_url)
|
||||
database_uri = f"postgresql://test:test@{parsed.hostname}:{parsed.port}/test_translate"
|
||||
|
||||
db_resp = await superset_client.create_database(
|
||||
database_name=f"ResProj Source {suffix}",
|
||||
sqlalchemy_uri=database_uri,
|
||||
)
|
||||
database_id = int(
|
||||
db_resp.get("id") or db_resp.get("result", {}).get("id", 0)
|
||||
)
|
||||
|
||||
ds_resp = await superset_client.create_dataset(
|
||||
table_name=source_table,
|
||||
database=database_id,
|
||||
schema_name="public",
|
||||
)
|
||||
dataset_id = int(
|
||||
ds_resp.get("id") or ds_resp.get("result", {}).get("id", 0)
|
||||
)
|
||||
|
||||
# ── Step 3: Create dashboard ──
|
||||
dash_resp = await superset_client.create_dashboard(
|
||||
dashboard_title=f"ResProj Dashboard {suffix}",
|
||||
slug=f"resproj-{suffix}",
|
||||
published=True,
|
||||
)
|
||||
dashboard_id = int(
|
||||
dash_resp.get("id") or dash_resp.get("result", {}).get("id", 0)
|
||||
)
|
||||
|
||||
# ── Step 4: Create chart linked to dashboard and dataset ──
|
||||
chart_resp = await superset_client.client.request(
|
||||
method="POST", endpoint="/chart/",
|
||||
data={
|
||||
"dashboards": [dashboard_id],
|
||||
"datasource_id": dataset_id,
|
||||
"datasource_type": "table",
|
||||
"slice_name": f"ResProj Chart {suffix}",
|
||||
"viz_type": "table",
|
||||
"params": json.dumps({
|
||||
"datasource": f"{dataset_id}__table",
|
||||
"viz_type": "table",
|
||||
"all_columns": ["id", "name", "value"],
|
||||
"row_limit": 50,
|
||||
}),
|
||||
},
|
||||
)
|
||||
chart_id = int(
|
||||
chart_resp.get("id") or chart_resp.get("result", {}).get("id", 0)
|
||||
)
|
||||
|
||||
# ── Step 5: Drive ResourceService list entrypoints ──
|
||||
from src.services.resource_service import ResourceService
|
||||
|
||||
resource_service = ResourceService()
|
||||
# Mock GitService to avoid repo dependency in integration test
|
||||
resource_service.git_service = MagicMock()
|
||||
resource_service.git_service.get_repo = MagicMock(return_value=None)
|
||||
|
||||
# 5a: get_dashboards_with_status — verify our dashboard is listed
|
||||
dashboards = await resource_service.get_dashboards_with_status(
|
||||
env=superset_env, tasks=None, include_git_status=False,
|
||||
)
|
||||
# Find our dashboard by title
|
||||
our_dash = next(
|
||||
(d for d in dashboards if d.get("id") == dashboard_id),
|
||||
None,
|
||||
)
|
||||
assert our_dash is not None, \
|
||||
f"Dashboard id={dashboard_id} not found in dashboards list. " \
|
||||
f"Available: {[d.get('id') for d in dashboards[:10]]}"
|
||||
# Required shape: id, slug, dashboard_title, published, last_task
|
||||
assert "id" in our_dash, "Dashboard response missing 'id'"
|
||||
assert "slug" in our_dash, "Dashboard response missing 'slug'"
|
||||
assert "title" in our_dash, "Dashboard response missing 'title'"
|
||||
assert our_dash.get("title") == f"ResProj Dashboard {suffix}"
|
||||
# When include_git_status=False, git_status should be None
|
||||
assert our_dash.get("git_status") is None, \
|
||||
f"Expected git_status=None, got {our_dash.get('git_status')}"
|
||||
# last_task should be None (no tasks passed)
|
||||
assert our_dash.get("last_task") is None, \
|
||||
f"Expected last_task=None, got {our_dash.get('last_task')}"
|
||||
|
||||
# 5b: get_datasets_with_status — verify our dataset is listed with linked_dashboard_count
|
||||
datasets = await resource_service.get_datasets_with_status(
|
||||
env=superset_env, tasks=None,
|
||||
)
|
||||
our_ds = next(
|
||||
(d for d in datasets if d.get("id") == dataset_id),
|
||||
None,
|
||||
)
|
||||
assert our_ds is not None, \
|
||||
f"Dataset id={dataset_id} not found in datasets list. " \
|
||||
f"Available: {[d.get('id') for d in datasets[:10]]}"
|
||||
# Required shape: id, table_name, schema, linked_dashboard_count, last_task
|
||||
assert "id" in our_ds, "Dataset response missing 'id'"
|
||||
assert "table_name" in our_ds, "Dataset response missing 'table_name'"
|
||||
assert our_ds.get("table_name") == source_table
|
||||
# Our dataset has 1 dashboard and 1 chart linked to it.
|
||||
# linked_dashboard_count should be >= 1 (the chart is linked to the dashboard).
|
||||
linked_count = our_ds.get("linked_dashboard_count", 0)
|
||||
assert linked_count >= 1, \
|
||||
f"Expected linked_dashboard_count >=1 for our dataset, got {linked_count}"
|
||||
# last_task should be None (no tasks passed)
|
||||
assert our_ds.get("last_task") is None, \
|
||||
f"Expected last_task=None, got {our_ds.get('last_task')}"
|
||||
|
||||
finally:
|
||||
# Cleanup Superset resources
|
||||
for cid in ([chart_id] if chart_id else []):
|
||||
with suppress(Exception):
|
||||
await superset_client.delete_chart(cid)
|
||||
for did in ([dashboard_id] if dashboard_id else []):
|
||||
with suppress(Exception):
|
||||
await superset_client.delete_dashboard(did)
|
||||
for dsid in ([dataset_id] if dataset_id else []):
|
||||
with suppress(Exception):
|
||||
await superset_client.delete_dataset(dsid)
|
||||
for dbid in ([database_id] if database_id else []):
|
||||
with suppress(Exception):
|
||||
await superset_client.delete_database(dbid)
|
||||
# Cleanup physical table
|
||||
with pg_engine.begin() as conn:
|
||||
conn.execute(text(f'DROP TABLE IF EXISTS public."{source_table}"'))
|
||||
# #endregion Test.Integration.TestResourceProjection
|
||||
# #endregion Test.Integration.TranslatePgE2EProjection.Test
|
||||
# #endregion Test.Integration.TranslatePgE2EProjection
|
||||
587
backend/tests/integration/test_translate_pg_e2e_recovery.py
Normal file
587
backend/tests/integration/test_translate_pg_e2e_recovery.py
Normal file
@@ -0,0 +1,587 @@
|
||||
# #region Test.Integration.TranslatePgE2ERecovery [C:5] [TYPE Module] [SEMANTICS test,integration,translate,e2e,postgres,llm-stub,recovery,testcontainers]
|
||||
# @BRIEF PostgreSQL translation pipeline E2E — recovery & cache scenarios: a malformed LLM response
|
||||
# fails the run gracefully (no garbage in the target table, one terminal event) and an incremental
|
||||
# rerun after a COMPLETED run processes only new source rows without duplicates.
|
||||
# @RELATION BINDS_TO -> [Plugin.Orchestrator.TranslationOrchestrator]
|
||||
# @RELATION BINDS_TO -> [Plugin.OrchestratorExec.TranslationExecutionEngine]
|
||||
# @RELATION BINDS_TO -> [Plugin.Executor.TranslationExecutor]
|
||||
# @RELATION BINDS_TO -> [Plugin.LlmCall.LLMTranslationService]
|
||||
# @RELATION DEPENDS_ON -> [Test.Conftest.IntegrationTestConftest]
|
||||
# @RELATION DEPENDS_ON -> [Test.Integration.TranslatePgE2E]
|
||||
# @TEST_CONTRACT TranslatePgE2ERecovery ->
|
||||
# {
|
||||
# scenarios: [
|
||||
# "malformed response: LLM returns non-JSON text; records are FAILED, run is FAILED, "
|
||||
# "target table stays empty, exactly one terminal event",
|
||||
# "incremental rerun: second run only processes rows not in first run's output; "
|
||||
# "physical table has no duplicates"
|
||||
# ]
|
||||
# }
|
||||
# @TEST_EDGE: malformed_response -> LLM returns malformed JSON; gracefully handled (moved here from
|
||||
# the pg_e2e header where it was declared without a test; unit-level parse/truncation coverage
|
||||
# lives in tests/plugins/translate/test_llm_call*.py)
|
||||
# @TEST_EDGE: incremental_rerun -> second run only processes rows not in first run's output
|
||||
# @TEST_INVARIANT incremental_only_new -> VERIFIED_BY: [Test.Integration.TestIncrementalRerunOnlyNewRows]
|
||||
# @TEST_INVARIANT physical_rows_written -> VERIFIED_BY: [test_incremental_rerun_only_new_rows]
|
||||
# @TEST_INVARIANT no_garbage_on_parse_failure -> VERIFIED_BY: [test_llm_malformed_response_fails_run_without_target_pollution]
|
||||
# @TEST_INVARIANT terminal_event_uniqueness -> VERIFIED_BY: [test_llm_malformed_response_fails_run_without_target_pollution]
|
||||
# (uniqueness/consistency side on the runner-driven failure path: never duplicated, never
|
||||
# contradicting the FAILED outcome; the exactly-one-terminal lifecycle is pinned at DB level
|
||||
# by Test.TranslateOrchestratorIntegration)
|
||||
# @RATIONALE Split from test_translate_pg_e2e.py (was 1037 lines, above the 800-line integration
|
||||
# cap) by scenario family: the parent file keeps single-run external-boundary scenarios
|
||||
# (happy path, 429 retry); this file owns recovery/cache semantics. Each test drives the full
|
||||
# real pipeline (source PG -> Superset dataset -> chart-data fetch -> LLM stub -> records ->
|
||||
# SQL insert via Superset SQL Lab -> physical target rows).
|
||||
# @REJECTED Keeping malformed_response as a declared-but-untested @TEST_EDGE in the parent header
|
||||
# was rejected — INV_9: a tag without a local verifying test is a defect.
|
||||
# @PRE Docker daemon running; shared Superset/PostgreSQL fixtures healthy.
|
||||
# @SIDE_EFFECT Creates/removes Superset databases, datasets and physical PG tables; writes
|
||||
# TranslationJob/Run/Record/Event rows to the integration DB.
|
||||
from contextlib import suppress
|
||||
import json
|
||||
import pytest
|
||||
from typing import Any
|
||||
from unittest.mock import AsyncMock, patch
|
||||
from uuid import uuid4
|
||||
|
||||
from sqlalchemy import text
|
||||
|
||||
from src.models.llm import LLMProvider
|
||||
from src.models.translate import TranslationRecord
|
||||
|
||||
|
||||
# #region Test.Integration.TranslatePgE2ERecovery.Test [C:4] [TYPE Class]
|
||||
# @BRIEF Recovery & cache E2E tests for the PostgreSQL-to-PostgreSQL translation pipeline.
|
||||
class TestTranslatePgE2ERecovery:
|
||||
"""Recovery scenarios with a fake LLM stub on the external HTTP boundary."""
|
||||
|
||||
# #region Test.Integration.MakeDeterministicLlmResponseRecovery [C:2] [TYPE Function]
|
||||
# @BRIEF Build deterministic LLM JSON response from source rows (same fixture as the parent file).
|
||||
@staticmethod
|
||||
def _make_llm_response(source_rows: list[dict[str, Any]]) -> str:
|
||||
"""Build a deterministic LLM JSON response for the given source rows.
|
||||
|
||||
Each row gets a fake "translation" by prepending "[RU] " to the source text.
|
||||
Format matches parse_llm_response expectations ("rows" list keyed by row_id).
|
||||
"""
|
||||
rows = []
|
||||
for i, row in enumerate(source_rows):
|
||||
source_text = row.get("source_text", "")
|
||||
rows.append({
|
||||
"row_id": row.get("row_index", str(i)),
|
||||
"ru": f"[RU] {source_text}" if source_text else "",
|
||||
"detected_source_language": "en",
|
||||
})
|
||||
return json.dumps({"rows": rows})
|
||||
# #endregion Test.Integration.MakeDeterministicLlmResponseRecovery
|
||||
|
||||
# #region Test.Integration.TestLlmMalformedResponse [C:3] [TYPE Function]
|
||||
# @BRIEF LLM stub returns non-JSON text: the pipeline degrades gracefully — every record is
|
||||
# FAILED, the run is FAILED with exactly one terminal event, and NO row reaches the target.
|
||||
# @TEST_EDGE: malformed_response -> VERIFIED_BY: this test
|
||||
@pytest.mark.integration
|
||||
@pytest.mark.asyncio
|
||||
async def test_llm_malformed_response_fails_run_without_target_pollution(
|
||||
self,
|
||||
superset_client,
|
||||
superset_db_url,
|
||||
pg_engine,
|
||||
db_session,
|
||||
):
|
||||
suffix = uuid4().hex[:10]
|
||||
source_table = f"translate_malf_source_{suffix}"
|
||||
target_table = f"translate_malf_target_{suffix}"
|
||||
|
||||
database_id = target_db_id = dataset_id = job_id = run_id = None
|
||||
|
||||
# ── Step 1: Seed source table ──
|
||||
with pg_engine.begin() as conn:
|
||||
conn.execute(text(f"""
|
||||
CREATE TABLE public."{source_table}" (
|
||||
id INTEGER PRIMARY KEY,
|
||||
product_name VARCHAR(128),
|
||||
description TEXT
|
||||
)
|
||||
"""))
|
||||
conn.execute(text(f"""
|
||||
INSERT INTO public."{source_table}" VALUES
|
||||
(1, 'Wireless Mouse', 'Ergonomic wireless mouse with USB receiver'),
|
||||
(2, 'USB-C Hub', '7-port USB-C hub with HDMI and PD charging')
|
||||
"""))
|
||||
|
||||
# ── Step 2: Target table with build_columns()-compatible shape ──
|
||||
with pg_engine.begin() as conn:
|
||||
conn.execute(text(f"""
|
||||
CREATE TABLE public."{target_table}" (
|
||||
id INTEGER PRIMARY KEY,
|
||||
product_name_ru TEXT,
|
||||
context TEXT,
|
||||
is_original INTEGER DEFAULT 0
|
||||
)
|
||||
"""))
|
||||
|
||||
try:
|
||||
# ── Step 3: Register source db/dataset and DML-enabled target db in Superset ──
|
||||
from urllib.parse import urlparse
|
||||
parsed = urlparse(superset_db_url)
|
||||
database_uri = (
|
||||
f"postgresql://test:test@{parsed.hostname}:{parsed.port}/test_translate"
|
||||
)
|
||||
db_resp = await superset_client.create_database(
|
||||
database_name=f"Translate Malf {suffix}",
|
||||
sqlalchemy_uri=database_uri,
|
||||
)
|
||||
database_id = int(db_resp.get("id") or db_resp.get("result", {}).get("id", 0))
|
||||
|
||||
ds_resp = await superset_client.create_dataset(
|
||||
table_name=source_table,
|
||||
database=database_id,
|
||||
schema_name="public",
|
||||
)
|
||||
dataset_id = int(ds_resp.get("id") or ds_resp.get("result", {}).get("id", 0))
|
||||
|
||||
tgt_db_resp = await superset_client.create_database(
|
||||
database_name=f"Translate Malf Target {suffix}",
|
||||
sqlalchemy_uri=database_uri,
|
||||
allow_dml=True,
|
||||
)
|
||||
target_db_id = int(
|
||||
tgt_db_resp.get("id") or tgt_db_resp.get("result", {}).get("id", 0)
|
||||
)
|
||||
|
||||
# ── Step 4: Provider + job + PENDING run (same contract as the parent happy path) ──
|
||||
provider = LLMProvider(
|
||||
id=f"e2e-llm-malf-{suffix}",
|
||||
provider_type="openai",
|
||||
name="E2E Test LLM Provider (Malformed)",
|
||||
base_url="http://fake-llm-localhost:9999",
|
||||
api_key="test-key",
|
||||
default_model="gpt-4o-mini",
|
||||
is_active=True,
|
||||
)
|
||||
db_session.add(provider)
|
||||
db_session.flush()
|
||||
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
from src.core.config_models import Environment as EnvConfig
|
||||
from src.plugins.translate.service import TranslateJobService
|
||||
from src.schemas.translate import TranslateJobCreate
|
||||
|
||||
config_manager = MagicMock()
|
||||
env_config = EnvConfig(
|
||||
id="test_env", name="Test", url=superset_client.client.base_url,
|
||||
username="admin", password="admin123", verify_ssl=False, timeout=30,
|
||||
)
|
||||
config_manager.get_environments.return_value = [env_config]
|
||||
config_manager.get_environment.return_value = env_config
|
||||
|
||||
job_service = TranslateJobService(db_session, config_manager, "e2e-test-user")
|
||||
job_payload = TranslateJobCreate(
|
||||
name=f"Malformed LLM Test {suffix}",
|
||||
source_dialect="postgresql", target_dialect="postgresql",
|
||||
source_datasource_id=str(dataset_id),
|
||||
target_table=target_table, target_schema="public",
|
||||
translation_column="product_name", target_column="product_name_ru",
|
||||
source_key_cols=["id"], target_key_cols=["id"],
|
||||
target_languages=["ru"], batch_size=50,
|
||||
upsert_strategy="MERGE", provider_id=provider.id,
|
||||
target_database_id=str(target_db_id),
|
||||
)
|
||||
job = await job_service.create_job(job_payload)
|
||||
job_id = job.id
|
||||
job.status = "ACTIVE"
|
||||
job.environment_id = "test_env"
|
||||
db_session.commit()
|
||||
|
||||
from src.plugins.translate.events import TranslationEventLog
|
||||
from src.plugins.translate.orchestrator import TranslationOrchestrator
|
||||
from src.plugins.translate.orchestrator_runner import TranslationStageRunner
|
||||
|
||||
orch = TranslationOrchestrator(db_session, config_manager, "e2e-test-user")
|
||||
run = orch.start_run(job_id=job_id)
|
||||
run_id = run.id
|
||||
db_session.commit()
|
||||
|
||||
# ── Step 5: External LLM boundary returns malformed (non-JSON) text ──
|
||||
# Hardcoded fixture: an unparseable payload. Unit ground truth
|
||||
# (tests/plugins/translate/test_llm_call.py::test_parse_failure) pins
|
||||
# successful=0/failed=N for this class of response; this test proves the
|
||||
# same contract through the FULL pipeline, including the insert gate.
|
||||
from src.services.llm_provider import LLMProviderService
|
||||
|
||||
mock_openai = AsyncMock(return_value=("this is not JSON at all {{{", "stop"))
|
||||
|
||||
event_log = TranslationEventLog(db_session)
|
||||
runner = TranslationStageRunner(
|
||||
db_session, config_manager, event_log, "e2e-test-user"
|
||||
)
|
||||
|
||||
with patch.object(LLMProviderService, "get_decrypted_api_key", return_value="test-key"), patch("src.plugins.translate._llm_call.call_openai_compatible", mock_openai):
|
||||
try:
|
||||
completed_run = await runner.execute_run(run)
|
||||
db_session.commit()
|
||||
except Exception:
|
||||
db_session.rollback()
|
||||
raise
|
||||
|
||||
mock_openai.assert_called()
|
||||
|
||||
# ── Step 6: Graceful-failure postconditions ──
|
||||
from src.models.translate import TranslationEvent
|
||||
|
||||
db_session.refresh(run)
|
||||
run_status = completed_run.status if hasattr(completed_run, "status") else run.status
|
||||
|
||||
# Executor @INVARIANT: pure failure (no successes, some failures) is FAILED.
|
||||
assert run_status == "FAILED", (
|
||||
f"Expected FAILED run on malformed LLM response, got {run_status}: "
|
||||
f"{getattr(completed_run, 'error_message', run.error_message)}"
|
||||
)
|
||||
|
||||
success_records = db_session.query(TranslationRecord).filter(
|
||||
TranslationRecord.run_id == run_id,
|
||||
TranslationRecord.status == "SUCCESS",
|
||||
).count()
|
||||
failed_records = db_session.query(TranslationRecord).filter(
|
||||
TranslationRecord.run_id == run_id,
|
||||
TranslationRecord.status == "FAILED",
|
||||
).count()
|
||||
assert success_records == 0, (
|
||||
f"Malformed response must not produce SUCCESS records, got {success_records}"
|
||||
)
|
||||
assert failed_records >= 1, (
|
||||
f"Expected >=1 FAILED record for the malformed batch, got {failed_records}"
|
||||
)
|
||||
|
||||
# Orchestrator @INVARIANT (uniqueness side, failure path): terminal events are
|
||||
# never duplicated and never contradict the run outcome. NOTE: this test drives
|
||||
# TranslationStageRunner directly; the terminal event itself is emitted by the
|
||||
# orchestrator dispatch wrapper, whose full lifecycle (exactly-one-terminal) is
|
||||
# pinned at DB level by Test.TranslateOrchestratorIntegration.
|
||||
terminal_events = db_session.query(TranslationEvent).filter(
|
||||
TranslationEvent.run_id == run_id,
|
||||
TranslationEvent.event_type.in_(
|
||||
["RUN_COMPLETED", "RUN_FAILED", "RUN_CANCELLED"]
|
||||
),
|
||||
).all()
|
||||
assert len(terminal_events) <= 1, (
|
||||
f"Terminal events must never duplicate, got "
|
||||
f"{[e.event_type for e in terminal_events]}"
|
||||
)
|
||||
if terminal_events:
|
||||
assert terminal_events[0].event_type == "RUN_FAILED", (
|
||||
f"FAILED run must not carry a {terminal_events[0].event_type} terminal event"
|
||||
)
|
||||
|
||||
# Insert gate: no garbage reaches the physical target table.
|
||||
insert_status = getattr(completed_run, "insert_status", None) or run.insert_status
|
||||
assert insert_status != "success", (
|
||||
f"Malformed-response run must not report insert success, got {insert_status}"
|
||||
)
|
||||
with pg_engine.begin() as conn:
|
||||
target_rows = conn.execute(
|
||||
text(f'SELECT COUNT(*) FROM public."{target_table}"')
|
||||
).scalar()
|
||||
assert target_rows == 0, (
|
||||
f"Target table must stay empty after a malformed-response run, got {target_rows} rows"
|
||||
)
|
||||
|
||||
finally:
|
||||
with suppress(Exception):
|
||||
await superset_client.delete_dataset(dataset_id) if dataset_id else None
|
||||
with suppress(Exception):
|
||||
await superset_client.delete_database(database_id) if database_id else None
|
||||
with suppress(Exception):
|
||||
if target_db_id:
|
||||
await superset_client.delete_database(target_db_id)
|
||||
if job_id:
|
||||
with suppress(Exception):
|
||||
p = db_session.query(LLMProvider).filter(
|
||||
LLMProvider.id == f"e2e-llm-malf-{suffix}"
|
||||
).first()
|
||||
if p:
|
||||
db_session.delete(p)
|
||||
db_session.commit()
|
||||
with pg_engine.begin() as conn:
|
||||
conn.execute(text(f'DROP TABLE IF EXISTS public."{source_table}"'))
|
||||
conn.execute(text(f'DROP TABLE IF EXISTS public."{target_table}"'))
|
||||
# #endregion Test.Integration.TestLlmMalformedResponse
|
||||
|
||||
# #region Test.Integration.TestIncrementalRerunOnlyNewRows [C:3] [TYPE Function]
|
||||
# @BRIEF After a successful run, second run only processes rows not in first run's output.
|
||||
# @TEST_EDGE: incremental_rerun -> VERIFIED_BY: test_incremental_rerun_only_new_rows
|
||||
@pytest.mark.integration
|
||||
@pytest.mark.asyncio
|
||||
async def test_incremental_rerun_only_new_rows(
|
||||
self,
|
||||
superset_client,
|
||||
superset_db_url,
|
||||
pg_engine,
|
||||
db_session,
|
||||
):
|
||||
suffix = uuid4().hex[:10]
|
||||
source_table = f"translate_incr_source_{suffix}"
|
||||
target_table = f"translate_incr_target_{suffix}"
|
||||
|
||||
database_id = target_db_id = dataset_id = job_id = run1_id = None
|
||||
|
||||
# ── Step 1: Seed source with 2 rows ──
|
||||
with pg_engine.begin() as conn:
|
||||
conn.execute(text(f"""
|
||||
CREATE TABLE public."{source_table}" (
|
||||
id INTEGER PRIMARY KEY, product_name VARCHAR(128), description TEXT
|
||||
)
|
||||
"""))
|
||||
conn.execute(text(f"""
|
||||
INSERT INTO public."{source_table}" VALUES
|
||||
(1, 'First Product', 'Description for first product'),
|
||||
(2, 'Second Product', 'Description for second product')
|
||||
"""))
|
||||
|
||||
# ── Step 2: Create target table (columns matching build_columns output) ──
|
||||
with pg_engine.begin() as conn:
|
||||
conn.execute(text(f"""
|
||||
CREATE TABLE public."{target_table}" (
|
||||
id INTEGER PRIMARY KEY,
|
||||
product_name_ru TEXT,
|
||||
context TEXT,
|
||||
is_original INTEGER DEFAULT 0
|
||||
)
|
||||
"""))
|
||||
|
||||
try:
|
||||
from urllib.parse import urlparse
|
||||
parsed = urlparse(superset_db_url)
|
||||
database_uri = f"postgresql://test:test@{parsed.hostname}:{parsed.port}/test_translate"
|
||||
|
||||
db_resp = await superset_client.create_database(
|
||||
database_name=f"Translate Incr {suffix}", sqlalchemy_uri=database_uri,
|
||||
)
|
||||
database_id = int(db_resp.get("id") or db_resp.get("result", {}).get("id", 0))
|
||||
|
||||
ds_resp = await superset_client.create_dataset(
|
||||
table_name=source_table, database=database_id, schema_name="public",
|
||||
)
|
||||
dataset_id = int(ds_resp.get("id") or ds_resp.get("result", {}).get("id", 0))
|
||||
|
||||
# Register target database in Superset for SQL Lab write (allow DML for INSERT)
|
||||
tgt_db_resp = await superset_client.create_database(
|
||||
database_name=f"Translate Incr Target {suffix}", sqlalchemy_uri=database_uri,
|
||||
allow_dml=True,
|
||||
)
|
||||
target_db_id = int(tgt_db_resp.get("id") or tgt_db_resp.get("result", {}).get("id", 0))
|
||||
|
||||
# Create provider
|
||||
provider = LLMProvider(
|
||||
id=f"e2e-llm-incr-{suffix}",
|
||||
provider_type="openai",
|
||||
name="E2E Test LLM Provider (Incremental)",
|
||||
base_url="http://fake-llm-localhost:9999",
|
||||
api_key="test-key",
|
||||
default_model="gpt-4o-mini",
|
||||
is_active=True,
|
||||
)
|
||||
db_session.add(provider)
|
||||
db_session.flush()
|
||||
|
||||
# Create job
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
from src.core.config_models import Environment as EnvConfig
|
||||
from src.plugins.translate.service import TranslateJobService
|
||||
from src.schemas.translate import TranslateJobCreate
|
||||
|
||||
config_manager = MagicMock()
|
||||
env_config = EnvConfig(
|
||||
id="test_env", name="Test", url=superset_client.client.base_url,
|
||||
username="admin", password="admin123", verify_ssl=False, timeout=30,
|
||||
)
|
||||
config_manager.get_environments.return_value = [env_config]
|
||||
config_manager.get_environment.return_value = env_config
|
||||
|
||||
job_service = TranslateJobService(db_session, config_manager, "e2e-test-user")
|
||||
job_payload = TranslateJobCreate(
|
||||
name=f"Incremental Test {suffix}",
|
||||
source_dialect="postgresql", target_dialect="postgresql",
|
||||
source_datasource_id=str(dataset_id),
|
||||
target_table=target_table, target_schema="public",
|
||||
translation_column="product_name", target_column="product_name_ru",
|
||||
source_key_cols=["id"], target_key_cols=["id"],
|
||||
target_languages=["ru"], batch_size=50,
|
||||
upsert_strategy="MERGE", provider_id=provider.id,
|
||||
target_database_id=str(target_db_id),
|
||||
)
|
||||
job = await job_service.create_job(job_payload)
|
||||
job_id = job.id
|
||||
job.status = "ACTIVE"
|
||||
job.environment_id = "test_env"
|
||||
db_session.commit()
|
||||
|
||||
# ── Run 1: translate 2 rows ──
|
||||
from src.services.llm_provider import LLMProviderService
|
||||
|
||||
rows_run1 = [
|
||||
{"row_index": "0", "source_text": "First Product", "source_data": {"id": 1, "product_name": "First Product"}},
|
||||
{"row_index": "1", "source_text": "Second Product", "source_data": {"id": 2, "product_name": "Second Product"}},
|
||||
]
|
||||
mock_response_1 = self._make_llm_response(rows_run1)
|
||||
mock_openai_1 = AsyncMock(return_value=(mock_response_1, "stop"))
|
||||
|
||||
from src.plugins.translate.events import TranslationEventLog
|
||||
from src.plugins.translate.orchestrator import TranslationOrchestrator
|
||||
from src.plugins.translate.orchestrator_runner import TranslationStageRunner
|
||||
|
||||
orch = TranslationOrchestrator(db_session, config_manager, "e2e-test-user")
|
||||
run1 = orch.start_run(job_id=job_id)
|
||||
run1_id = run1.id
|
||||
db_session.commit()
|
||||
|
||||
event_log = TranslationEventLog(db_session)
|
||||
runner = TranslationStageRunner(db_session, config_manager, event_log, "e2e-test-user")
|
||||
|
||||
with patch.object(LLMProviderService, "get_decrypted_api_key", return_value="test-key"), patch("src.plugins.translate._llm_call.call_openai_compatible", mock_openai_1):
|
||||
try:
|
||||
completed_run1 = await runner.execute_run(run1)
|
||||
db_session.commit()
|
||||
except Exception:
|
||||
db_session.rollback()
|
||||
raise
|
||||
|
||||
# ── Verify run 1 ──
|
||||
# Run 1 with 2 source records should produce 2 TranslationRecords
|
||||
recs1 = db_session.query(TranslationRecord).filter(
|
||||
TranslationRecord.run_id == run1_id,
|
||||
TranslationRecord.status == "SUCCESS",
|
||||
).all()
|
||||
assert len(recs1) >= 1, f"Run 1 expected >=1 successful records, got {len(recs1)}"
|
||||
|
||||
# Run 1 status should be COMPLETED with successful insert
|
||||
assert completed_run1.status == "COMPLETED" or run1.status == "COMPLETED", \
|
||||
f"Run 1 expected COMPLETED, got {completed_run1.status if hasattr(completed_run1, 'status') else run1.status}"
|
||||
|
||||
# Run 1 should have written 2 physical rows to target table (2 source records, MERGE collapses by key)
|
||||
with pg_engine.begin() as conn:
|
||||
r1_rows = conn.execute(
|
||||
text(f'SELECT COUNT(*) FROM public."{target_table}"')
|
||||
).scalar()
|
||||
assert r1_rows == 2, \
|
||||
f"Run 1 expected 2 physical rows in target table, got {r1_rows}"
|
||||
|
||||
# ── Step 3: Add a new row to source ──
|
||||
with pg_engine.begin() as conn:
|
||||
conn.execute(text(f"""
|
||||
INSERT INTO public."{source_table}" VALUES
|
||||
(3, 'Third Product', 'Description for third product')
|
||||
"""))
|
||||
|
||||
# Refresh the Superset dataset cache so the new row is visible
|
||||
# in the chart data API query. Without refresh, Superset returns
|
||||
# the stale cached result (2 rows instead of 3).
|
||||
await superset_client.refresh_dataset_schema(dataset_id)
|
||||
|
||||
# ── Run 2: should only process the new row ──
|
||||
# The incremental filter preserves row_index from the unfiltered fetch.
|
||||
# With 3 total rows (2 original + 1 new), the new row (id=3) gets row_index="2".
|
||||
rows_run2 = [
|
||||
{"row_index": "2", "source_text": "Third Product", "source_data": {"id": 3, "product_name": "Third Product"}},
|
||||
]
|
||||
mock_response_2 = self._make_llm_response(rows_run2)
|
||||
mock_openai_2 = AsyncMock(return_value=(mock_response_2, "stop"))
|
||||
|
||||
run2 = orch.start_run(job_id=job_id)
|
||||
db_session.commit()
|
||||
with patch.object(LLMProviderService, "get_decrypted_api_key", return_value="test-key"), patch("src.plugins.translate._llm_call.call_openai_compatible", mock_openai_2):
|
||||
try:
|
||||
completed_run2 = await runner.execute_run(run2)
|
||||
db_session.commit()
|
||||
except Exception:
|
||||
db_session.rollback()
|
||||
raise
|
||||
|
||||
# ── Verify run 2 incremental behavior ──
|
||||
|
||||
# Run 2 should have exactly 1 TranslationRecord (only the new row id=3)
|
||||
recs2 = db_session.query(TranslationRecord).filter(
|
||||
TranslationRecord.run_id == run2.id,
|
||||
TranslationRecord.status == "SUCCESS",
|
||||
).all()
|
||||
assert len(recs2) == 1, \
|
||||
f"Run 2 (incremental) expected exactly 1 TranslationRecord (new row only), got {len(recs2)}"
|
||||
|
||||
# Run 2 status should be COMPLETED
|
||||
assert completed_run2.status == "COMPLETED" or run2.status == "COMPLETED", \
|
||||
f"Run 2 expected COMPLETED, got {completed_run2.status if hasattr(completed_run2, 'status') else run2.status}"
|
||||
|
||||
# Run 2 with 1 new source record: build_rows() produces original+translated (2 rows),
|
||||
# but the MERGE path deduplicates by key to prevent PostgreSQL "ON CONFLICT DO UPDATE
|
||||
# command cannot affect row a second time" — so insert_rows_prepared = 1.
|
||||
r2_prepared = getattr(completed_run2, 'insert_rows_prepared', run2.insert_rows_prepared if hasattr(run2, 'insert_rows_prepared') else None)
|
||||
r2_affected = getattr(completed_run2, 'insert_rows_affected', run2.insert_rows_affected if hasattr(run2, 'insert_rows_affected') else None)
|
||||
assert r2_prepared == 1, \
|
||||
f"Run 2 expected insert_rows_prepared=1, got {r2_prepared}"
|
||||
# rows_affected may vary by Superset response (sometimes 0 for DML);
|
||||
# the physical row count assertions below are the real validator.
|
||||
if r2_affected is not None and r2_affected > 0:
|
||||
pass # Superset returned a row count — informative but not required
|
||||
|
||||
# Physical target table should have 3 rows (no duplicates, 2 from run 1 + 1 new from run 2)
|
||||
with pg_engine.begin() as conn:
|
||||
total_rows = conn.execute(
|
||||
text(f'SELECT COUNT(*) FROM public."{target_table}"')
|
||||
).scalar()
|
||||
assert total_rows == 3, \
|
||||
f"Expected 3 total physical rows after run 2, got {total_rows}"
|
||||
|
||||
# Verify the new row (id=3) has the translated text
|
||||
with pg_engine.begin() as conn:
|
||||
row3 = conn.execute(
|
||||
text(f'SELECT product_name_ru FROM public."{target_table}" WHERE id = 3')
|
||||
).fetchone()
|
||||
assert row3 is not None, "Row id=3 should exist in target table"
|
||||
assert row3[0] is not None and "[RU]" in str(row3[0]), \
|
||||
f"Row id=3 should contain '[RU]' translated text, got '{row3[0]}'"
|
||||
|
||||
# Verify unchanged rows (id=1, id=2) still have translations from run 1
|
||||
with pg_engine.begin() as conn:
|
||||
row1 = conn.execute(
|
||||
text(f'SELECT product_name_ru FROM public."{target_table}" WHERE id = 1')
|
||||
).fetchone()
|
||||
row2 = conn.execute(
|
||||
text(f'SELECT product_name_ru FROM public."{target_table}" WHERE id = 2')
|
||||
).fetchone()
|
||||
assert row1 is not None and "[RU]" in str(row1[0]), \
|
||||
f"Row id=1 should still have translated text, got '{row1[0]}'"
|
||||
assert row2 is not None and "[RU]" in str(row2[0]), \
|
||||
f"Row id=2 should still have translated text, got '{row2[0]}'"
|
||||
|
||||
# Verify counter persistence: run2 counters are persisted in the DB
|
||||
db_session.refresh(run2)
|
||||
assert run2.insert_rows_prepared == 1, \
|
||||
f"Persisted insert_rows_prepared for run2 should be 1 (1 deduped row), got {run2.insert_rows_prepared}"
|
||||
assert run2.insert_status == "success", \
|
||||
f"Persisted insert_status for run2 should be 'success', got {run2.insert_status}"
|
||||
|
||||
finally:
|
||||
with suppress(Exception):
|
||||
await superset_client.delete_database(database_id) if database_id else None
|
||||
with suppress(Exception):
|
||||
await superset_client.delete_dataset(dataset_id) if dataset_id else None
|
||||
with suppress(Exception):
|
||||
if target_db_id:
|
||||
await superset_client.delete_database(target_db_id)
|
||||
if job_id:
|
||||
with suppress(Exception):
|
||||
p = db_session.query(LLMProvider).filter(
|
||||
LLMProvider.id == f"e2e-llm-incr-{suffix}"
|
||||
).first()
|
||||
if p:
|
||||
db_session.delete(p)
|
||||
db_session.commit()
|
||||
with pg_engine.begin() as conn:
|
||||
conn.execute(text(f'DROP TABLE IF EXISTS public."{source_table}"'))
|
||||
conn.execute(text(f'DROP TABLE IF EXISTS public."{target_table}"'))
|
||||
# #endregion Test.Integration.TestIncrementalRerunOnlyNewRows
|
||||
# #endregion Test.Integration.TranslatePgE2ERecovery.Test
|
||||
# #endregion Test.Integration.TranslatePgE2ERecovery
|
||||
Reference in New Issue
Block a user