文件
AiXun-DataGov/script/datagov/bi-period-comparison-mysql-smoke.py
T
2026-11-20 15:32:57 +08:00

67 行
7.8 KiB
Python

#!/usr/bin/env python3
"""Actual production comparison Plan/compiler over literal CTEs; no business rows or writes."""
import argparse
import base64
from decimal import Decimal
import hashlib
import importlib.util
import json
import os
from pathlib import Path
ROOT = Path(__file__).resolve().parents[2]
module = importlib.util.spec_from_file_location("bi_fixture_helpers", ROOT / "script/datagov/bi-other-mysql-smoke.py")
helpers = importlib.util.module_from_spec(module); module.loader.exec_module(helpers)
run, literal, CONTAINER, TENANT = helpers.run, helpers.literal, helpers.CONTAINER, helpers.TENANT
SOURCES = ["aixun-api/aixun-api-integration/src/main/java/cn/aixunkeji/datagov/integration/api/tablefile/AnalyticsQuery.java", "aixun-modules/aixun-integration/src/main/java/cn/aixunkeji/datagov/integration/tablefile/AnalyticsSqlCompiler.java", "aixun-modules/aixun-integration/src/main/java/cn/aixunkeji/datagov/integration/tablefile/DateBucketSql.java", "aixun-modules/aixun-integration/src/main/java/cn/aixunkeji/datagov/integration/tablefile/PeriodComparisonSql.java", "aixun-modules/aixun-integration/src/main/java/cn/aixunkeji/datagov/integration/tablefile/CategoryRemainderSql.java"]
CASES = [
("raw_average_and_cross_day_distinct", "MONTH", "2024-02-01", "2024-03-01", None, [("2023-02-01", "A", 10, "a"), ("2023-02-28", "A", 30, "b"), ("2024-02-01", "A", 10, "a"), ("2024-02-28", "A", 20, "a"), ("2024-02-29", "A", 40, "b"), ("2024-02-29", "A", 90, "b")], [("2024-02-01", "A", "40", "2", "20", "20", "1", "2", "0", "0")]),
("null_key_and_missing_sides_zero_baseline", "MONTH", "2024-02-01", "2024-03-01", None, [("2023-02-10", None, 0, "a"), ("2024-02-10", None, 10, "a"), ("2024-02-10", "A", 15, "a"), ("2023-02-10", "B", 5, "b")], [("2024-02-01", None, "10", "1", "0", "10", None, "1", "0", "0"), ("2024-02-01", "A", "15", "1", None, None, None, None, None, None), ("2024-02-01", "B", None, None, "5", None, None, "1", None, None)]),
("negative_baseline_does_not_flip_rate_meaning", "MONTH", "2024-02-01", "2024-03-01", None, [("2023-02-10", "A", -5, "a"), ("2024-02-10", "A", 10, "a")], [("2024-02-01", "A", "10", "1", "-5", "15", None, "1", "0", "0")]),
("fiscal_quarter_aligns_real_bucket_start", "FISCAL_QUARTER", "2023-12-01", "2024-03-01", 12, [("2023-01-31", "A", 10, "a"), ("2024-01-31", "A", 30, "b")], [("2023-12-01", "A", "30", "1", "10", "20", "2", "1", "0", "0")]),
("empty_does_not_create_comparison_zeroes", "MONTH", "2024-02-01", "2024-03-01", None, [], []),
("fractional_decimal_difference_and_ratio", "MONTH", "2024-02-01", "2024-03-01", None, [("2023-02-10", "A", "0.1", "a"), ("2024-02-10", "A", "0.3", "a")], [("2024-02-01", "A", "0.3", "1", "0.1", "0.2", "2", "1", "0", "0")]),
("large_decimal_preserves_above_javascript_integer_limit", "MONTH", "2024-02-01", "2024-03-01", None, [("2023-02-10", "A", "9007199254740993", "a"), ("2024-02-10", "A", "18014398509481986", "a")], [("2024-02-01", "A", "18014398509481986", "1", "9007199254740993", "9007199254740993", "1", "1", "0", "0")]),
]
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", "cases": [c[0] for c in CASES], "writes": "NONE"})); 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 n.startswith("aixun-datagov-local-") for n in identity[4].split()): raise RuntimeError("DataGov ownership mismatch")
compiled = ROOT / ".local-evidence/bi-axes-wave8/date-classes"
hashes = {p: hashlib.sha256((ROOT / p).read_bytes()).hexdigest() for p in SOURCES}
if json.loads((compiled / "comparison-source-sha256.json").read_text()) != hashes: raise RuntimeError("Recompile actual production comparison sources")
classes = [compiled, ROOT / "aixun-api/aixun-api-integration/target/classes", ROOT / "aixun-modules/aixun-integration/target/classes"]
classpath = os.pathsep.join(str(p) for p in classes)
# Package-private production compiler and its fixture must share the same application classloader.
run(["javac", "--release", "21", "-cp", classpath, "-d", str(compiled), str(ROOT / "script/datagov/BiPeriodComparisonMysqlProbe.java")])
java = ["java", "--class-path", classpath, "cn.aixunkeji.datagov.integration.tablefile.BiPeriodComparisonMysqlProbe"]
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'
mysql = ["docker", "exec", "-i", CONTAINER, "sh", "-c", shell]
version = run(mysql, "SELECT VERSION();\n").strip(); outcomes = []
for name, unit, start, end, fiscal, rows, expected in CASES:
generated = run(java + [unit, start, end] + ([str(fiscal)] if fiscal else [])).splitlines()
sql = base64.b64decode(generated[0]).decode(); parameters = [base64.b64decode(p).decode() for p in generated[1].split(",")]; columns = generated[2].split(",")
physical = "`aixun_datagov_system`.`bi_yoy_fixture`"
if sql.count(physical) != 2 or parameters[0] != TENANT or parameters[3] != TENANT: raise AssertionError("Compiler bindings changed")
data = [(day, area, amount, person, TENANT) for day, area, amount, person in rows] + [("2024-02-01", "foreign", 999999, "foreign", "outside")]
fixture = "WITH `bi_yoy_fixture` AS (" + " UNION ALL ".join(f"SELECT CAST({literal(day)} AS DATE) AS day,{literal(area)} AS area,CAST({literal(amount)} AS DECIMAL(38,10)) AS amount,{literal(person)} AS person,{literal(tenant)} AS tenant" for day, area, amount, person, tenant in data) + ") "
projection = ",".join(f"IF(`{c}` IS NULL,'-',TO_BASE64(CAST(`{c}` AS CHAR)))" for c in columns)
statement = fixture + f"SELECT {projection} FROM (" + sql.replace(physical, "`bi_yoy_fixture`") + ") AS observed"
commands = ["SET SESSION MAX_EXECUTION_TIME=10000", f"SET @fixture_sql={literal(statement)}", "PREPARE fixture_statement FROM @fixture_sql"]
commands += [f"SET @fixture_p{i}={literal(p)}" for i, p in enumerate(parameters)]
commands += ["EXECUTE fixture_statement USING " + ",".join(f"@fixture_p{i}" for i in range(len(parameters))), "DEALLOCATE PREPARE fixture_statement"]
returned = run(mysql, ";\n".join(commands) + ";\n")
actual = [tuple(None if p == "-" else base64.b64decode(p).decode() for p in line.split("\t")) for line in returned.splitlines()]
if len(actual) != len(expected): raise AssertionError(name + " row count changed")
for received, wanted in zip(actual, expected):
if len(received) != len(wanted): raise AssertionError(name + " column count changed")
for i, (a, b) in enumerate(zip(received, wanted)):
if (a != b if i < 2 or a is None or b is None else Decimal(a) != Decimal(b)): raise AssertionError(f"{name}: {received!r} != {wanted!r}")
outcomes.append({"case": name, "status": "PASS", "rows": len(actual), "compilerSha256": hashlib.sha256(sql.encode()).hexdigest(), "executedSha256": hashlib.sha256(statement.encode()).hexdigest()})
print(json.dumps({"status": "PASS", "container": CONTAINER, "mysqlVersion": version, "writes": "NONE", "sourceSha256": hashes, "cases": outcomes, "limits": ["Actual Plan/compiler SQL and result metadata; Native policy and Browser NOT_RUN", "MariaDB NOT_RUN"]}, ensure_ascii=False, indent=2))
if __name__ == "__main__": main()