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

84 行
9.3 KiB
Python

#!/usr/bin/env python3
"""Production DATE compiler + Owner against literal CTEs in this project's MySQL only.
No tables, business records, migrations or stored configuration are read or written.
The fixed fixture FROM identity alone is replaced with the literal CTE name.
"""
import argparse
import base64
import hashlib
import importlib.util
import json
import os
from pathlib import Path
from decimal import Decimal
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 = helpers.run, helpers.literal
CONTAINER, TENANT = helpers.CONTAINER, helpers.TENANT
PHYSICAL = "`aixun_datagov_system`.`bi_date_fixture`"
CASES = [
("leap_day_and_null", "DAY", [(None, 7, None), ("2024-02-28", 10, "a"), ("2024-02-29", 20, "a"), ("2024-02-29", 30, "b")], [(None, "7", "0"), ("2024-02-28", "10", "1"), ("2024-02-29", "25", "2")], None),
("monday_week_across_year", "WEEK", [("2024-12-29", 8, "a"), ("2024-12-30", 10, "a"), ("2025-01-05", 30, "b"), ("2025-01-06", 50, "c")], [("2024-12-23", "8", "1"), ("2024-12-30", "20", "2"), ("2025-01-06", "50", "1")], None),
("monthly_raw_average_and_distinct", "MONTH", [("2024-02-01", 10, "a"), ("2024-02-28", 20, "a"), ("2024-02-28", 40, "b"), ("2024-02-29", 90, "b"), ("2024-03-01", 7, "c")], [("2024-02-01", "40", "2"), ("2024-03-01", "7", "1")], None),
("gregorian_quarter_boundary", "QUARTER", [("2024-01-31", 10, "a"), ("2024-03-31", 20, "a"), ("2024-04-01", 100, "b")], [("2024-01-01", "15", "1"), ("2024-04-01", "100", "1")], None),
("gregorian_year_and_leap_day", "YEAR", [("2023-12-31", 10, "a"), ("2024-01-01", 20, "a"), ("2024-02-29", 50, "b")], [("2023-01-01", "10", "1"), ("2024-01-01", "35", "2")], None),
("filter_raw_dates_before_bucketing", "MONTH", [("2024-02-01", 100, "excluded"), ("2024-02-20", 20, "a"), ("2024-02-29", 40, "b")], [("2024-02-01", "30", "2")], "2024-02-15"),
("empty_does_not_invent_zero", "MONTH", [], [], None),
("fiscal_april_year_raw_average_distinct_null", "FISCAL_YEAR", [(None, 7, None), ("2023-04-01", 10, "a"), ("2024-02-28", 20, "a"), ("2024-02-29", 40, "b"), ("2024-03-31", 90, "b"), ("2024-04-01", 12, "c")], [(None, "7", "0"), ("2023-04-01", "40", "2"), ("2024-04-01", "12", "1")], None, 4),
("fiscal_february_quarter_crosses_year", "FISCAL_QUARTER", [("2023-11-01", 10, "a"), ("2024-01-31", 30, "b"), ("2024-02-01", 50, "c")], [("2023-11-01", "20", "2"), ("2024-02-01", "50", "1")], None, 2),
("fiscal_december_quarter_includes_leap_day", "FISCAL_QUARTER", [("2023-12-31", 10, "a"), ("2024-02-29", 30, "a"), ("2024-03-01", 50, "c")], [("2023-12-01", "20", "1"), ("2024-03-01", "50", "1")], None, 12),
("fiscal_january_matches_explicit_calendar_year", "FISCAL_YEAR", [("2023-12-31", 10, "a"), ("2024-02-29", 30, "b")], [("2023-01-01", "10", "1"), ("2024-01-01", "30", "1")], None, 1),
("fiscal_december_year_boundary", "FISCAL_YEAR", [("2024-11-30", 10, "a"), ("2024-12-01", 30, "b")], [("2023-12-01", "10", "1"), ("2024-12-01", "30", "1")], None, 12),
("fiscal_raw_date_filter_precedes_period", "FISCAL_YEAR", [("2023-04-01", 999, "excluded"), ("2024-02-29", 10, "a"), ("2024-03-31", 30, "a")], [("2023-04-01", "20", "1")], "2024-02-01", 4),
]
def main():
parser = argparse.ArgumentParser(); parser.add_argument("--execute", action="store_true"); parser.add_argument("--compiled-dir", type=Path); args = parser.parse_args()
if not args.execute:
print(json.dumps({"status": "NOT_RUN", "container": CONTAINER, "cases": [case[0] for case 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 container ownership mismatch")
classes = [ROOT / "aixun-api/aixun-api-integration/target/classes", ROOT / "aixun-modules/aixun-integration/target/classes", ROOT / "aixun-modules/aixun-dataproduct/target/classes"]
source_files = ["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-dataproduct/src/main/java/cn/aixunkeji/datagov/dataproduct/bi/BiQuerySource.java", "aixun-modules/aixun-dataproduct/src/main/java/cn/aixunkeji/datagov/dataproduct/bi/BiTimeBuckets.java"]
if args.compiled_dir:
approved = ROOT / ".local-evidence/bi-axes-wave8/date-classes"
if args.compiled_dir.resolve() != approved.resolve(): raise RuntimeError("Only the task's isolated check output is supported")
expected = json.loads((approved / "source-sha256.json").read_text())
if expected != {name: hashlib.sha256((ROOT / name).read_bytes()).hexdigest() for name in source_files}: raise RuntimeError("Compiled production sources changed; rebuild the isolated check output")
classes.insert(0, approved)
spring = Path.home() / ".m2/repository/org/springframework/spring-web/7.0.8/spring-web-7.0.8.jar"
if not spring.is_file() or any(not path.is_dir() for path in classes): raise RuntimeError("Coordinated production classes unavailable")
java = ["java", "--class-path", os.pathsep.join(str(path) for path in classes + [spring]), str(ROOT / "script/datagov/BiTimeBucketMysqlProbe.java")]
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 case in CASES:
name, unit, rows, expected, minimum, *fiscal = case
fiscal_args = [minimum or "-", str(fiscal[0])] if fiscal else ([minimum] if minimum else [])
generated = run(java + ["compile", unit] + fiscal_args).splitlines()
sql = base64.b64decode(generated[0]).decode(); parameters = [base64.b64decode(value).decode() for value in generated[1].split(",")]
if sql.count(PHYSICAL) != 1 or parameters != [TENANT] + ([minimum] if minimum else []): raise AssertionError("Compiler binding changed")
data = [(day, amount, person, TENANT) for day, amount, person in rows] + [("2024-01-01", 999999, "foreign", "outside")]
fixture = "WITH `bi_date_fixture` AS (" + " UNION ALL ".join(f"SELECT CAST({literal(day)} AS DATE) AS day,CAST({literal(amount)} AS DECIMAL(20,6)) AS amount,{literal(person)} AS person,{literal(tenant)} AS tenant" for day, amount, person, tenant in data) + ") "
projection = ",".join(f"IF({column} IS NULL,'-',TO_BASE64(CAST({column} AS CHAR)))" for column in ("day", "average", "people"))
statement = fixture + f"SELECT {projection} FROM (" + sql.replace(PHYSICAL, "`bi_date_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(value)}" for i, value 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 value == "-" else base64.b64decode(value).decode() for value in line.split("\t")) for line in returned.splitlines()]
if len(actual) != len(expected): raise AssertionError(name + " unexpected row count")
for received, wanted in zip(actual, expected):
if received[0] != wanted[0] or Decimal(received[1]) != Decimal(wanted[1]) or received[2] != wanted[2]: raise AssertionError(f"{name}: {received!r} != {wanted!r}")
owner = run(java + ["validate", unit] + (["-", str(fiscal[0])] if fiscal else []), returned).strip()
if owner != f"SUCCEEDED\t{len(expected)}": raise AssertionError("Owner did not validate actual dates")
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", "compiler": "ACTUAL_SOURCE_ISOLATED_CHECK" if args.compiled_dir else "COORDINATED_TARGET_CLASSES", "sourceSha256": {name: hashlib.sha256((ROOT / name).read_bytes()).hexdigest() for name in source_files}, "cases": outcomes, "limits": ["Native authorization end-to-end NOT_RUN", "Browser NOT_RUN", "MariaDB NOT_RUN", "No prior-year comparison"]}, ensure_ascii=False, indent=2))
if __name__ == "__main__": main()