diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 89aecbc..0416cac 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -19,6 +19,8 @@ jobs: components: rustfmt, clippy - name: Rust cache uses: Swatinem/rust-cache@v2 + - name: Verify the pinned stdlib Bundle + run: python3 tools/stdlib/bundle.py - name: Formatting run: cargo fmt --all -- --check - name: Clippy @@ -41,7 +43,10 @@ jobs: run: cargo test -p marqdo-cli --test architecture_boundaries - name: CI evidence tool tests run: python3 -m unittest discover -s tools/ci -p "test_*.py" - - name: Whole stdlib product tests + - name: Whole stdlib product tests (explicit pinned Bundle) + env: + MARQDO_TEST_STDLIB_BUNDLE: ${{ github.workspace }}/stdlib + MARQDO_TEST_BUNDLE_PIN: ${{ github.workspace }}/tools/stdlib/bundle-pin.json run: cargo test -p marqdo-cli --test stdlib_product - name: Validate public JSON schemas run: | @@ -93,6 +98,16 @@ jobs: --trust-native-plugin \ --allow-plugin demo.solver + independent-build: + name: independent CLI/worker build (no stdlib source) + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: dtolnay/rust-toolchain@stable + - uses: Swatinem/rust-cache@v2 + - name: Build from a copy without stdlib and run a language-only program + run: python3 tools/ci/independent_build.py + schema: name: schema instance validation + consumers runs-on: ubuntu-latest @@ -240,7 +255,7 @@ jobs: release-evidence: name: release evidence manifest - needs: [test, schema, cross-platform, frozen-extensions] + needs: [test, schema, cross-platform, frozen-extensions, independent-build] if: always() runs-on: ubuntu-latest steps: @@ -253,6 +268,7 @@ jobs: LINUX_RESULT: ${{ needs.test.result }} SCHEMA_RESULT: ${{ needs.schema.result }} EXTENSIONS_RESULT: ${{ needs.frozen-extensions.result }} + INDEPENDENT_RESULT: ${{ needs.independent-build.result }} run: | set -euo pipefail state() { @@ -263,11 +279,12 @@ jobs: esac } linux="$(state "$LINUX_RESULT")" - if [ "$(state "$SCHEMA_RESULT")" != "PASS" ] || [ "$(state "$EXTENSIONS_RESULT")" != "PASS" ]; then + if [ "$(state "$SCHEMA_RESULT")" != "PASS" ] || [ "$(state "$EXTENSIONS_RESULT")" != "PASS" ] || [ "$(state "$INDEPENDENT_RESULT")" != "PASS" ]; then linux="FAIL" fi python3 tools/ci/release_evidence.py --profile rc --target-sha "$TARGET_SHA" \ --out "docs/evidence/ci/$TARGET_SHA/manifest.json" \ + --gate "independent_build=$(state "$INDEPENDENT_RESULT"):$TARGET_SHA:$RUN_URL" \ --gate "linux=$linux:$TARGET_SHA:$RUN_URL" \ --gate "windows=UNSUPPORTED:$TARGET_SHA:linux-only-rc-scope" \ --gate "macos=UNSUPPORTED:$TARGET_SHA:linux-only-rc-scope" \ diff --git a/.woodpecker/main.yml b/.woodpecker/main.yml index d385bdb..1026359 100644 --- a/.woodpecker/main.yml +++ b/.woodpecker/main.yml @@ -39,6 +39,7 @@ steps: - apt-get install -y --no-install-recommends curl ca-certificates python3 python3-jsonschema build-essential gcc-mingw-w64-x86-64 - curl -fsSL https://deb.nodesource.com/setup_22.x | bash - - apt-get install -y --no-install-recommends nodejs + - python3 tools/stdlib/bundle.py - cargo fmt --all -- --check - cargo clippy --workspace --all-targets -- -D warnings # Provider CLI tests resolve a real provider worker next to the CLI @@ -48,12 +49,19 @@ steps: - cargo test -p marqdo-cli --test docs_consistency - cargo test -p marqdo-cli --test architecture_boundaries - python3 -m unittest discover -s tools/ci -p "test_*.py" - - cargo test -p marqdo-cli --test stdlib_product + - MARQDO_TEST_STDLIB_BUNDLE="$PWD/stdlib" MARQDO_TEST_BUNDLE_PIN="$PWD/tools/stdlib/bundle-pin.json" cargo test -p marqdo-cli --test stdlib_product # Windows compile gate: runtime lanes are native on GitHub; this catches # cfg/compile regressions on the Linux CI without a Windows runner. - rustup target add x86_64-pc-windows-gnu - cargo check --workspace --all-targets --target x86_64-pc-windows-gnu + independent-build: + image: rust:1.100-bookworm + commands: + - apt-get update + - apt-get install -y --no-install-recommends ca-certificates git python3 + - python3 tools/ci/independent_build.py + minimum-rust: image: rust:1.89-bookworm commands: @@ -71,6 +79,7 @@ steps: # only supported transport and resolution is a sibling-of-CLI lookup. - cargo build --release --locked -p marqdo-cli -p marqdo-provider-worker - test -x target/release/marqdo-provider-worker + - python3 tools/stdlib/bundle.py # Build the deterministic archive from this exact commit and cold-install # smoke-test it; the package script refuses a dirty tree or wrong SHA. - | diff --git a/.woodpecker/performance.yml b/.woodpecker/performance.yml index 57a3e43..0589f90 100644 --- a/.woodpecker/performance.yml +++ b/.woodpecker/performance.yml @@ -10,6 +10,7 @@ steps: commands: - apt-get update - apt-get install -y --no-install-recommends python3 util-linux ca-certificates git openssl build-essential + - python3 tools/stdlib/bundle.py - cargo build --release --locked -p marqdo-cli -p marqdo-provider-worker - | set -eu @@ -38,7 +39,8 @@ steps: (cd "$perf_dir/beta" && python3 tools/perf/runner.py --no-build \ --warmups 5 --samples 20 --platform-id woodpecker-agent-1 \ --cpu-list "$cpu_list" --out "$perf_dir/beta.json" > /dev/null) - python3 tools/perf/runner.py --no-build --binary "$candidate/marqdo" --warmups 5 --samples 20 \ + python3 tools/perf/runner.py --no-build --binary "$candidate/marqdo" \ + --stdlib-dir "$candidate/stdlib" --warmups 5 --samples 20 \ --platform-id woodpecker-agent-1 --cpu-list "$cpu_list" \ --baseline "$perf_dir/beta.json" --out perf.json > /dev/null python3 - <<'PY' diff --git a/docs/ci.md b/docs/ci.md index 0457026..dca2f7b 100644 --- a/docs/ci.md +++ b/docs/ci.md @@ -14,8 +14,10 @@ The default Docker pipeline runs on push and pull request. A fast `contract` lane exercises the public Analysis/Observation contracts through the real CLI and the independent Python consumers; the full `test` lane runs the Rust gates -and the Windows cross-target compile check; `build` packages the archive, runs -the from-archive smoke and the frozen external conformance suite. +and the Windows cross-target compile check; `independent-build` exports the +commit without `stdlib/` and proves both shipped binaries still build and run a +language-only program; `build` packages the archive from the pinned stdlib +Bundle, runs the from-archive smoke and the frozen external conformance suite. ```text contract (rust:1.100-bookworm, python3-jsonschema, both shipped binaries): @@ -26,21 +28,29 @@ contract (rust:1.100-bookworm, python3-jsonschema, both shipped binaries): stale-Analysis rejection test (rust:1.100-bookworm, clippy/rustfmt, Node.js 22, MinGW, both binaries): + python3 tools/stdlib/bundle.py (verify the pinned Bundle) cargo fmt --all -- --check cargo clippy --workspace --all-targets -- -D warnings cargo build --locked -p marqdo-provider-worker cargo test --workspace --locked docs_consistency / architecture_boundaries / stdlib_product + stdlib_product again with MARQDO_TEST_STDLIB_BUNDLE + MARQDO_TEST_BUNDLE_PIN python3 -m unittest discover -s tools/ci -p "test_*.py" rustup target add x86_64-pc-windows-gnu cargo check --workspace --all-targets --target x86_64-pc-windows-gnu +independent-build (rust:1.100-bookworm, git, python3): + git archive HEAD, remove stdlib/, no ecosystem checkout + cargo build --locked -p marqdo-cli -p marqdo-provider-worker + language-only check/call through the built CLI + stdlib-dependent run must fail closed; no stdlib/ next to the binary + minimum-rust (rust:1.89-bookworm): cargo check --locked --workspace --all-targets build (depends on test, minimum-rust, contract): cargo build --release --locked -p marqdo-cli -p marqdo-provider-worker - package the deterministic archive for $CI_COMMIT_SHA + python3 tools/stdlib/bundle.py; package --stdlib-dir stdlib --bundle-pin ... from-archive smoke (tools/release/smoke.py) frozen external conformance (tools/ci/run_frozen_extensions.sh, 7/7) ``` @@ -93,6 +103,11 @@ syntax; Debian bookworm's Node 18 fails those tests. workspace tests so the provider CLI tests use the real helper, and adds a `cargo check --workspace --all-targets --target x86_64-pc-windows-gnu` compile gate (native Windows/macOS runtime lanes stay on the GitHub matrix). +* **ADR-0070 explicit Bundle:** the `test` lane verifies + `tools/stdlib/bundle-pin.json` and runs the product suite once with an + explicit `MARQDO_TEST_STDLIB_BUNDLE`; the new `independent-build` lane builds + both binaries from a copy without `stdlib/` and requires the stdlib-dependent + program to fail closed. * The Woodpecker **build** lane and the GitHub **release-candidate** lane build `marqdo` **and** `marqdo-provider-worker` and package both as siblings; the provider transport resolves only that sibling (no PATH fallback), so an diff --git a/docs/performance.md b/docs/performance.md index 79f0265..c4bf528 100644 --- a/docs/performance.md +++ b/docs/performance.md @@ -27,9 +27,12 @@ dominated by emulation and is not comparable with native or KVM. ## Tool `tools/perf/runner.py` (schema `marqdo.perf.v2`) builds one release binary, -records its SHA256/Cargo.lock/rustc/source SHA, verifies every workload's exact -wire digest **before** timing, then reports warmups/samples, p50, p95, MAD, -CPU user/sys, peak RSS and the environment manifest. See +records its SHA256/Cargo.lock/rustc/source SHA, resolves one pinned stdlib +Bundle (name, version, tree/alias digests, source commit) and passes it to every +workload as `MARQDO_STDLIB_DIR`, verifies every workload's exact wire digest +**before** timing, then reports warmups/samples, p50, p95, MAD, CPU user/sys, +peak RSS and the environment manifest. A bad Bundle input or digest mismatch +fails before any workload runs; there is no checkout fallback (ADR-0070). See [`tools/perf/README.md`](../tools/perf/README.md). Rules enforced by the tool: diff --git a/tests/independent/language-only.mq.md b/tests/independent/language-only.mq.md new file mode 100644 index 0000000..0647ee9 --- /dev/null +++ b/tests/independent/language-only.mq.md @@ -0,0 +1,12 @@ +# Language-only program + +This fixture uses only the language itself: no `std:` import, no host +capability, no foreign kernel and no plugin. It is the program the +independent-build lane runs through a real CLI built from a copy without the +`stdlib/` tree (ADR-0070). + +## @exec main + +`值 = 1 + 2` + +`return 值` diff --git a/tools/ci/independent_build.py b/tools/ci/independent_build.py new file mode 100644 index 0000000..7f9355c --- /dev/null +++ b/tools/ci/independent_build.py @@ -0,0 +1,217 @@ +#!/usr/bin/env python3 +"""Prove the CLI and Provider Worker build without any stdlib source (ADR-0070). + +The script exports one committed revision with `git archive`, removes the +`stdlib/` tree (there is no ecosystem checkout either), builds +`marqdo-cli` + `marqdo-provider-worker` with `--locked`, and then: + +* runs a language-only program through the freshly built CLI (`check` + `call`); +* requires a stdlib-dependent program to fail closed — the debug source + fallback points at the removed copy, so a success would be a real defect; +* requires no `stdlib/` directory next to the built binary; +* records both binary digests and the source SHA. + +Usage: + + python3 tools/ci/independent_build.py + python3 tools/ci/independent_build.py --offline --keep +""" + +from __future__ import annotations + +import argparse +import hashlib +import io +import json +import os +import re +import shutil +import subprocess +import sys +import tarfile +import tempfile +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[2] +BINARIES = ("marqdo", "marqdo-provider-worker") +LANGUAGE_ONLY = Path("tests/independent/language-only.mq.md") +STDLIB_DEPENDENT = Path("examples/hello.mq.md") +MISSING_BUNDLE_PATTERN = re.compile(r"stdlib|symbol\.unknown|打印|print", re.IGNORECASE) + + +class BuildError(Exception): + pass + + +def run( + command: list[str], + cwd: Path, + *, + env: dict[str, str] | None = None, + timeout: float = 1800, + check: bool = True, +) -> subprocess.CompletedProcess: + completed = subprocess.run( + command, + cwd=cwd, + env=env, + text=True, + capture_output=True, + timeout=timeout, + ) + if check and completed.returncode != 0: + raise BuildError( + f"command failed ({completed.returncode}): {' '.join(command)}\n" + f"stdout:\n{completed.stdout}\nstderr:\n{completed.stderr}" + ) + return completed + + +def sha256_file(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for chunk in iter(lambda: handle.read(1024 * 1024), b""): + digest.update(chunk) + return digest.hexdigest() + + +def git_output(repo: Path, *arguments: str) -> bytes: + completed = subprocess.run( + ["git", "-C", str(repo), *arguments], + capture_output=True, + ) + if completed.returncode != 0: + raise BuildError( + f"git {' '.join(arguments)} failed: {completed.stderr.decode(errors='replace')}" + ) + return completed.stdout + + +def export_revision(repo: Path, revision: str, destination: Path) -> str: + try: + head = git_output(repo, "rev-parse", revision).decode().strip() + archive = git_output(repo, "archive", "--format=tar", revision) + except (OSError, subprocess.TimeoutExpired) as error: + raise BuildError(f"cannot export {revision} from {repo}: {error}") from error + destination.mkdir(parents=True, exist_ok=True) + with tarfile.open(fileobj=io.BytesIO(archive), mode="r:") as tar: + try: + tar.extractall(destination, filter="fully_trusted") + except TypeError: # Python < 3.12 without the PEP 706 backport + tar.extractall(destination) + return head + + +def main(argv: list[str]) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--repo", default=str(ROOT)) + parser.add_argument("--source", default="HEAD", help="committed revision to export") + parser.add_argument("--work-dir", default=None, help="explicit work directory (kept)") + parser.add_argument("--target-dir", default=None, help="cargo target directory (kept)") + parser.add_argument("--offline", action="store_true") + parser.add_argument("--keep", action="store_true") + parser.add_argument("--timeout", type=float, default=1800.0) + args = parser.parse_args(argv) + + repo = Path(args.repo).resolve() + if args.work_dir: + work = Path(args.work_dir).resolve() + if work.exists(): + shutil.rmtree(work) + keep = True + else: + work = Path(tempfile.mkdtemp(prefix="marqdo-independent-build-")) + keep = args.keep + target = Path(args.target_dir).resolve() if args.target_dir else work / "target" + source = work / "source" + try: + source_sha = export_revision(repo, args.source, source) + stdlib = source / "stdlib" + if not stdlib.is_dir(): + raise BuildError( + "the exported revision has no stdlib/ tree; the lane must remove a " + "real Bundle to prove the build does not need it" + ) + shutil.rmtree(stdlib) + if stdlib.exists(): + raise BuildError(f"failed to remove {stdlib}") + + env = os.environ.copy() + env.pop("MARQDO_STDLIB_DIR", None) + env["CARGO_TARGET_DIR"] = str(target) + env.setdefault("NO_COLOR", "1") + command = ["cargo", "build", "--locked", "-p", "marqdo-cli", "-p", "marqdo-provider-worker"] + if args.offline: + command.append("--offline") + run(command, source, env=env, timeout=args.timeout) + + binary = target / "debug" / "marqdo" + if not binary.is_file(): + raise BuildError(f"the build produced no CLI binary at {binary}") + if (binary.parent / "stdlib").exists(): + raise BuildError(f"a stdlib/ directory appeared next to {binary}") + binaries = {} + for name in BINARIES: + path = target / "debug" / name + if not path.is_file(): + raise BuildError(f"the build produced no {name} binary at {path}") + binaries[name] = {"sha256": sha256_file(path), "size": path.stat().st_size} + + checked = run([str(binary), "check", str(LANGUAGE_ONLY)], source, env=env, timeout=args.timeout) + called = run( + [str(binary), "call", str(LANGUAGE_ONLY), "main"], + source, + env=env, + timeout=args.timeout, + ) + if called.stdout.strip() != "3": + raise BuildError( + f"language-only call printed {called.stdout.strip()!r}, expected '3'" + ) + missing = run( + [str(binary), "run", str(STDLIB_DEPENDENT)], + source, + env=env, + timeout=args.timeout, + check=False, + ) + if missing.returncode == 0: + raise BuildError( + "a stdlib-dependent program succeeded without any stdlib Bundle " + "(a source fallback exists); this is a release blocker" + ) + if not MISSING_BUNDLE_PATTERN.search(missing.stderr + missing.stdout): + raise BuildError( + "the missing-Bundle failure does not name the stdlib/print/symbol " + f"cause:\n{missing.stderr}" + ) + + summary = { + "schema": "marqdo.independent-build", + "schema_version": 1, + "source_sha": source_sha, + "source_revision": args.source, + "copy": str(source), + "target_dir": str(target), + "binaries": binaries, + "checks": { + "stdlib_source_removed": True, + "language_only_check": "PASS", + "language_only_call": "PASS:3", + "stdlib_dependent_missing_bundle": "PASS", + "no_sibling_stdlib": True, + }, + "status": "PASS", + } + print(json.dumps(summary, indent=2, sort_keys=True)) + return 0 + except BuildError as error: + print(f"independent-build: error: {error}", file=sys.stderr) + return 1 + finally: + if not keep: + shutil.rmtree(work, ignore_errors=True) + + +if __name__ == "__main__": + raise SystemExit(main(sys.argv[1:])) diff --git a/tools/perf/README.md b/tools/perf/README.md index bc3e2bf..8217de3 100644 --- a/tools/perf/README.md +++ b/tools/perf/README.md @@ -27,6 +27,11 @@ workload whose wire output did not match the committed expected digest. governor, CPU affinity and toolchain. For an approved-node comparison it also requires an approved, correctness-verified MEASURED baseline. Record competing load and investigate differences before sign-off. +* One explicit Bundle: `--stdlib-dir` (default: the pinned Bundle) is verified + against `tools/stdlib/bundle-pin.json`, and every workload receives it as + `MARQDO_STDLIB_DIR`. The report records the Bundle name, version, tree/alias + digests and source commit. A bad input or digest mismatch fails before any + workload runs; there is no checkout fallback (ADR-0070). * Avoid TCG/QEMU for final performance numbers; use native or KVM with fixed CPU affinity (`--cpu-list`) and an administrator-approved governor. * The suggested investigation thresholds are p50 +15% and peak RSS +20%; they diff --git a/tools/perf/runner.py b/tools/perf/runner.py index b14a8ef..548fcfe 100755 --- a/tools/perf/runner.py +++ b/tools/perf/runner.py @@ -38,6 +38,9 @@ EXPECTED = ROOT / "tools" / "perf" / "expected" SCHEMA = "marqdo.perf.v2" MIN_WARMUPS = 5 MIN_SAMPLES = 20 + +sys.path.insert(0, str(ROOT / "tools" / "stdlib")) +import bundle as stdlib_bundle # noqa: E402 P50_REGRESSION = 0.15 RSS_REGRESSION = 0.20 @@ -312,6 +315,7 @@ def run_workload( record: bool, timeout: float, cpu_list: str, + stdlib_dir: Path, ) -> dict: name = workload["name"] prefix = [] @@ -325,8 +329,9 @@ def run_workload( measured_argv = prefix + [str(binary)] + (workload.get("measure_argv") or workload["argv"]) env = dict(os.environ) env.pop("MARQDO_STDLIB_DIR", None) - if not (binary.parent / "stdlib" / "stdlib.json").is_file(): - env["MARQDO_STDLIB_DIR"] = str(ROOT / "stdlib") + # One explicit, pinned Bundle for every workload; no sibling or checkout + # fallback (ADR-0070). + env["MARQDO_STDLIB_DIR"] = str(stdlib_dir) env.setdefault("NO_COLOR", "1") expected_document = load_expected(name) expected = expected_document.get("wire_sha256") if expected_document else None @@ -514,6 +519,8 @@ def compare_baseline(report: dict, baseline: dict) -> list[dict]: def main(argv: list[str]) -> int: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--binary", default=str(ROOT / "target" / "release" / "marqdo")) + parser.add_argument("--stdlib-dir", default=None) + parser.add_argument("--bundle-pin", default=str(ROOT / "tools" / "stdlib" / "bundle-pin.json")) parser.add_argument("--no-build", action="store_true") parser.add_argument("--warmups", type=int, default=MIN_WARMUPS) parser.add_argument("--samples", type=int, default=MIN_SAMPLES) @@ -528,6 +535,13 @@ def main(argv: list[str]) -> int: parser.add_argument("--allow-smoke", action="store_true") args = parser.parse_args(argv) + try: + stdlib_dir, stdlib_record, stdlib_pin = stdlib_bundle.resolve( + args.stdlib_dir, Path(args.bundle_pin) + ) + except stdlib_bundle.BundleError as error: + raise SystemExit(f"perf: error: {error}") from error + if args.samples < 1 or args.warmups < 0: raise SystemExit("samples must be >= 1 and warmups >= 0") if (args.samples < MIN_SAMPLES or args.warmups < MIN_WARMUPS) and not args.allow_smoke: @@ -571,6 +585,7 @@ def main(argv: list[str]) -> int: args.record_expected, args.timeout, args.cpu_list, + stdlib_dir, ) results.append(result) print( @@ -589,6 +604,14 @@ def main(argv: list[str]) -> int: report = { "schema": SCHEMA, "source_sha": source_sha, + "stdlib": { + "name": stdlib_record["name"], + "version": stdlib_record["version"], + "tree_digest": stdlib_record["tree_digest"], + "aliases_digest": stdlib_record["aliases_digest"], + "source_commit": stdlib_pin["source"].get("commit"), + "root": str(stdlib_dir), + }, "platform_id": args.platform_id, "environment_approved": bool(args.approved_node), "binary": {