Skip to content
pi-c Artifact [9b25f58e16]
Login

Artifact [9b25f58e16]

Artifact 9b25f58e168a438cfbe24b3858cd14fb7540a90dc57f921dbc3607b62037a0e8:


#!/usr/bin/env python3
"""Snapshot local fixture evidence and hashes; never marks product contracts PASS."""
import argparse
from datetime import datetime, timezone
import hashlib
import json
from pathlib import Path
import platform
import re

ROOT = Path(__file__).resolve().parents[1]
OUT = ROOT / "build/qualification"


def hashed(path):
    path = path.resolve()
    if not path.is_relative_to(ROOT) or not path.is_file():
        raise ValueError(f"Missing/nonlocal evidence: {path}")
    if path.stat().st_size > 64 * 1024 * 1024:
        raise ValueError("Evidence exceeds 64 MiB limit")
    return {"path": str(path.relative_to(ROOT)),
            "sha256": hashlib.sha256(path.read_bytes()).hexdigest()}


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--log", type=Path, required=True)
    args = parser.parse_args()
    log = args.log.resolve()
    text = log.read_text()
    required = ("79 mapped IDs", "qualification:", "oracle-mutant:", "replay:",
                "assertion-disabled qualification builds are explicitly rejected",
                "fuzz: OK", "stat::number_of_executed_units:")
    if not all(marker in text for marker in required):
        raise ValueError("Incomplete local pipeline log; refusing PASS manifest")
    mcdc = json.loads((OUT / "mcdc/summary.json").read_text())
    bench = json.loads((OUT / "bench/results.json").read_text())
    if mcdc.get("status") != "PASS" or bench.get("status") != "PASS":
        raise ValueError("MC/DC or native fixture benchmark did not pass")
    fuzz = Path((OUT / "fuzz/latest-run.txt").read_text().strip())
    if not fuzz.resolve().is_relative_to(OUT / "fuzz"):
        raise ValueError("Fuzz evidence path escapes qualification directory")
    sources = [ROOT / "Makefile", ROOT / "reference/pi.lock.json"]
    for pattern in ("contracts/*.json", "test/qualification/*.[ch]", "test/fuzz/*.c",
                    "test/fuzz/corpus/*", "test/probes/*.c", "test/test_*.py",
                    "bench/*.c", "tools/*.py", "tools/*.sh", "tools/*.c",
                    "tools/remote/*.sh", "tools/remote/*.py", "test/remote/*",
                    "test/test_*.sh"):
        sources.extend(path for path in ROOT.glob(pattern) if path.is_file())
    binaries = [OUT / path for path in (
        "native/test_qualification", "native/test_oracle_mutant", "native/replay",
        "sanitize/test_qualification", "sanitize/test_oracle_mutant", "mcdc/probe",
        "bench/measure", "bench/o2", "bench/o3")]
    binaries.append(fuzz / "fuzz_ops")
    for optional in (OUT / "bench/lto", OUT / "run-bounded"):
        if optional.is_file():
            binaries.append(optional)
    artifacts = [log, OUT / "mcdc/summary.json", OUT / "mcdc/export.json",
                 OUT / "mcdc/context.txt", OUT / "bench/results.json",
                 OUT / "bench/metadata.txt", OUT / "assertion-guard.log",
                 fuzz / "output.log"]
    artifacts.extend(sorted((OUT / "bench").glob("*.measure.json")))
    artifacts.extend(sorted((OUT / "native").glob("*.argv")))
    artifacts.extend(sorted((OUT / "sanitize").glob("*.argv")))
    artifacts.append(fuzz / "fuzz_ops.argv")
    native_flags = (OUT / "native/test_qualification.argv").read_text().splitlines()
    versions = re.findall(r"== (?:normal|sanitize|fuzz): compiler (.+)", text)
    dependencies = {"scope": "fixture toolchain labels, not dynamic-library attestation",
                    "compiler_versions": sorted(set(versions))}
    benchmark_parameters = {}
    for line in (OUT / "bench/metadata.txt").read_text().splitlines():
        key, separator, value = line.partition("=")
        if separator and key in ("samples", "iterations", "deadline"):
            benchmark_parameters[key] = int(value)
    if not 20 <= benchmark_parameters.get("samples", 0) <= 200:
        raise ValueError("Benchmark sample metadata is missing or out of bounds")
    workload = {"saved_corpus": [hashed(path) for path in
                               sorted((ROOT / "test/fuzz/corpus").iterdir())],
                "benchmark_parameters": benchmark_parameters,
                "fixture_campaign": "100 DST seeds; bounded seed-1 operation-sequence fuzz smoke"}
    record = {
        "version": 1, "status": "PASS", "scope": "qualification_fixture",
        "generated_at": datetime.now(timezone.utc).isoformat(),
        "reason": "Local fixture gates passed; remote and production qualification remain gated",
        "sources": [hashed(path) for path in sorted(set(sources))],
        "binaries": [hashed(path) for path in binaries],
        "artifacts": [hashed(path) for path in artifacts],
        "command": ["make", "check", "sanitize", "fuzz-smoke", "bench"],
        "host": platform.platform() + " " + platform.machine(),
        "toolchain": {"compiler": "native clang and libFuzzer clang (see retained log)",
                      "version": "; ".join(sorted(set(versions))),
                      "flags": native_flags[1:]},
        "toolchain_note": "Primary flags are the actual native test argv; variant argv/context/metadata are retained separately",
        "dependencies": dependencies,
        "dependencies_sha256": hashlib.sha256(json.dumps(dependencies, sort_keys=True).encode()).hexdigest(),
        "workload_sha256": hashlib.sha256(json.dumps(workload, sort_keys=True).encode()).hexdigest(),
        "samples": benchmark_parameters["samples"],
        "sample_kind": "samples per native benchmark measurement",
        "durability_policy": "fixture-only; no SQLite or fsync qualification",
        "failure_model": "simulated fixture transitions; not host/power-loss recovery",
        "contract_ids": [], "teardown": {"status": "not-required", "resources": []},
        "limitations": ["Remote work is paused; no remote resources created",
                        "Local benchmark fixtures are informational, not product performance"]
    }
    path = OUT / "local-evidence.json"
    path.write_text(json.dumps(record, indent=2) + "\n")
    print("Fixture evidence manifest:", path.relative_to(ROOT))


if __name__ == "__main__":
    try:
        main()
    except (ValueError, OSError, KeyError, TypeError) as error:
        raise SystemExit(f"FAIL: {error}")