文件
AiXun-DataGov/script/datagov/metadata-scan-assist-mysql-smoke.py
2026-11-20 15:32:57 +08:00

64 行
6.2 KiB
Python

#!/usr/bin/env python3
"""Check the production scan-evidence SELECT against temporary fixture tables only."""
import argparse
import hashlib
import importlib.util
import json
import re
from pathlib import Path
ROOT = Path(__file__).resolve().parents[2]
spec = importlib.util.spec_from_file_location("export_fixture", ROOT / "script/datagov/bi-export-jobs-mysql-smoke.py")
fixture = importlib.util.module_from_spec(spec); spec.loader.exec_module(fixture)
run, literal, CONTAINER = fixture.run, fixture.literal, fixture.CONTAINER
SOURCE = ROOT / "aixun-modules/aixun-governance/src/main/java/cn/aixunkeji/datagov/governance/metadataingestion/MetadataScanAssistEvidence.java"
def main():
parser = argparse.ArgumentParser(); parser.add_argument("--execute", action="store_true"); args = parser.parse_args()
if not args.execute:
print(json.dumps({"status":"NOT_RUN", "writes":"SESSION_TEMPORARY_TABLES_ONLY"})); return
identity = run(["docker","inspect","--format",'{{.Name}}|{{index .Config.Labels "com.docker.compose.project"}}|{{index .Config.Labels "com.docker.compose.service"}}|{{.State.Running}}|{{range $n,$v := .NetworkSettings.Networks}}{{$n}} {{end}}',CONTAINER]).strip().split("|")
if identity[:4] != ["/"+CONTAINER,"aixun-datagov-local","mysql","true"] or not identity[4].split() or any(not name.startswith("aixun-datagov-local-") for name in identity[4].split()): raise RuntimeError("DataGov ownership mismatch")
statements = []
for relative, names in [("db/migration/governance/V20260828.042__create_metadata_ingestion.sql",["md_ingestion_run"]),("db/migration/governance/V20261011.212__create_native_metadata_jobs.sql",["md_native_job","md_native_scan_stage"])]:
text=(ROOT/relative).read_text()
for name in names:
found=re.findall(r"CREATE TABLE (?:IF NOT EXISTS )?"+name+r" \(.*?\) ENGINE=.*?;",text,re.S)
if len(found)!=1: raise AssertionError("Fixture schema missing")
statements.append(found[0].replace("CREATE TABLE","CREATE TEMPORARY TABLE",1))
query=re.findall(r'jdbc.query\("""(.*?)"""',SOURCE.read_text(),re.S)
if len(query)!=1 or query[0].count("?")!=4: raise AssertionError("Production evidence SELECT changed")
query=query[0].strip()
snapshot={"sourceDataSourceId":2,"sourceDataSourceVersion":3,"incremental":True,"databaseIncludes":'["frozen-a"]',"databaseExcludes":'[]',"schemaIncludes":'[]',"schemaExcludes":'[]',"tableIncludes":'["first","second"]',"tableExcludes":'[]',"hostPort":"synthetic-private-host"}
encoded=json.dumps(snapshot,separators=(",",":")); digest=hashlib.sha256(encoded.encode()).hexdigest(); job="11111111-1111-4111-8111-111111111111"
statements += ["START TRANSACTION", "INSERT INTO md_ingestion_run(run_id,connector_id,policy_id,run_status,snapshot_sha256,snapshot_json,external_pipeline_id,external_pipeline_fqn,external_run_id,org_id,create_by) VALUES(7,1,5,'UNKNOWN',"+literal(digest)+","+literal(encoded)+","+literal(job)+",'service.pipeline',"+literal(job)+",10,7)"]
def observe(name, predicate, parameters=None):
statement="SELECT "+literal(name)+",IF((SELECT "+predicate+" FROM ("+query+") evidence),'PASS','FAIL')"
statements.extend(["SET @fixture_sql="+literal(statement),"PREPARE fixture_statement FROM @fixture_sql"])
statements.extend("SET @fixture_p%d=%s"%(index,literal(value)) for index,value in enumerate(parameters or [7,1,10,digest]))
statements.extend(["EXECUTE fixture_statement USING @fixture_p0,@fixture_p1,@fixture_p2,@fixture_p3","DEALLOCATE PREPARE fixture_statement"])
observe("unbound_run_retains_frozen_scope_without_native_counts","COUNT(*)=1 AND MIN(source_version)=3 AND MIN(table_includes)=2 AND COUNT(native_state)=0 AND COUNT(staged_tables)=0")
statements.append("INSERT INTO md_native_job(job_id,request_id,platform_run_id,actor_id,org_id,source_id,source_version,pipeline_fqn,state) VALUES("+literal(job)+",'synthetic',7,7,10,2,3,'service.pipeline','UNKNOWN')")
statements.append("INSERT INTO md_native_scan_stage(job_id,object_key,table_name,structure_json,structure_sha) VALUES("+literal(job)+",REPEAT('a',64),'synthetic-table',JSON_OBJECT(),REPEAT('b',64))")
observe("exact_binding_exposes_only_recorded_stage_count","COUNT(*)=1 AND MIN(native_state)='UNKNOWN' AND MIN(staged_tables)=1 AND COUNT(asset_count)=0")
for field, changed, restored in [("org_id","11","10"),("source_id","9","2"),("source_version","4","3"),("pipeline_fqn","'other.pipeline'","'service.pipeline'")]:
statements.append("UPDATE md_native_job SET "+field+"="+changed)
observe("mismatched_"+field+"_cannot_supply_native_evidence","COUNT(*)=1 AND COUNT(native_state)=0 AND COUNT(staged_tables)=0")
statements.append("UPDATE md_native_job SET "+field+"="+restored)
observe("foreign_organization_cannot_read_run","COUNT(*)=0",[7,1,99,digest])
statements.append("UPDATE md_native_job SET del_flag='1'")
observe("deleted_native_job_cannot_supply_current_evidence","COUNT(*)=1 AND COUNT(native_state)=0 AND COUNT(staged_tables)=0")
statements.append("UPDATE md_native_job SET del_flag='0'")
statements.append("UPDATE md_ingestion_run SET snapshot_json=JSON_SET(snapshot_json,'$.sourceDataSourceVersion',999)")
observe("mutated_frozen_snapshot_is_rejected","COUNT(*)=0")
statements.append("ROLLBACK")
shell='test "$MYSQL_DATABASE" = aixun_datagov_system && test -n "$MYSQL_ROOT_PASSWORD" || exit 21; MYSQL_PWD="$MYSQL_ROOT_PASSWORD"; export MYSQL_PWD; exec mysql --user=root --database="$MYSQL_DATABASE" --batch --raw --skip-column-names --default-character-set=utf8mb4 --connect-timeout=5'
output=run(["docker","exec","-i",CONTAINER,"sh","-c",shell],";\n".join(statements)+";\n")
outcomes=[dict(zip(["case","status"],line.split("\t"))) for line in output.splitlines()]
if len(outcomes)!=9 or any(item.get("status")!="PASS" for item in outcomes): raise AssertionError(json.dumps(outcomes))
print(json.dumps({"status":"PASS","sourceSha256":hashlib.sha256(SOURCE.read_bytes()).hexdigest(),"writes":"SESSION_TEMPORARY_TABLES_ONLY_ROLLED_BACK","cases":outcomes,"limits":["Browser and model NOT_RUN", "Current-user permission tests are separate"]},ensure_ascii=False,indent=2))
if __name__=="__main__": main()