Files
marqdo-lint/scripts/validate-control-flow.py
T

220 lines
10 KiB
Python
Executable File

#!/usr/bin/env python3
"""Run the RC.1/RC.2 release gate using unpacked Linux release bundles."""
import argparse
import hashlib
import json
import os
from pathlib import Path
import re
import shutil
import subprocess
import tempfile
ROOT = Path(__file__).resolve().parents[1]
RELEASES = {
"3.0.0-rc.1": {
"source_commit": "f7a5a7b0163bf5229ed09adfffd892f9899e6667",
"archive_sha256": "9f49036ada141871492ef721f08569c74fd2854b5e5d1bfc065ba4d812dcabc7",
"binary_sha256": "2fc5f74d8dd64a4a1b4617e630cb2af9fae5ba0ab769467c32ecb5a988894b6d",
"negotiated_analysis": 2,
},
"3.0.0-rc.2": {
"source_commit": "9149ee40a48fcda692c5c112f66c465487d13dfb",
"archive_sha256": "e32e6426caf023fc813ebdbf5a171ec164ee2ffb843ae5594b8e7b9780f496ea",
"binary_sha256": "5caa90b8f6a282aef5bb301443ede6cd3bdcf5f64c88969e6d71cb324b03dc5b",
"negotiated_analysis": 3,
},
}
class ValidationError(Exception):
pass
def require(condition, message):
if not condition:
raise ValidationError(message)
def sha256(path):
with path.open("rb") as stream:
return hashlib.file_digest(stream, "sha256").hexdigest()
def run(args, *, cwd=ROOT, env=None, expected=0):
result = subprocess.run(list(map(str, args)), cwd=cwd, env=env, capture_output=True, text=True)
if expected is not None and result.returncode != expected:
raise ValidationError(
f"{args}: expected exit {expected}, got {result.returncode}\n"
f"{result.stdout}{result.stderr}"
)
return result
def validate_core(binary, version):
require(binary.is_file() and os.access(binary, os.X_OK), f"missing frozen core: {binary}")
digest = sha256(binary)
require(digest == RELEASES[version]["binary_sha256"], f"unexpected {version} binary SHA-256: {digest}")
require(run([binary, "--version"]).stdout.strip() == f"marqdo {version}", f"wrong version: {binary}")
return digest
def test_suite(binary):
env = dict(os.environ, MARQDO_BIN=str(binary))
cached_cargo = ROOT / ".cache/cargo-home"
if cached_cargo.is_dir():
env.setdefault("CARGO_HOME", str(cached_cargo))
output = run(["cargo", "test", "--locked"], env=env).stdout
counts = re.findall(r"test result: ok\. (\d+) passed; 0 failed", output)
require(counts and sum(map(int, counts)) > 0, "cargo test reported no passing tests")
return sum(map(int, counts))
def trace_dispatch(strace, binary, work, env, name, args, major, expected):
trace = work / f"{name}.trace"
result = run(
[strace, "-f", "-qq", "-v", "-s", "4096", "-e", "trace=execve", "-o", trace, binary, "lint", *args],
cwd=work, env=env, expected=expected,
)
core_calls = []
tool_calls = []
for line in trace.read_text().splitlines():
match = re.search(r'execve\(("(?:[^"\\]|\\.)*"), (\[(?:"(?:[^"\\]|\\.)*"(?:, )?)*\]),', line)
if not match:
continue
program = Path(json.loads(match[1]))
argv = json.loads(match[2])[1:]
if program == binary:
core_calls.append(argv)
elif program.name == "marqdo-lint":
tool_calls.append(line)
else:
raise ValidationError(f"{name}: unexpected executed program {program}")
require(len(tool_calls) == 1, f"{name}: expected one packaged lint process")
require(f'"MARQDO_PROTOCOL_ANALYSIS={major}"' in tool_calls[0], f"{name}: incorrect negotiated Analysis major")
require(core_calls and core_calls[0][0] == "lint", f"{name}: missing core dispatch process")
child_commands = set()
for argv in core_calls[1:]:
if argv == ["--version"]:
child_commands.add("--version")
elif len(argv) == 4 and argv[0] == "inspect" and argv[2:] == ["--ast", "--json"]:
child_commands.add("inspect FILE --ast --json")
elif len(argv) == 5 and argv[0] == "check" and argv[2:4] == ["--json", "--emit"]:
child_commands.add("check FILE --json --emit PATH")
else:
raise ValidationError(f"{name}: unexpected core child command {argv}")
require(len(child_commands) == 3, f"{name}: missing static child command: {child_commands}")
return result.stdout, sorted(child_commands)
def validate_bundle(strace, binary, version, bundle, directory):
work = directory / "independent-cwd"
work.mkdir(parents=True)
home = directory / "home"
home.mkdir()
env = {
"PATH": "/usr/bin:/bin",
"LANG": "C.UTF-8",
"HOME": str(home),
"MARQDO_TOOL_HOME": str(directory / "registry"),
}
manifest = bundle / "tool.json"
run([binary, "tool", "install", manifest], cwd=work, env=env)
tools = run([binary, "tool", "list", "--json"], cwd=work, env=env).stdout
require('"lint"' in tools, f"{version}: lint missing after tool install")
major = RELEASES[version]["negotiated_analysis"]
cases = [
("legacy-branches", ROOT / "tests/fixtures/golden/branches.mq.md", 2, 0, "json", "never", None),
("style-warning", ROOT / "examples/bad/branch-single-item.mq.md", 2, 1, "human", "warning", "MQD-BRANCH-001"),
("incomplete", ROOT / "tests/fixtures/golden/invalid-control.mq.md", None, 2, "json", "never", "sem.unclosed_control"),
]
if major == 3:
cases.extend([
("release-hello", binary.parent / "examples/hello.mq.md", 2, 0, "json", "never", None),
("multi-arm", ROOT / "tests/fixtures/rc2/multi-arm.mq.md", 2, 0, "json", "never", None),
("loop-jumps", ROOT / "tests/fixtures/rc2/loop-jumps.mq.md", 3, 0, "json", "never", None),
("release-control-flow", binary.parent / "examples/control-flow.mq.md", 3, 0, "json", "never", None),
("author-example", ROOT / "examples/good/control-flow-rc2.mq.md", 3, 0, "json", "warning", None),
])
evidence = {}
for name, original, expected_major, status, output_format, fail_on, diagnostic in cases:
source = work / f"{name}.mq.md"
shutil.copyfile(original, source)
if expected_major is not None:
artifact = work / f"{name}.analysis.json"
run([binary, "check", source.name, "--json", "--emit", artifact], cwd=work, env=env)
actual = json.loads(artifact.read_text())["schema_version"]
require(actual == expected_major, f"{name}: incorrect artifact major {actual}")
text, commands = trace_dispatch(
strace, binary, work, env, name,
[source.name, "--format", output_format, "--fail-on", fail_on], major, status,
)
digest = sha256(source)
analysis_status = "analysis_incomplete" if status == 2 else "complete"
if output_format == "json":
report = json.loads(text)
require(report["schema"] == "marqdo.lint" and report["schema_version"] == 1, f"{name}: unexpected report protocol")
require(report["analysis_status"] == analysis_status, f"{name}: unexpected report state")
require(report["source"]["digest"] == f"sha256:{digest}", f"{name}: source digest mismatch")
if diagnostic:
require(diagnostic in text, f"{name}: missing diagnostic {diagnostic}")
evidence[name] = {
"input_sha256": digest,
"analysis_major": expected_major,
"analysis_status": analysis_status,
"exit": status,
"format": output_format,
**({"diagnostic": diagnostic} if diagnostic else {}),
}
run([binary, "tool", "remove", "lint"], cwd=work, env=env)
tools = run([binary, "tool", "list", "--json"], cwd=work, env=env).stdout
require('"lint"' not in tools, f"{version}: lint remains after uninstall")
removed = run([binary, "lint", "legacy-branches.mq.md"], cwd=work, env=env, expected=None)
require(removed.returncode != 0, f"{version}: removed lint still dispatches")
return {"install_exit": 0, "remove_exit": 0, "dispatch_after_remove_exit": removed.returncode,
"static_child_commands": commands, "cases": evidence}
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("rc1", type=Path, help="frozen marqdo 3.0.0-rc.1 executable")
parser.add_argument("rc2", type=Path, help="frozen marqdo 3.0.0-rc.2 executable")
parser.add_argument("--report", type=Path, help="write JSON evidence to this path")
args = parser.parse_args()
try:
binaries = dict(zip(RELEASES, (args.rc1.resolve(), args.rc2.resolve())))
before = {version: validate_core(binary, version) for version, binary in binaries.items()}
strace = shutil.which("strace")
require(strace, "strace is required to verify the Tool v1 subprocess contract")
results = {}
for version, binary in binaries.items():
passed = test_suite(binary)
print(f"{version}: cargo test --locked, {passed} tests passed", flush=True)
results[version] = {**RELEASES[version], "tests_passed": passed, "binary_sha256_before": before[version]}
with tempfile.TemporaryDirectory(prefix="marqdo-lint-release-") as scratch:
bundle = Path(scratch) / "bundle"
run([ROOT / "scripts/package-tool.sh", bundle])
manifest = json.loads((bundle / "tool.json").read_text())
require(manifest["compatibility"]["analysis"] == [2, 3], "unexpected bundle compatibility")
evidence = {
"lint_binary_sha256": sha256(bundle / "bin/marqdo-lint"),
"tool_analysis_compatibility": manifest["compatibility"]["analysis"],
"cores": results,
}
for version, binary in binaries.items():
results[version]["tool"] = validate_bundle(strace, binary, version, bundle, Path(scratch) / version)
after = sha256(binary)
require(after == before[version], f"{version}: core binary changed during gate")
results[version]["binary_sha256_after"] = after
print(f"{version}: packaged Tool v1 install, dispatch, exit codes and removal passed", flush=True)
if args.report:
args.report.write_text(json.dumps(evidence, ensure_ascii=False, indent=2) + "\n")
except (OSError, ValidationError, ValueError, KeyError) as error:
parser.exit(1, f"release gate failed: {error}\n")
if __name__ == "__main__":
main()