文件
2026-11-20 15:32:57 +08:00

100 行
7.5 KiB
Python

#!/usr/bin/env python3
"""Production compiler/decoder against pure synthetic CTEs in DataGov's own MySQL.
No real table is read, created or modified. The sole target substitution binds the
compiler's fixed physical fixture identifier to a literal CTE. All aggregation,
top ordering, anti-match and four prepared parameters remain compiler-produced.
The local container's existing credential is used only inside that container.
"""
import argparse
import base64
import hashlib
import json
import os
from pathlib import Path
import subprocess
from decimal import Decimal
ROOT = Path(__file__).resolve().parents[2]
CONTAINER = "aixun-datagov-mysql"
PHYSICAL = "`aixun_datagov_system`.`bi_other_fixture`"
TENANT = "fixture' OR 1=1 --"
CASES = [
("unequal_group_average", "AVG", 1, [("a", 100), ("a", 100), ("b", 10), ("c", 0), ("c", 0), ("c", 0)], [("a", "100", "0"), (None, "2.5", "1"), (None, "0", "2")], False),
("cross_category_distinct", "COUNT_DISTINCT", 1, [("a", 1), ("a", 2), ("a", 3), ("b", 1), ("b", 2), ("c", 2), ("c", 4)], [("a", "3", "0"), (None, "3", "1"), (None, "2", "2")], False),
("null_and_actual_other", "SUM", 2, [(None, 100), ("其他", 90), ("b", 20)], [(None, "100", "0"), ("其他", "90", "0"), (None, "20", "1"), (None, "20", "2")], False),
("stable_ties_null_last", "SUM", 2, [("b", 10), (None, 10), ("a", 10)], [("a", "10", "0"), ("b", "10", "0"), (None, "10", "1"), (None, "10", "2")], False),
("hidden_negative_positive_remainder", "SUM", 1, [("a", 100), ("b", -10), ("c", 20)], [("a", "100", "0"), (None, "10", "1"), (None, "-10", "2")], True),
("no_remainder", "AVG", 2, [("a", 4)], [("a", "4", "0"), (None, "4", "2")], False),
("all_null_remaining_values", "AVG", 1, [("a", 10), ("b", None), ("c", None)], [("a", "10", "0"), (None, None, "1"), (None, "10", "2")], False),
("empty_filtered_result", "AVG", 1, [], [(None, None, "2")], False),
]
def run(command, data=None, timeout=45):
result = subprocess.run(command, input=data, text=True, capture_output=True, timeout=timeout, cwd=ROOT)
if result.returncode:
# The invocation has no literal credentials; preserve a bounded error for diagnosis.
raise RuntimeError(result.stderr[-1800:] or "Process failed")
return result.stdout
def b64(value):
return base64.b64encode(value.encode()).decode()
def literal(value):
return "NULL" if value is None else f"CONVERT(0x{str(value).encode().hex()} USING utf8mb4)"
def fixture(rows):
# A foreign synthetic tenant must be excluded on every source occurrence.
values = [(category, amount, TENANT) for category, amount in rows] + [("foreign", 99999, "outside")]
return "WITH `bi_other_fixture` AS (" + " UNION ALL ".join(
f"SELECT CAST({literal(c)} AS CHAR(128)) AS category,CAST({literal(v)} AS DECIMAL(20,6)) AS amount,{literal(t)} AS tenant"
for c, v, t in values) + ") "
def compare(actual, expected):
if len(actual) != len(expected):
raise AssertionError(f"row count {len(actual)} != {len(expected)}")
for received, wanted in zip(actual, expected):
if received[0] != wanted[0] or received[2] != wanted[2]:
raise AssertionError(f"category/level mismatch {received!r} != {wanted!r}")
if (received[1] is None) != (wanted[1] is None) or wanted[1] is not None and Decimal(received[1]) != Decimal(wanted[1]):
raise AssertionError(f"aggregate mismatch {received!r} != {wanted!r}")
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", "container": CONTAINER, "cases": [c[0] for c in CASES], "writes": "NONE; literal CTE only"}, ensure_ascii=False)); 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")
dependencies = [ROOT / "aixun-api/aixun-api-integration/target/classes", ROOT / "aixun-modules/aixun-integration/target/classes", ROOT / "aixun-modules/aixun-dataproduct/target/classes"]
for path in dependencies:
if not path.is_dir(): raise RuntimeError("Production classes are unavailable; run the coordinated affected tests first")
spring = Path.home() / ".m2/repository/org/springframework/spring-web/7.0.8/spring-web-7.0.8.jar"
if not spring.is_file(): raise RuntimeError("Expected managed Spring Web dependency unavailable")
java = ["java", "--class-path", os.pathsep.join(str(p) for p in dependencies + [spring]), str(ROOT / "script/datagov/BiOtherMysqlProbe.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()
results = []
for name, aggregate, top, rows, expected, rejected in CASES:
generated = run(java + ["compile", aggregate, str(top)]).splitlines()
sql = base64.b64decode(generated[0]).decode(); parameters = [base64.b64decode(p).decode() for p in generated[1].split(",")]
if sql.count(PHYSICAL) != 4 or parameters != [TENANT] * 4: raise AssertionError("Production plan binding changed")
sql = sql.rstrip(";")
projection = ",".join(f"IF({column} IS NULL,'-',TO_BASE64(CAST({column} AS CHAR)))" for column in ("category", "value", "__aixun_category_level"))
statement = fixture(rows) + f"SELECT {projection} FROM (" + sql.replace(PHYSICAL, "`bi_other_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"]
received = 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 received.splitlines()]
compare(actual, expected)
owner = run(java + ["decode", aggregate, str(top)], received).strip()
if rejected and owner != "REJECTED\t149109" or not rejected and not owner.startswith("SUCCEEDED\t"):
raise AssertionError(f"Owner outcome mismatch: {owner}")
results.append({"case": name, "status": "PASS", "rawRowCount": len(actual), "owner": owner.split("\t"), "compilerSha256": hashlib.sha256(sql.encode()).hexdigest(), "executedSha256": hashlib.sha256(statement.encode()).hexdigest()})
print(json.dumps({"status": "PASS", "container": CONTAINER, "mysqlVersion": version, "writes": "NONE", "binding": "fixed physical fixture identifier to literal CTE only", "cases": results, "limits": ["Not a Browser test", "Does not prove Native source registration or live reader RBAC", "Other database engines NOT_RUN"]}, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()