#!/usr/bin/env python3 """Production relative DATE arithmetic + compiler against literal CTEs. No business data/DDL/writes.""" import argparse import base64 from datetime import date, timedelta from decimal import Decimal import hashlib import importlib.util import json import os from pathlib import Path ROOT = Path(__file__).resolve().parents[2] spec = importlib.util.spec_from_file_location("bi_fixture_helpers", ROOT / "script/datagov/bi-other-mysql-smoke.py") helpers = importlib.util.module_from_spec(spec); spec.loader.exec_module(helpers) run, literal, CONTAINER, TENANT = helpers.run, helpers.literal, helpers.CONTAINER, helpers.TENANT API = "aixun-api/aixun-api-integration/src/main/java/cn/aixunkeji/datagov/integration/api/tablefile/" SQL = "aixun-modules/aixun-integration/src/main/java/cn/aixunkeji/datagov/integration/tablefile/" SOURCES = [API + n + ".java" for n in ["AnalyticsQuery", "AnalyticsRelativeWindow"]] + [SQL + n + ".java" for n in ["AnalyticsSqlCompiler", "RelativeWindowSql", "DateBucketSql", "PeriodComparisonSql", "CategoryRemainderSql"]] CASES = [ ("east_leap_day", "DAY", 1, "Asia/Shanghai", "2024-03-01T00:30:00Z", "2024-03-01", "2024-02-29", "2024-03-01", False), ("same_instant_west", "DAY", 1, "America/Los_Angeles", "2024-03-01T00:30:00Z", "2024-02-29", "2024-02-28", "2024-02-29", False), ("dst_date_not_duration", "DAY", 2, "America/New_York", "2024-03-11T04:30:00Z", "2024-03-11", "2024-03-09", "2024-03-11", False), ("monday_week_cross_year", "WEEK", 1, "UTC", "2025-01-01T12:00:00Z", "2025-01-01", "2024-12-23", "2024-12-30", False), ("complete_months", "MONTH", 2, "UTC", "2025-01-31T12:00:00Z", "2025-01-31", "2024-11-01", "2025-01-01", False), ("gregorian_quarter", "QUARTER", 2, "UTC", "2025-02-12T12:00:00Z", "2025-02-12", "2024-07-01", "2025-01-01", False), ("complete_year", "YEAR", 1, "UTC", "2025-12-31T12:00:00Z", "2025-12-31", "2024-01-01", "2025-01-01", False), ("source_date_policy_intersection", "MONTH", 1, "UTC", "2024-03-15T12:00:00Z", "2024-03-15", "2024-02-01", "2024-03-01", True), ] 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 / "relative-source-sha256.json").read_text()) != hashes: raise RuntimeError("Recompile production relative sources") classpath = os.pathsep.join(str(p) for p in [compiled, ROOT / "aixun-api/aixun-api-integration/target/classes", ROOT / "aixun-modules/aixun-integration/target/classes"]) run(["javac", "--release", "21", "-cp", classpath, "-d", str(compiled), str(ROOT / "script/datagov/BiRelativeWindowMysqlProbe.java")]) java = ["java", "--class-path", classpath, "cn.aixunkeji.datagov.integration.tablefile.BiRelativeWindowMysqlProbe"] 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, count, zone, instant, reference, start, end, policy in CASES: last = (date.fromisoformat(end) - timedelta(days=1)).isoformat() generated = run(java + [unit, str(count), zone, instant] + ([last] if policy else [])).splitlines() sql = base64.b64decode(generated[0]).decode(); parameters = [base64.b64decode(p).decode() for p in generated[1].split(",")] if generated[3] != ",".join([reference, start, end]) or generated[2] != "average,people": raise AssertionError(name + " frozen metadata changed") physical = "`aixun_datagov_system`.`bi_relative_fixture`" if sql.count(physical) != 1 or parameters != [TENANT] + ([last] if policy else []) + [start, end]: raise AssertionError("Production bindings changed") rows = [(start, 10, "a", TENANT), (last, 20, "a", TENANT), (last, 30, "b", TENANT), ((date.fromisoformat(start)-timedelta(days=1)).isoformat(), 999, "before", TENANT), (end, 999, "after", TENANT), (None, 999, "null", TENANT), (last, 999, "foreign", "outside")] fixture = "WITH `bi_relative_fixture` AS (" + " UNION ALL ".join(f"SELECT CAST({literal(day)} AS DATE) AS day,CAST({literal(amount)} AS DECIMAL(38,10)) AS amount,{literal(person)} AS person,{literal(tenant)} AS tenant" for day, amount, person, tenant in rows) + ") " statement = fixture + sql.replace(physical, "`bi_relative_fixture`") commands = ["SET SESSION MAX_EXECUTION_TIME=10000", f"SET @fixture_sql={literal(statement)}", "PREPARE fixture_statement FROM @fixture_sql"] + [f"SET @fixture_p{i}={literal(p)}" for i, p in enumerate(parameters)] + ["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").strip().split("\t") if len(returned) != 2 or Decimal(returned[0]) != Decimal(25 if policy else 20) or returned[1] != "2": raise AssertionError(name + " aggregate mismatch") outcomes.append({"case": name, "status": "PASS", "window": generated[3], "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": ["Native policies, Browser, MariaDB NOT_RUN", "Only literal synthetic CTEs, no business reads"]}, ensure_ascii=False, indent=2)) if __name__ == "__main__": main()