From b9c72e1d2a369fde015c2137d447a66f38beb841 Mon Sep 17 00:00:00 2001 From: cflmy Date: Thu, 26 Nov 2026 14:54:11 +0800 Subject: [PATCH 1/9] docs: inventory stdlib source coupling and record the Phase A boundary Record ADR-0070 (one explicit stdlib Bundle build input) and the issue #11 Phase A inventory of every direct checkout-stdlib reference. Baseline 4bbefc9; bundle source 2cbde54; no runtime contract change. --- ...0070-explicit-stdlib-bundle-build-input.md | 123 ++++++++++++++++++ docs/adr/README.md | 3 + ...-11-26-stdlib-source-coupling-inventory.md | 72 ++++++++++ 3 files changed, 198 insertions(+) create mode 100644 docs/adr/0070-explicit-stdlib-bundle-build-input.md create mode 100644 docs/evidence/2026-11-26-stdlib-source-coupling-inventory.md diff --git a/docs/adr/0070-explicit-stdlib-bundle-build-input.md b/docs/adr/0070-explicit-stdlib-bundle-build-input.md new file mode 100644 index 0000000..c0d8e3d --- /dev/null +++ b/docs/adr/0070-explicit-stdlib-bundle-build-input.md @@ -0,0 +1,123 @@ +# ADR-0070 — One explicit stdlib Bundle build input (Phase A) + +Status: **Accepted for implementation on the 3.0 prerelease line** (2026-11-26). +Relates to: issue +[#11](https://git.cflmy.cn/cflmy/marqdo-cli/issues/11), ADR-0028 (bundled +stdlib and `std:` imports), ADR-0039 (deferred extraction), ADR-0058 (public +aliases), ADR-0062 (resource ownership), ADR-0068 (single current public +contracts). +Evidence: +[`docs/evidence/2026-11-26-stdlib-source-coupling-inventory.md`](../evidence/2026-11-26-stdlib-source-coupling-inventory.md). + +## Context + +Issue #11 starts the extraction that ADR-0039 deferred: the CLI and the +Provider Worker must build and run on their own, while a release is assembled +from one explicitly provided, verifiable stdlib Bundle. The extraction trigger +listed by ADR-0039 is now real: an ecosystem repository pins component commits +and assembles the production Bundle, and nine component repositories own module +sources. + +At the implementation baseline `4bbefc92449ee480c8a2c89b0308feb4cda8d0e7` the +stdlib source directory is implicit in four different ways, documented in the +inventory linked above: + +* both packaging entry points read the checkout's `stdlib/` with no build + argument (`tools/pack-stdlib.py`, `tools/release/package.py`); +* product tests, the semantic harness and the P2 closure lane rebuild + `repo_root()/stdlib` independently; +* the performance runner silently falls back to `ROOT / "stdlib"` when the + binary has no sibling bundle; +* the debug CLI resolves a compile-time source tree + (`CARGO_MANIFEST_DIR/../../stdlib`) after the explicit override and the + sibling directory. + +Separating compile, package and product-test lanes later requires changing all +of them at once, and none of them records which Bundle commit produced a test +run. The runtime contracts themselves — `stdlib.json`, the +`marqdo.stdlib-package` descriptor, Analysis `project.stdlib` and Observation +identity — are not the problem and must not change. + +## Decision + +### 1. Explicit build input + +`tools/pack-stdlib.py` and `tools/release/package.py` accept the same required +`--stdlib-dir PATH` argument. It names an unpacked Bundle root that contains +`stdlib.json`. There is no implicit default: a missing path, a missing manifest, +a tree-digest mismatch, an alias-digest mismatch or a missing required module +fails the command before any archive is written. Both entry points keep the +existing deterministic archive layout, descriptor fields, digest algorithms +and checksums. + +Both entry points also accept an optional `--bundle-pin PATH`. When given, the +input must match the pinned identity and the release record names the pinned +source commit; the pin is not a substitute for verifying the Bundle's own +manifest. + +### 2. One pinned Bundle identity + +`tools/stdlib/bundle-pin.json` records the Bundle name, version, source +repository and commit, tree digest and alias digest. `tools/stdlib/bundle.py` +is the single resolver and verifier for source-side consumers: tests, the +performance runner and release CI resolve the Bundle through it instead of +concatenating `stdlib/`. + +An explicit `MARQDO_TEST_STDLIB_BUNDLE` (tests) or `--stdlib-dir` (tools) takes +precedence over the pin's default location, but the input must still verify +against the pin's digests. An invalid explicit input fails even when a valid +sibling Bundle exists; silent fallback is forbidden. Phase B updates the pin to +the Bundle assembled by the ecosystem repository; the algorithm does not change. + +### 3. Runtime contract unchanged + +`MARQDO_STDLIB_DIR` remains the explicit runtime override (invalid values fail +hard), followed by `stdlib/` next to the executable. The debug-only +compile-time source fallback remains in Phase A so the development loop keeps +working; it is removed in Phase B together with the in-repo production sources. +`stdlib.json`, `marqdo.stdlib-package`, Analysis `project.stdlib`, module ids +and Observation identity keep their current shapes and values. + +### 4. Separated test lanes + +The lanes become explicit: + +* **independent compilation** — `cargo build --locked -p marqdo-cli + -p marqdo-provider-worker` in a copy without `stdlib/`, then a language-only + program through the real CLI; +* **loader unit tests** — small synthetic bundles built in a temporary + directory, so loader logic does not depend on the product tree; +* **product tests** — the whole pinned Bundle through `std:` and the real CLI; +* **conformance** — the frozen, independent fixture corpus, unchanged. + +### 5. Phase B gate + +Phase B (switch to the ecosystem-assembled Bundle, delete the in-repo +production sources, the debug source fallback and the replaced `std:` entries) +requires the accepted component commits of ecosystem issue #2 and the extension +replacement evidence named by issue #11. This ADR records the Phase A input +boundary only; it does not authorize deleting sources or changing `std:` +semantics. + +## Consequences + +* A packaging run can be pointed at a downloaded or separately built Bundle and + still produce the same deterministic archive and `RELEASE_INFO.json` record. +* Every product/perf CI run names the Bundle commit and digest it used; a + stale Bundle is visible instead of implicit. +* Phase B becomes a pin/CI change plus source removal, not a simultaneous + rewrite of the test lanes. +* The repository still carries the Bundle in Phase A, so the extraction is not + claimed as complete. `docs/STATUS.md` must record the Phase A state, not the + final externalized state. + +## Non-goals + +* Changing `std:` spelling, digest algorithms, module ids, public aliases or + the `stdlib.json`/descriptor shapes. +* Fetching a Bundle over the network, adding a package registry or a signature + scheme. +* Removing the debug source fallback, the in-repo `stdlib/` sources or any + `std:` entry in Phase A. +* Declaring the extraction, the external Conformance suite or the ecosystem + switch done before their evidence exists. diff --git a/docs/adr/README.md b/docs/adr/README.md index 5bd2204..b29dc33 100644 --- a/docs/adr/README.md +++ b/docs/adr/README.md @@ -70,3 +70,6 @@ Files: `0001`–`0050`, plus: pre-stable public boundary, replaced in place; * [0069](0069-public-analysis-boundary.md) — one public Analysis projection for independent document, lint and knowledge consumers. +* [0070](0070-explicit-stdlib-bundle-build-input.md) — Phase A of the stdlib + extraction: one required `--stdlib-dir` build input, one pinned Bundle + identity for tests/perf/release CI; runtime contracts unchanged. diff --git a/docs/evidence/2026-11-26-stdlib-source-coupling-inventory.md b/docs/evidence/2026-11-26-stdlib-source-coupling-inventory.md new file mode 100644 index 0000000..a566e1e --- /dev/null +++ b/docs/evidence/2026-11-26-stdlib-source-coupling-inventory.md @@ -0,0 +1,72 @@ +# Stdlib source-directory coupling inventory (issue #11, Phase A) + +Date: 2026-11-26. +Implementation baseline: `4bbefc92449ee480c8a2c89b0308feb4cda8d0e7` (current +`master`). Bundle source commit: `2cbde54602c07f62a62f341400bc9cb4764a93f8` +(the last commit that touched `stdlib/` at the baseline). Pinned Bundle: +`marqdo-stdlib` `0.1.0`, tree digest +`sha256:5407d3665ba2fe105820d0f1af5efaafa10c277a69eb819c3225719813c8c713`, +alias digest +`sha256:5f513c0fdbb3c1e9829be3c9fa23a2d1e89cb8510073fb5eb1e8e2f5265a83bb`. + +This file inventories every direct reference to the checkout's stdlib source +directory found for issue #11 Phase A, before the explicit build-input change. +It is an inventory, not a claim that Phase A is finished; the executed evidence +is recorded separately when the work lands. Decision: +[ADR-0070](../adr/0070-explicit-stdlib-bundle-build-input.md). + +## Packaging and release tooling + +| Entry point | Reference | Phase A disposition | +|---|---|---| +| `tools/pack-stdlib.py` | `STDLIB = ROOT / "stdlib"` (line 17); used by the tree digest, manifest read, file list, archive and descriptor (lines 37–97) | required `--stdlib-dir`, optional `--bundle-pin`; shared digest/verify helper | +| `tools/release/package.py` | `STDLIB = ROOT / "stdlib"` (line 37); `verify_stdlib` (lines 110–141), staging copy (line 229), `RELEASE_INFO.stdlib` (lines 245–264) | required `--stdlib-dir`, optional `--bundle-pin`; `RELEASE_INFO.stdlib.source` records the pinned commit | +| `tools/release/smoke.py` | reads only the extracted archive's `install/stdlib` (lines 81–116) | unchanged; it stays an independent verifier of the shipped bytes | +| `tools/perf/runner.py` | pops `MARQDO_STDLIB_DIR`, then falls back to `ROOT / "stdlib"` when the binary has no sibling bundle (lines 327–330) | resolve the pinned Bundle explicitly and always export `MARQDO_STDLIB_DIR`; no silent repo fallback | +| `tools/ci/test_release_archive.py` | reads `ROOT/stdlib/stdlib.json` and `ROOT/stdlib` (lines 33, 40, 54) | pass the explicit/pinned path; add failure-path assertions | +| `.github/workflows/ci.yml` | `package.py` invocation without a Bundle argument (line 224); product lane (lines 44–45) | pass `--stdlib-dir` + `--bundle-pin`; verify the pin in the product lane | +| `.woodpecker/main.yml` | product lane (line 51), `package.py` invocation (line 80) | same as above | +| `.woodpecker/performance.yml` | `package.py` invocation (line 25) | pass `--stdlib-dir` + `--bundle-pin`; perf runner resolves the pin | +| `docs/releasing.md` | release command without a Bundle argument (line 119) | document the required input and the pin | + +## Runtime and development discovery + +| Entry point | Reference | Phase A disposition | +|---|---|---| +| `crates/cli/src/stdlib.rs` | debug-only `CARGO_MANIFEST_DIR/../../stdlib` fallback after `MARQDO_STDLIB_DIR` and the sibling directory (lines 73–82) | keep for the development loop; remove in Phase B | +| `crates/cli/src/stdlib.rs` unit tests | `dev_bundle()` loads the whole in-repo tree (lines 457–492) | replace with synthetic small bundles so loader tests do not depend on the product tree | + +## Test harnesses that rebuild `repo_root()/stdlib` + +| Harness | Reference | Role | Phase A disposition | +|---|---|---|---| +| `crates/cli/tests/stdlib_product.rs` | `stdlib_dir()` (lines 35–37), fixtures (line 48), cwd/`MARQDO_STDLIB_DIR` (lines 130–138) | product | pinned resolver | +| `crates/cli/tests/stdlib_bundle.rs` | `stdlib_dir()` (lines 19–20) | product | pinned resolver | +| `crates/cli/tests/stdlib_http.rs` | cwd and `MARQDO_STDLIB_DIR` (lines 22–23) | product | pinned resolver | +| `crates/cli/tests/stdlib_table.rs` | cwd and `MARQDO_STDLIB_DIR` (lines 21–22) | product | pinned resolver | +| `crates/cli/tests/stdlib_alias_routing.rs` | copies `repo()/stdlib` (lines 64–65) | product | pinned resolver | +| `crates/cli/tests/p2_closure.rs` | table self-test path, cwd and env (lines 112, 122–123) | product | pinned resolver | +| `crates/cli/tests/conformance_semantics.rs` | alias binding (line 294), entry `std:` imports (line 431) | conformance | pinned resolver | +| `crates/cli/tests/architecture_boundaries.rs` | in-repo digest/import gates (lines 90–114, 442–477) | architecture gate | pinned resolver plus the Phase A in-repo assertion | + +## References that are intentionally not build inputs + +* `crates/cli/src/analysis/*`, `crates/cli/src/loader.rs` and + `crates/cli/src/commands.rs` consume the verified `StdlibBundle` identity at + run time; they do not read the source directory. +* `crates/marqdo-runtime/src/builtins_impl.rs` and + `crates/marqdo-sandbox/*` mention stdlib only in diagnostics/tests. +* `docs/evidence/*` and historical ADRs keep their recorded paths; they are + decision history, not executable inputs. + +## Acceptance for Phase A + +1. A clean copy without `stdlib/` and without an ecosystem checkout builds + `marqdo-cli` and `marqdo-provider-worker` with `--locked`. +2. Both packaging entries fail without `--stdlib-dir`, and fail on a missing + directory, a missing `stdlib.json`, a tree-digest mismatch, an alias-digest + mismatch or a pin mismatch. +3. Product tests, the performance runner and release CI resolve the Bundle + through `tools/stdlib/bundle.py` and name its pinned commit and digest. +4. The frozen Conformance corpus and the independent `tools/release/smoke.py` + checks stay in place. -- 2.54.1 From 1b9d9c4c26335f8c0e21c3a995b9eec05a3a01d3 Mon Sep 17 00:00:00 2001 From: cflmy Date: Thu, 26 Nov 2026 15:00:26 +0800 Subject: [PATCH 2/9] stdlib: add one pinned Bundle resolver and explicit pack input Add tools/stdlib/bundle.py + bundle-pin.json as the single source-side Bundle identity (name, version, source commit, tree/alias digests) and require tools/pack-stdlib.py --stdlib-dir instead of reading the checkout implicitly. Missing input, missing manifest, digest/alias mismatch, pin mismatch and symlinks fail closed; two packs are byte-identical. Tests: tools/ci/test_stdlib_bundle_tools.py. --- tools/ci/test_stdlib_bundle_tools.py | 316 +++++++++++++++++++++++++++ tools/pack-stdlib.py | 125 ++++++----- tools/stdlib/bundle-pin.json | 15 ++ tools/stdlib/bundle.py | 308 ++++++++++++++++++++++++++ 4 files changed, 700 insertions(+), 64 deletions(-) create mode 100644 tools/ci/test_stdlib_bundle_tools.py create mode 100644 tools/stdlib/bundle-pin.json create mode 100644 tools/stdlib/bundle.py diff --git a/tools/ci/test_stdlib_bundle_tools.py b/tools/ci/test_stdlib_bundle_tools.py new file mode 100644 index 0000000..4c8575a --- /dev/null +++ b/tools/ci/test_stdlib_bundle_tools.py @@ -0,0 +1,316 @@ +"""Explicit stdlib Bundle input tests (ADR-0070 / issue #11 Phase A). + +Covers the shared resolver (`tools/stdlib/bundle.py`) and the deterministic +package entry point (`tools/pack-stdlib.py`). The digest helpers here are +independent re-implementations so a bug in the shared helper cannot make the +test agree with itself. +""" + +from __future__ import annotations + +import contextlib +import hashlib +import importlib.util +import io +import json +import os +import tarfile +import tempfile +import unittest +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[2] + + +def load_module(name: str, path: Path): + spec = importlib.util.spec_from_file_location(name, path) + module = importlib.util.module_from_spec(spec) + assert spec.loader is not None + spec.loader.exec_module(module) + return module + + +def independent_tree_digest(root: Path) -> str: + digest = hashlib.sha256() + paths = sorted( + (path.relative_to(root).as_posix(), path) + for path in root.rglob("*.mq.md") + if path.is_file() + ) + for relative, path in paths: + digest.update(relative.encode()) + digest.update(b"\0") + digest.update(path.read_bytes()) + digest.update(b"\0") + return "sha256:" + digest.hexdigest() + + +def independent_aliases_digest(aliases: list[dict]) -> str: + digest = hashlib.sha256() + for alias in sorted(aliases, key=lambda item: (item["target_module"], item["target_function"])): + digest.update(alias["target_module"].encode()) + digest.update(b"\0") + digest.update(alias["target_function"].encode()) + digest.update(b"\0") + for name in sorted(alias["public_names"]): + digest.update(name.encode()) + digest.update(b"\0") + return "sha256:" + digest.hexdigest() + + +ALIASES = [ + { + "public_names": ["print", "打印"], + "target_module": "io.mq.md", + "target_function": "写值", + "expected_signature": "params(值)", + "effects": ["write"], + } +] + + +def make_bundle(root: Path, *, version: str = "9.9.9", name: str = "marqdo-stdlib") -> dict: + """Create a minimal Bundle with independently computed digests.""" + root.mkdir(parents=True) + (root / "README.md").write_text("# test bundle\n") + (root / "io.mq.md").write_text("## @knowledge io\n") + (root / "io").mkdir() + (root / "io" / "console.mq.md").write_text("## @knowledge console\n") + manifest = { + "schema": "marqdo.stdlib-bundle", + "schema_version": 1, + "name": name, + "version": version, + "digest": independent_tree_digest(root), + "aliases_digest": independent_aliases_digest(ALIASES), + "public_aliases": ALIASES, + } + (root / "stdlib.json").write_text(json.dumps(manifest, indent=2) + "\n") + return manifest + + +def write_pin(path: Path, manifest: dict, source_path: str, commit: str = "a" * 40) -> dict: + pin = { + "schema": "marqdo.stdlib-bundle-pin", + "schema_version": 1, + "name": manifest["name"], + "version": manifest["version"], + "source": {"kind": "test", "repository": "test/test", "commit": commit, "path": source_path}, + "tree_digest": manifest["digest"], + "aliases_digest": manifest["aliases_digest"], + } + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(json.dumps(pin, indent=2) + "\n") + return pin + + +class BundleResolverTest(unittest.TestCase): + def setUp(self) -> None: + self.bundle = load_module("stdlib_bundle", ROOT / "tools/stdlib/bundle.py") + self.tmp = tempfile.TemporaryDirectory() + self.addCleanup(self.tmp.cleanup) + self.dir = Path(self.tmp.name) + + def test_repository_bundle_matches_the_pin(self) -> None: + root, record, pin = self.bundle.resolve() + self.assertEqual(root, (ROOT / "stdlib").resolve()) + self.assertEqual(record["tree_digest"], pin["tree_digest"]) + self.assertEqual(record["aliases_digest"], pin["aliases_digest"]) + self.assertEqual(record["name"], "marqdo-stdlib") + self.assertIn("io.mq.md", record["files"]) + + def test_explicit_valid_bundle_still_has_to_match_the_pin(self) -> None: + other = self.dir / "other-bundle" + matching = make_bundle(other) + pin_path = self.dir / "pin.json" + write_pin(pin_path, matching, str(other)) + root, record, _ = self.bundle.resolve(other, pin_path) + self.assertEqual(root, other.resolve()) + self.assertEqual(record["name"], "marqdo-stdlib") + + pinned = load_module("stdlib_bundle_pin_check", ROOT / "tools/stdlib/bundle.py") + self.assertRaisesRegex( + pinned.BundleError, + "does not match the pin", + pinned.verify_pin, + {"name": "marqdo-stdlib", "version": "0.1.0", + "tree_digest": "sha256:" + "0" * 64, "aliases_digest": "sha256:" + "0" * 64}, + pinned.load_pin(ROOT / "tools/stdlib/bundle-pin.json"), + ) + + def test_bad_explicit_input_fails_even_when_the_default_is_valid(self) -> None: + with self.assertRaisesRegex(self.bundle.BundleError, "does not exist"): + self.bundle.resolve(self.dir / "missing") + + def test_missing_manifest_fails(self) -> None: + bare = self.dir / "bare" + bare.mkdir() + (bare / "io.mq.md").write_text("## @knowledge io\n") + with self.assertRaisesRegex(self.bundle.BundleError, "has no manifest"): + self.bundle.verify(bare) + + def test_tree_digest_mismatch_fails(self) -> None: + bundle = self.dir / "tampered" + make_bundle(bundle) + (bundle / "io.mq.md").write_text("## @knowledge tampered\n") + with self.assertRaisesRegex(self.bundle.BundleError, "tree digest mismatch"): + self.bundle.verify(bundle) + + def test_alias_digest_mismatch_fails(self) -> None: + bundle = self.dir / "alias-tampered" + manifest = make_bundle(bundle) + manifest["aliases_digest"] = "sha256:" + "0" * 64 + (bundle / "stdlib.json").write_text(json.dumps(manifest) + "\n") + with self.assertRaisesRegex(self.bundle.BundleError, "alias digest mismatch"): + self.bundle.verify(bundle) + + def test_public_aliases_without_a_digest_fail(self) -> None: + bundle = self.dir / "no-alias-digest" + manifest = make_bundle(bundle) + del manifest["aliases_digest"] + (bundle / "stdlib.json").write_text(json.dumps(manifest) + "\n") + with self.assertRaisesRegex(self.bundle.BundleError, "without aliases_digest"): + self.bundle.verify(bundle) + + def test_symlink_inside_the_bundle_is_rejected(self) -> None: + bundle = self.dir / "linked" + make_bundle(bundle) + try: + (bundle / "escape.mq.md").symlink_to("/etc/hostname") + except (OSError, NotImplementedError): + self.skipTest("symbolic links are unavailable on this host") + with self.assertRaisesRegex(self.bundle.BundleError, "symbolic link"): + self.bundle.verify(bundle) + + def test_bad_pin_schema_is_rejected(self) -> None: + pin_path = self.dir / "bad-pin.json" + pin_path.write_text(json.dumps({"schema": "other", "schema_version": 1}) + "\n") + with self.assertRaisesRegex(self.bundle.BundleError, "schema_version"): + self.bundle.load_pin(pin_path) + + def test_cli_prints_the_resolved_path(self) -> None: + stdout = io.StringIO() + with contextlib.redirect_stdout(stdout): + self.assertEqual(self.bundle.main(["--print-path"]), 0) + self.assertEqual(Path(stdout.getvalue().strip()), (ROOT / "stdlib").resolve()) + + def test_cli_fails_for_an_invalid_explicit_input(self) -> None: + stderr = io.StringIO() + with contextlib.redirect_stderr(stderr): + self.assertEqual(self.bundle.main(["--stdlib-dir", str(self.dir / "missing")]), 1) + self.assertIn("does not exist", stderr.getvalue()) + + +class PackStdlibTest(unittest.TestCase): + def setUp(self) -> None: + self.pack = load_module("pack_stdlib", ROOT / "tools/pack-stdlib.py") + self.tmp = tempfile.TemporaryDirectory() + self.addCleanup(self.tmp.cleanup) + self.dir = Path(self.tmp.name) + + def run_pack(self, *args: str) -> int: + stdout = io.StringIO() + with contextlib.redirect_stdout(stdout): + return self.pack.main(list(args)) + + def test_stdlib_dir_is_required(self) -> None: + with self.assertRaises(SystemExit) as raised, contextlib.redirect_stderr(io.StringIO()): + self.pack.main([]) + self.assertEqual(raised.exception.code, 2) + + def test_missing_input_fails(self) -> None: + with self.assertRaises(SystemExit) as raised: + self.run_pack("--stdlib-dir", str(self.dir / "missing"), "--out-dir", str(self.dir)) + self.assertIn("does not exist", str(raised.exception.code)) + + def test_missing_manifest_fails(self) -> None: + bare = self.dir / "bare" + bare.mkdir() + with self.assertRaises(SystemExit) as raised: + self.run_pack("--stdlib-dir", str(bare), "--out-dir", str(self.dir)) + self.assertIn("has no manifest", str(raised.exception.code)) + + def test_tampered_tree_fails(self) -> None: + bundle = self.dir / "bundle" + make_bundle(bundle) + (bundle / "io.mq.md").write_text("## @knowledge tampered\n") + with self.assertRaises(SystemExit) as raised: + self.run_pack("--stdlib-dir", str(bundle), "--out-dir", str(self.dir)) + self.assertIn("tree digest mismatch", str(raised.exception.code)) + + def test_pin_mismatch_fails(self) -> None: + bundle = self.dir / "bundle" + manifest = make_bundle(bundle) + pin_path = self.dir / "pin.json" + pin = write_pin(pin_path, manifest, str(bundle)) + pin["tree_digest"] = "sha256:" + "0" * 64 + pin_path.write_text(json.dumps(pin) + "\n") + with self.assertRaises(SystemExit) as raised: + self.run_pack( + "--stdlib-dir", str(bundle), "--out-dir", str(self.dir), "--bundle-pin", str(pin_path) + ) + self.assertIn("does not match the pin", str(raised.exception.code)) + + def test_pack_is_deterministic_and_records_the_bundle_identity(self) -> None: + bundle = self.dir / "bundle" + manifest = make_bundle(bundle) + pin_path = self.dir / "pin.json" + write_pin(pin_path, manifest, str(bundle)) + first = self.dir / "first" + second = self.dir / "second" + for out in (first, second): + self.assertEqual( + self.run_pack( + "--stdlib-dir", str(bundle), "--out-dir", str(out), + "--bundle-pin", str(pin_path), + ), + 0, + ) + archive_name = "marqdo-stdlib-9.9.9.tar.gz" + first_bytes = (first / archive_name).read_bytes() + self.assertEqual(first_bytes, (second / archive_name).read_bytes()) + self.assertEqual( + (first / f"{archive_name}.sha256").read_bytes(), + (second / f"{archive_name}.sha256").read_bytes(), + ) + descriptor = json.loads((first / "marqdo-stdlib-9.9.9.json").read_text()) + self.assertEqual(descriptor["schema"], "marqdo.stdlib-package") + self.assertEqual(descriptor["schema_version"], 1) + self.assertEqual(descriptor["name"], manifest["name"]) + self.assertEqual(descriptor["version"], manifest["version"]) + self.assertEqual(descriptor["tree_digest"], independent_tree_digest(bundle)) + self.assertEqual(descriptor["aliases_digest"], independent_aliases_digest(ALIASES)) + self.assertEqual( + descriptor["archive_sha256"], "sha256:" + hashlib.sha256(first_bytes).hexdigest() + ) + self.assertEqual(descriptor["files"], sorted(descriptor["files"])) + + with tarfile.open(first / archive_name, mode="r:gz") as archive: + members = archive.getmembers() + self.assertEqual([m.name for m in members], descriptor["files"]) + for member in members: + self.assertEqual(member.mtime, 0) + self.assertIn(member.uid, (0,)) + self.assertEqual(member.gid, 0) + self.assertEqual(member.mode, 0o644) + self.assertEqual( + archive.extractfile("io.mq.md").read(), (bundle / "io.mq.md").read_bytes() + ) + + def test_repository_bundle_packs_against_the_committed_pin(self) -> None: + out = self.dir / "out" + self.assertEqual( + self.run_pack( + "--stdlib-dir", str(ROOT / "stdlib"), "--out-dir", str(out), + "--bundle-pin", str(ROOT / "tools/stdlib/bundle-pin.json"), + ), + 0, + ) + descriptor = json.loads((out / "marqdo-stdlib-0.1.0.json").read_text()) + manifest = json.loads((ROOT / "stdlib/stdlib.json").read_text()) + self.assertEqual(descriptor["tree_digest"], manifest["digest"]) + self.assertEqual(descriptor["aliases_digest"], manifest["aliases_digest"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/pack-stdlib.py b/tools/pack-stdlib.py index dbe455b..e7d0414 100755 --- a/tools/pack-stdlib.py +++ b/tools/pack-stdlib.py @@ -1,74 +1,79 @@ #!/usr/bin/env python3 -"""Build a deterministic offline marqdo-stdlib package. +"""Build a deterministic offline marqdo-stdlib package from an explicit Bundle. -The archive is intended for the separate external stdlib repository/release -workflow, not for the CLI's in-repo development fallback. It contains the -Markdown stdlib tree, stdlib.json and README.md, with stable mtimes/ownership. +The input is one unpacked Bundle root (a directory that contains +`stdlib.json`), passed with the required `--stdlib-dir`. This script does not +read the checkout's `stdlib/` implicitly: the CLI release and the separate +stdlib release workflow both name the Bundle they package (ADR-0070). + +The archive contains the Markdown stdlib tree, `stdlib.json` and every other +file in the Bundle, with stable mtimes/ownership. An optional `--bundle-pin` +also requires the input to match the pinned name/version/commit/digests. + +Usage: + + python3 tools/pack-stdlib.py --stdlib-dir stdlib \ + --bundle-pin tools/stdlib/bundle-pin.json """ +from __future__ import annotations + +import argparse import hashlib import io import json -import os +import sys import tarfile from pathlib import Path ROOT = Path(__file__).resolve().parents[1] -STDLIB = ROOT / "stdlib" DIST = ROOT / "dist" - -def aliases_digest(manifest: dict) -> str: - digest = hashlib.sha256() - for alias in sorted( - manifest.get("public_aliases", []), - key=lambda a: (a["target_module"], a["target_function"]), - ): - digest.update(alias["target_module"].encode()) - digest.update(b"\0") - digest.update(alias["target_function"].encode()) - digest.update(b"\0") - for name in sorted(alias["public_names"]): - digest.update(name.encode()) - digest.update(b"\0") - return f"sha256:{digest.hexdigest()}" +sys.path.insert(0, str(Path(__file__).resolve().parent / "stdlib")) +import bundle as stdlib_bundle # noqa: E402 -def tree_digest() -> str: - digest = hashlib.sha256() - for path in sorted( - STDLIB.rglob("*.mq.md"), key=lambda p: p.relative_to(STDLIB).as_posix() - ): - relative = path.relative_to(STDLIB).as_posix() - digest.update(relative.encode()) - digest.update(b"\0") - digest.update(path.read_bytes()) - digest.update(b"\0") - return digest.hexdigest() +def gzip_open(raw): + import gzip + + return gzip.GzipFile(fileobj=raw, mode="wb", mtime=0, filename="") -def main() -> int: - manifest = json.loads((STDLIB / "stdlib.json").read_text()) - version = manifest["version"] - digest = tree_digest() - if manifest["digest"] != f"sha256:{digest}": - raise SystemExit("stdlib.json digest does not match the tree") - alias_digest = aliases_digest(manifest) - if manifest.get("aliases_digest") != alias_digest: - raise SystemExit("stdlib.json aliases_digest does not match public_aliases") +def verify_input(root: Path, pin_path: Path | None) -> dict: + try: + record = stdlib_bundle.verify(root) + stdlib_bundle.require_files(record, ("stdlib.json",)) + if record["aliases_digest"] is None: + raise stdlib_bundle.BundleError( + f"{root / 'stdlib.json'} declares no aliases_digest" + ) + if pin_path is not None: + pin = stdlib_bundle.load_pin(pin_path) + stdlib_bundle.verify_pin(record, pin) + except stdlib_bundle.BundleError as error: + raise SystemExit(f"pack-stdlib: error: {error}") from error + return record - files = sorted( - [p for p in STDLIB.rglob("*") if p.is_file() and p.name != "stdlib.json"] - + [STDLIB / "stdlib.json"], - key=lambda p: p.relative_to(STDLIB).as_posix(), - ) - DIST.mkdir(exist_ok=True) - archive = DIST / f"marqdo-stdlib-{version}.tar.gz" + +def main(argv: list[str]) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--stdlib-dir", required=True) + parser.add_argument("--out-dir", default=str(DIST)) + parser.add_argument("--bundle-pin", default=None) + args = parser.parse_args(argv) + + root = Path(args.stdlib_dir) + record = verify_input(root, Path(args.bundle_pin) if args.bundle_pin else None) + version = record["version"] + files = [root / name for name in record["files"]] + out_dir = Path(args.out_dir) + out_dir.mkdir(parents=True, exist_ok=True) + archive = out_dir / f"marqdo-stdlib-{version}.tar.gz" with archive.open("wb") as raw: with gzip_open(raw) as gz: with tarfile.open(fileobj=gz, mode="w") as tar: for path in files: - relative = path.relative_to(STDLIB).as_posix() + relative = path.relative_to(root).as_posix() info = tarfile.TarInfo(name=relative) data = path.read_bytes() info.size = len(data) @@ -81,28 +86,20 @@ def main() -> int: descriptor = { "schema": "marqdo.stdlib-package", "schema_version": 1, - "name": manifest["name"], + "name": record["name"], "version": version, - "tree_digest": f"sha256:{digest}", - "aliases_digest": alias_digest, + "tree_digest": record["tree_digest"], + "aliases_digest": record["aliases_digest"], "archive": archive.name, "archive_sha256": f"sha256:{archive_sha}", - "files": [p.relative_to(STDLIB).as_posix() for p in files], + "files": record["files"], } - descriptor_path = DIST / f"marqdo-stdlib-{version}.json" + descriptor_path = out_dir / f"marqdo-stdlib-{version}.json" descriptor_path.write_text(json.dumps(descriptor, indent=2) + "\n") - (DIST / f"{archive.name}.sha256").write_text( - f"{archive_sha} {archive.name}\n" - ) + (out_dir / f"{archive.name}.sha256").write_text(f"{archive_sha} {archive.name}\n") print(json.dumps(descriptor, indent=2)) return 0 -def gzip_open(raw): - import gzip - - return gzip.GzipFile(fileobj=raw, mode="wb", mtime=0, filename="") - - if __name__ == "__main__": - raise SystemExit(main()) + raise SystemExit(main(sys.argv[1:])) diff --git a/tools/stdlib/bundle-pin.json b/tools/stdlib/bundle-pin.json new file mode 100644 index 0000000..f81bc90 --- /dev/null +++ b/tools/stdlib/bundle-pin.json @@ -0,0 +1,15 @@ +{ + "schema": "marqdo.stdlib-bundle-pin", + "schema_version": 1, + "name": "marqdo-stdlib", + "version": "0.1.0", + "source": { + "kind": "in-repo", + "repository": "cflmy/marqdo-cli", + "commit": "2cbde54602c07f62a62f341400bc9cb4764a93f8", + "path": "stdlib", + "note": "Phase A (ADR-0070): the pinned Bundle is the checkout tree at this commit. Phase B replaces this record with the accepted ecosystem Bundle commit and digest; do not change it in the same commit as test fixtures." + }, + "tree_digest": "sha256:5407d3665ba2fe105820d0f1af5efaafa10c277a69eb819c3225719813c8c713", + "aliases_digest": "sha256:5f513c0fdbb3c1e9829be3c9fa23a2d1e89cb8510073fb5eb1e8e2f5265a83bb" +} diff --git a/tools/stdlib/bundle.py b/tools/stdlib/bundle.py new file mode 100644 index 0000000..b470a64 --- /dev/null +++ b/tools/stdlib/bundle.py @@ -0,0 +1,308 @@ +#!/usr/bin/env python3 +"""One resolver and verifier for a stdlib Bundle (ADR-0070). + +Every source-side consumer that needs the official Bundle — packaging tools, +product tests, the performance runner and release CI — resolves it through +this module instead of concatenating a checkout path. The identity comes from +`tools/stdlib/bundle-pin.json` (name, version, source commit, tree digest, +alias digest); an explicit input may change the location but must still match +the pinned digests. + +The digest algorithms are byte-identical to `marqdo_cli::stdlib` and to +`tools/release/smoke.py` (which stays an independent verifier of the shipped +archive). Nothing here is used by the running CLI. + +Usage: + + python3 tools/stdlib/bundle.py [--stdlib-dir PATH] [--pin PATH] [--print-path] + +Exit status is 1 for an invalid Bundle and 2 for a bad command line. +""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import os +import sys +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[2] +PIN_PATH = ROOT / "tools" / "stdlib" / "bundle-pin.json" +PIN_SCHEMA = "marqdo.stdlib-bundle-pin" +PIN_SCHEMA_VERSION = 1 +REQUIRED_MANIFEST_FIELDS = ("name", "version", "digest") + + +class BundleError(Exception): + """An input is not a verifiable stdlib Bundle.""" + + +def _sha256_bytes(*chunks: bytes) -> str: + digest = hashlib.sha256() + for chunk in chunks: + digest.update(chunk) + return "sha256:" + digest.hexdigest() + + +def _walk_files(root: Path) -> list[Path]: + """Every regular file under `root`, sorted, rejecting symlinks. + + Deterministic packaging must not follow a link outside the Bundle root or + archive a link whose target differs by platform. + """ + files: list[Path] = [] + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + dirnames.sort() + base = Path(dirpath) + for name in dirnames: + if (base / name).is_symlink(): + raise BundleError( + f"stdlib Bundle contains a symbolic link directory: " + f"{(base / name).relative_to(root).as_posix()}" + ) + for name in sorted(filenames): + path = base / name + if path.is_symlink(): + raise BundleError( + f"stdlib Bundle contains a symbolic link: " + f"{path.relative_to(root).as_posix()}" + ) + if path.is_file(): + files.append(path) + files.sort(key=lambda path: path.relative_to(root).as_posix()) + return files + + +def load_manifest(root: Path) -> dict: + manifest_path = root / "stdlib.json" + if not root.is_dir(): + raise BundleError(f"stdlib Bundle directory does not exist: {root}") + if not manifest_path.is_file(): + raise BundleError(f"stdlib Bundle has no manifest: {manifest_path}") + try: + manifest = json.loads(manifest_path.read_text(encoding="utf-8")) + except (OSError, UnicodeDecodeError, json.JSONDecodeError) as error: + raise BundleError(f"cannot read valid JSON from {manifest_path}: {error}") from error + if not isinstance(manifest, dict): + raise BundleError(f"{manifest_path} must contain a JSON object") + for field in REQUIRED_MANIFEST_FIELDS: + value = manifest.get(field) + if not isinstance(value, str) or not value: + raise BundleError(f"{manifest_path} has no non-empty `{field}`") + return manifest + + +def tree_digest(root: Path) -> str: + """`relative POSIX path + NUL + bytes + NUL` over every `*.mq.md` file.""" + root = Path(root) + chunks: list[bytes] = [] + for path in _walk_files(root): + if not path.name.endswith(".mq.md"): + continue + chunks.append(path.relative_to(root).as_posix().encode()) + chunks.append(b"\0") + chunks.append(path.read_bytes()) + chunks.append(b"\0") + return _sha256_bytes(*chunks) + + +def aliases_digest(manifest: dict) -> str: + """Canonical digest over `public_aliases`, byte-identical to the loader.""" + chunks: list[bytes] = [] + aliases = sorted( + manifest.get("public_aliases", []), + key=lambda alias: (alias["target_module"], alias["target_function"]), + ) + for alias in aliases: + chunks.append(alias["target_module"].encode()) + chunks.append(b"\0") + chunks.append(alias["target_function"].encode()) + chunks.append(b"\0") + for name in sorted(alias["public_names"]): + chunks.append(name.encode()) + chunks.append(b"\0") + return _sha256_bytes(*chunks) + + +def _verify_aliases(manifest: dict, manifest_path: Path) -> list[dict]: + raw = manifest.get("public_aliases", []) + if not isinstance(raw, list): + raise BundleError(f"{manifest_path} public_aliases must be an array") + seen: set[str] = set() + aliases: list[dict] = [] + for entry in raw: + if not isinstance(entry, dict): + raise BundleError(f"{manifest_path} public alias must be an object") + names = entry.get("public_names") + if not isinstance(names, list) or not names: + raise BundleError(f"{manifest_path} public alias declares no names") + for name in names: + if not isinstance(name, str) or not name: + raise BundleError(f"{manifest_path} public alias name must be a non-empty string") + if name in seen: + raise BundleError(f"{manifest_path} public alias name `{name}` is declared twice") + seen.add(name) + module = entry.get("target_module") + if not isinstance(module, str) or not module: + raise BundleError(f"{manifest_path} public alias has no target_module") + relative = Path(module) + if relative.is_absolute() or ".." in relative.parts: + raise BundleError( + f"{manifest_path} public alias target_module `{module}` must stay inside the Bundle" + ) + function = entry.get("target_function") + if not isinstance(function, str) or not function: + raise BundleError(f"{manifest_path} public alias has no target_function") + aliases.append(entry) + aliases.sort(key=lambda alias: (alias["target_module"], alias["target_function"])) + return aliases + + +def verify(root: Path) -> dict: + """Validate one unpacked Bundle root and return its identity record.""" + root = Path(root) + manifest = load_manifest(root) + manifest_path = root / "stdlib.json" + tree = tree_digest(root) + declared_tree = manifest["digest"] + if declared_tree != tree: + raise BundleError( + f"stdlib tree digest mismatch: stdlib.json declares {declared_tree}, " + f"the files are {tree}" + ) + aliases = _verify_aliases(manifest, manifest_path) + declared_aliases = manifest.get("aliases_digest") + actual_aliases = aliases_digest(manifest) + if declared_aliases is None and aliases: + raise BundleError(f"{manifest_path} declares public_aliases without aliases_digest") + if declared_aliases is not None and declared_aliases != actual_aliases: + raise BundleError( + f"stdlib public-alias digest mismatch: stdlib.json declares {declared_aliases}, " + f"the alias table is {actual_aliases}" + ) + files = sorted(path.relative_to(root).as_posix() for path in _walk_files(root)) + modules = [name for name in files if name.endswith(".mq.md")] + if not modules: + raise BundleError(f"stdlib Bundle {root} contains no .mq.md module") + return { + "name": manifest["name"], + "version": manifest["version"], + "tree_digest": tree, + "aliases_digest": actual_aliases if declared_aliases is not None else None, + "file_count": len(files), + "files": files, + } + + +def require_files(record: dict, required: tuple[str, ...]) -> None: + missing = [name for name in required if name not in record["files"]] + if missing: + raise BundleError( + "stdlib Bundle is missing required file(s): " + ", ".join(missing) + ) + + +def load_pin(path: Path = PIN_PATH) -> dict: + path = Path(path) + try: + pin = json.loads(path.read_text(encoding="utf-8")) + except (OSError, UnicodeDecodeError, json.JSONDecodeError) as error: + raise BundleError(f"cannot read Bundle pin {path}: {error}") from error + if not isinstance(pin, dict): + raise BundleError(f"Bundle pin {path} must contain a JSON object") + if pin.get("schema") != PIN_SCHEMA or pin.get("schema_version") != PIN_SCHEMA_VERSION: + raise BundleError( + f"Bundle pin {path} must be {PIN_SCHEMA} schema_version {PIN_SCHEMA_VERSION}" + ) + source = pin.get("source") + if not isinstance(source, dict) or not isinstance(source.get("path"), str): + raise BundleError(f"Bundle pin {path} has no source.path") + for field in ("name", "version", "tree_digest", "aliases_digest"): + if not isinstance(pin.get(field), str) or not pin[field]: + raise BundleError(f"Bundle pin {path} has no non-empty `{field}`") + return pin + + +def verify_pin(record: dict, pin: dict) -> None: + """Require a verified Bundle record to match the pinned identity.""" + for field in ("name", "version", "tree_digest", "aliases_digest"): + if record.get(field) != pin.get(field): + raise BundleError( + f"stdlib Bundle does not match the pin: {field} is " + f"{record.get(field)!r}, the pin records {pin.get(field)!r}" + ) + + +def resolve( + explicit: str | Path | None = None, + pin_path: Path = PIN_PATH, + *, + require_pin: bool = True, +) -> tuple[Path, dict, dict]: + """Resolve and verify the Bundle, returning `(root, record, pin)`. + + `explicit` overrides the pinned location but never the pinned identity + unless `require_pin` is false. A bad explicit input fails even when the + default location is valid; there is no fallback. + """ + pin = load_pin(pin_path) + if explicit is None: + root = ROOT / pin["source"]["path"] + else: + root = Path(explicit) + record = verify(root) + if require_pin: + verify_pin(record, pin) + require_files( + record, + ( + "stdlib.json", + "io.mq.md", + "io/console.mq.md", + ), + ) + return root.resolve(), record, pin + + +def main(argv: list[str]) -> int: + parser = argparse.ArgumentParser( + description="Resolve and verify the pinned stdlib Bundle (ADR-0070)." + ) + parser.add_argument("--stdlib-dir", default=None) + parser.add_argument("--pin", default=str(PIN_PATH)) + parser.add_argument("--print-path", action="store_true") + parser.add_argument("--dump-pin", action="store_true") + args = parser.parse_args(argv) + try: + root, record, pin = resolve(args.stdlib_dir, Path(args.pin)) + except BundleError as error: + print(f"bundle: error: {error}", file=sys.stderr) + return 1 + if args.print_path: + print(root) + return 0 + if args.dump_pin: + print(json.dumps(pin, indent=2, sort_keys=True)) + return 0 + print( + json.dumps( + { + "root": str(root), + "name": record["name"], + "version": record["version"], + "tree_digest": record["tree_digest"], + "aliases_digest": record["aliases_digest"], + "source_commit": pin["source"].get("commit"), + "file_count": record["file_count"], + }, + indent=2, + sort_keys=True, + ) + ) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main(sys.argv[1:])) -- 2.54.1 From 422b9de6d7b5d4504c53aca5fa632288ea32711d Mon Sep 17 00:00:00 2001 From: cflmy Date: Thu, 26 Nov 2026 15:07:29 +0800 Subject: [PATCH 3/9] release: take the stdlib Bundle as one explicit, pinned input package.py now requires --stdlib-dir and accepts --bundle-pin; it verifies the manifest, required files, tree/alias digests and the pin before staging, copies exactly that Bundle next to the binary, and records stdlib.source{kind,repository,commit,path} in RELEASE_INFO. Digest logic moves to tools/stdlib/bundle.py. GitHub/Woodpecker release steps and docs/releasing.md pass the pinned input. --- .github/workflows/ci.yml | 3 +- .woodpecker/main.yml | 3 +- .woodpecker/performance.yml | 3 +- docs/releasing.md | 15 +++- tools/ci/test_release_archive.py | 61 +++++++++++-- tools/release/package.py | 143 +++++++++++++++---------------- 6 files changed, 138 insertions(+), 90 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 4071633..89aecbc 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -221,7 +221,8 @@ jobs: cargo build --release --locked -p marqdo-cli -p marqdo-provider-worker version="$(cargo metadata --no-deps --format-version 1 --offline \ | python3 -c 'import json,sys; print(next(p["version"] for p in json.load(sys.stdin)["packages"] if p["name"]=="marqdo-cli"))')" - python3 tools/release/package.py --source-sha "$GITHUB_SHA" --version "$version" + python3 tools/release/package.py --source-sha "$GITHUB_SHA" --version "$version" \ + --stdlib-dir stdlib --bundle-pin tools/stdlib/bundle-pin.json python3 tools/release/smoke.py --archive dist/marqdo-*.tar.gz tools/ci/run_frozen_extensions.sh dist/marqdo-*.tar.gz "$GITHUB_SHA" dist/frozen-extension-evidence.json - uses: actions/upload-artifact@v4 diff --git a/.woodpecker/main.yml b/.woodpecker/main.yml index d07b483..d385bdb 100644 --- a/.woodpecker/main.yml +++ b/.woodpecker/main.yml @@ -77,7 +77,8 @@ steps: set -eu version="$(cargo metadata --no-deps --format-version 1 --offline \ | python3 -c 'import json,sys; print(next(p["version"] for p in json.load(sys.stdin)["packages"] if p["name"]=="marqdo-cli"))')" - python3 tools/release/package.py --source-sha "$CI_COMMIT_SHA" --version "$version" + python3 tools/release/package.py --source-sha "$CI_COMMIT_SHA" --version "$version" \ + --stdlib-dir stdlib --bundle-pin tools/stdlib/bundle-pin.json python3 tools/release/smoke.py --archive dist/marqdo-*.tar.gz tools/ci/run_frozen_extensions.sh dist/marqdo-*.tar.gz "$CI_COMMIT_SHA" dist/frozen-extension-evidence.json cat dist/frozen-extension-evidence.json diff --git a/.woodpecker/performance.yml b/.woodpecker/performance.yml index 2c868f3..57a3e43 100644 --- a/.woodpecker/performance.yml +++ b/.woodpecker/performance.yml @@ -22,7 +22,8 @@ steps: (cd "$perf_dir/beta" && cargo build --release --locked -p marqdo-cli) version="$(target/release/marqdo --version | cut -d ' ' -f 2)" - python3 tools/release/package.py --version "$version" --source-sha "$CI_COMMIT_SHA" --out-dir "$perf_dir" + python3 tools/release/package.py --version "$version" --source-sha "$CI_COMMIT_SHA" \ + --stdlib-dir stdlib --bundle-pin tools/stdlib/bundle-pin.json --out-dir "$perf_dir" archive="$perf_dir/marqdo-$version-x86_64-unknown-linux-gnu.tar.gz" (cd "$perf_dir" && sha256sum -c "$(basename "$archive.sha256")") tar -xzf "$archive" -C "$perf_dir" diff --git a/docs/releasing.md b/docs/releasing.md index 60e8d6a..e77b079 100644 --- a/docs/releasing.md +++ b/docs/releasing.md @@ -116,7 +116,8 @@ The archive is built deterministically from a clean tree at `SOURCE_SHA`: version="$(cargo metadata --no-deps --format-version 1 --offline \ | python3 -c 'import json,sys; print(next(p["version"] for p in json.load(sys.stdin)["packages"] if p["name"]=="marqdo-cli"))')" sha="$(git rev-parse HEAD)" -python3 tools/release/package.py --version "$version" --source-sha "$sha" +python3 tools/release/package.py --version "$version" --source-sha "$sha" \ + --stdlib-dir stdlib --bundle-pin tools/stdlib/bundle-pin.json # dist/marqdo--x86_64-unknown-linux-gnu.tar.gz(+.sha256) ``` @@ -128,9 +129,15 @@ and self-test), `LICENSE-APACHE`, `README.md`, `CHANGELOG.md`, `COMPATIBILITY.md artifacts so the examples run without a compiler) and `tests/consumers/`. `RELEASE_INFO.json` records the stdlib `name`, `version`, `tree_digest`, -`aliases_digest`, `file_count` and `files`. `package.py` recomputes both digests -with the same canonical algorithm as the runtime and refuses to package a mismatch -with `stdlib/stdlib.json` (RFC-EXT-0003 H-08 / T-PKG-04). +`aliases_digest`, `file_count` and `files`, plus `stdlib.source` (kind, +repository, commit, path) when `--bundle-pin` is given. `--stdlib-dir` is a +required build input and names the unpacked Bundle root; `package.py` verifies +its manifest and recomputes both digests with the same canonical algorithm as +the runtime, and fails on a missing directory, a missing `stdlib.json`, a +tree/alias digest mismatch or a pin mismatch before it stages anything +(ADR-0070, RFC-EXT-0003 H-08 / T-PKG-04). The pin itself is resolved and +verified by `python3 tools/stdlib/bundle.py`; tests, the performance runner and +release CI use the same resolver instead of an implicit checkout path. The `protocols.analysis` field identifies the default Analysis major. `protocols.analysis_versions` lists all majors the archive can emit. The archive smoke exercises a published example and a consumer for each major. The bundled stdlib is a diff --git a/tools/ci/test_release_archive.py b/tools/ci/test_release_archive.py index a76f640..ae8c430 100644 --- a/tools/ci/test_release_archive.py +++ b/tools/ci/test_release_archive.py @@ -2,8 +2,8 @@ These tests are stdlib-only and do not build an archive; they pin the digest helpers that package.py/smoke.py share with the runtime and check that the -release pipeline references a verified stdlib bundle instead of relying on the -compile-time source path. +release pipeline takes the stdlib Bundle as one explicit, verified input +instead of relying on the compile-time source path (ADR-0070). """ from __future__ import annotations @@ -12,6 +12,8 @@ import contextlib import importlib.util import io import json +import shutil +import tempfile import unittest from pathlib import Path @@ -31,10 +33,11 @@ class ReleaseArchiveContractTest(unittest.TestCase): self.package = load_module("release_package", ROOT / "tools/release/package.py") self.smoke = load_module("release_smoke", ROOT / "tools/release/smoke.py") self.manifest = json.loads((ROOT / "stdlib/stdlib.json").read_text(encoding="utf-8")) + self.pin = json.loads((ROOT / "tools/stdlib/bundle-pin.json").read_text(encoding="utf-8")) def test_tree_digest_matches_manifest(self) -> None: self.assertEqual( - self.package.stdlib_tree_digest(), self.manifest["digest"] + self.package.stdlib_tree_digest(ROOT / "stdlib"), self.manifest["digest"] ) self.assertEqual( self.smoke.stdlib_tree_digest(ROOT / "stdlib"), self.manifest["digest"] @@ -51,7 +54,9 @@ class ReleaseArchiveContractTest(unittest.TestCase): ) def test_verify_record_names_required_files_and_count(self) -> None: - record = self.package.verify_stdlib() + record = self.package.verify_stdlib( + ROOT / "stdlib", ROOT / "tools/stdlib/bundle-pin.json" + ) self.assertEqual(record["name"], self.manifest["name"]) self.assertEqual(record["version"], self.manifest["version"]) self.assertEqual(record["tree_digest"], self.manifest["digest"]) @@ -60,13 +65,53 @@ class ReleaseArchiveContractTest(unittest.TestCase): self.assertIn("io.mq.md", record["files"]) self.assertIn("io/console.mq.md", record["files"]) self.assertEqual(record["file_count"], len(record["files"])) + self.assertEqual(record["source"]["commit"], self.pin["source"]["commit"]) + self.assertEqual(record["source"]["kind"], "in-repo") - def test_package_stages_stdlib_next_to_the_binary_and_math_backend(self) -> None: + def test_verify_record_has_no_source_without_a_pin(self) -> None: + record = self.package.verify_stdlib(ROOT / "stdlib") + self.assertNotIn("source", record) + + def test_missing_explicit_input_fails_closed(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + stderr = io.StringIO() + with contextlib.redirect_stderr(stderr): + with self.assertRaises(SystemExit) as raised: + self.package.verify_stdlib(Path(tmp) / "missing") + self.assertEqual(raised.exception.code, 1) + self.assertIn("does not exist", stderr.getvalue()) + + def test_tampered_explicit_input_and_wrong_pin_fail_closed(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + copy = Path(tmp) / "stdlib" + shutil.copytree(ROOT / "stdlib", copy) + (copy / "io.mq.md").write_text("## @knowledge tampered\n", encoding="utf-8") + with contextlib.redirect_stderr(io.StringIO()): + with self.assertRaises(SystemExit) as raised: + self.package.verify_stdlib(copy) + self.assertEqual(raised.exception.code, 1) + + shutil.rmtree(copy) + shutil.copytree(ROOT / "stdlib", copy) + restamped = json.loads((copy / "stdlib.json").read_text(encoding="utf-8")) + restamped["version"] = "9.9.9" + (copy / "stdlib.json").write_text(json.dumps(restamped), encoding="utf-8") + stderr = io.StringIO() + with contextlib.redirect_stderr(stderr): + with self.assertRaises(SystemExit) as raised: + self.package.verify_stdlib(copy, ROOT / "tools/stdlib/bundle-pin.json") + self.assertEqual(raised.exception.code, 1) + self.assertIn("does not match the pin", stderr.getvalue()) + + def test_package_takes_one_explicit_stdlib_dir(self) -> None: source = (ROOT / "tools/release/package.py").read_text(encoding="utf-8") - self.assertIn('copy_tree(STDLIB, stage_dir / "stdlib")', source) - self.assertIn('"math-backend"', source.replace("math_backend", "math-backend")) + self.assertIn('add_argument("--stdlib-dir", required=True)', source) + self.assertIn('add_argument("--bundle-pin"', source) + self.assertIn('copy_tree(stdlib_dir, stage_dir / "stdlib")', source) self.assertIn('"stdlib": stdlib_info', source) - self.assertIn("verify_stdlib()", source) + self.assertIn("verify_stdlib(", source) + self.assertNotIn('STDLIB = ROOT / "stdlib"', source) + self.assertIn('"math-backend"', source.replace("math_backend", "math-backend")) def test_archive_declares_only_current_analysis_revision(self) -> None: self.smoke.verify_analysis_metadata({"analysis": 3}) diff --git a/tools/release/package.py b/tools/release/package.py index b52c159..f1d645b 100644 --- a/tools/release/package.py +++ b/tools/release/package.py @@ -4,7 +4,13 @@ The archive is deterministic (sorted entries, commit timestamp, uid/gid 0) and contains the CLI, the provider worker helper (same directory, same target), the licenses/changelog/compatibility matrix, the public specs, the developer docs, -the runnable examples and the public protocol consumers. +the runnable examples, the public protocol consumers and the stdlib Bundle that +`--stdlib-dir` names. + +The stdlib Bundle is one required, explicit build input (ADR-0070): a missing +directory, missing manifest, tree/alias digest mismatch or pin mismatch fails +before anything is staged. An optional `--bundle-pin` also records the pinned +source commit in `RELEASE_INFO.json.stdlib.source`. It refuses to package a dirty tree, a version that does not match the Cargo workspace, or a HEAD that differs from `--source-sha`, and it fails if the @@ -16,7 +22,9 @@ Usage (from the repository root, after python3 tools/release/package.py \ --source-sha "$(git rev-parse HEAD)" \ - --version 3.0.0-rc.4 + --version 3.0.0-rc.4 \ + --stdlib-dir stdlib \ + --bundle-pin tools/stdlib/bundle-pin.json """ from __future__ import annotations @@ -34,7 +42,7 @@ from pathlib import Path ROOT = Path(__file__).resolve().parents[2] BINARIES = ("marqdo", "marqdo-provider-worker") -STDLIB = ROOT / "stdlib" +PRODUCT_STDLIB_FILES = ("stdlib.json", "io.mq.md", "io/console.mq.md") EXAMPLES_WITH_BUILD = ( "plugin-demo", "plugin-multi-export", @@ -42,6 +50,9 @@ EXAMPLES_WITH_BUILD = ( "math-backend", ) +sys.path.insert(0, str(ROOT / "tools" / "stdlib")) +import bundle as stdlib_bundle # noqa: E402 + def fail(message: str) -> "NoReturn": print(f"package: error: {message}", file=sys.stderr) @@ -64,81 +75,51 @@ def sha256_file(path: Path) -> str: return digest.hexdigest() -def sha256_bytes(*chunks: bytes) -> str: - digest = hashlib.sha256() - for chunk in chunks: - digest.update(chunk) - return "sha256:" + digest.hexdigest() +def stdlib_tree_digest(root: Path) -> str: + """Canonical stdlib tree digest, byte-identical to the CLI loader. - -def stdlib_tree_digest(root: Path = STDLIB) -> str: - """Canonical stdlib tree digest, byte-identical to - `marqdo_cli::stdlib::tree_digest`: sorted `*.mq.md` relative POSIX paths, - `path + NUL + bytes + NUL`.""" - paths = sorted( - (path.relative_to(root).as_posix(), path) - for path in root.rglob("*.mq.md") - if path.is_file() - ) - return sha256_bytes( - *( - chunk - for relative, path in paths - for chunk in (relative.encode(), b"\0", path.read_bytes(), b"\0") - ) - ) + The algorithm lives in `tools/stdlib/bundle.py` (ADR-0070); `root` is the + explicit `--stdlib-dir` input, never an implicit checkout path. + """ + return stdlib_bundle.tree_digest(root) def stdlib_aliases_digest(manifest: dict) -> str: """Canonical public-alias digest, byte-identical to the CLI loader.""" - chunks: list[bytes] = [] - aliases = sorted( - manifest.get("public_aliases", []), - key=lambda alias: (alias["target_module"], alias["target_function"]), - ) - for alias in aliases: - chunks.append(alias["target_module"].encode()) - chunks.append(b"\0") - chunks.append(alias["target_function"].encode()) - chunks.append(b"\0") - for name in sorted(alias["public_names"]): - chunks.append(name.encode()) - chunks.append(b"\0") - return sha256_bytes(*chunks) + return stdlib_bundle.aliases_digest(manifest) -def verify_stdlib() -> dict: - """Validate the shipped stdlib tree and return the RELEASE_INFO record.""" - manifest_path = STDLIB / "stdlib.json" - if not manifest_path.is_file(): - fail(f"missing bundled stdlib manifest {manifest_path}") - manifest = json.loads(manifest_path.read_text(encoding="utf-8")) - tree = stdlib_tree_digest() - aliases = stdlib_aliases_digest(manifest) - if tree != manifest.get("digest"): - fail(f"stdlib tree digest {tree} does not match stdlib.json digest {manifest.get('digest')}") - if aliases != manifest.get("aliases_digest"): - fail( - f"stdlib alias digest {aliases} does not match stdlib.json " - f"aliases_digest {manifest.get('aliases_digest')}" - ) - required = ["stdlib.json", "io.mq.md", "io/console.mq.md"] - files = sorted( - path.relative_to(STDLIB).as_posix() - for path in STDLIB.rglob("*") - if path.is_file() - ) - for name in required: - if name not in files: - fail(f"bundled stdlib is missing required file {name}") - return { - "name": manifest.get("name"), - "version": manifest.get("version"), - "tree_digest": tree, - "aliases_digest": aliases, - "file_count": len(files), - "files": files, - } +def verify_stdlib(root: Path, pin_path: Path | None = None) -> dict: + """Validate the explicit Bundle root and return the RELEASE_INFO record.""" + root = Path(root) + try: + record = stdlib_bundle.verify(root) + stdlib_bundle.require_files(record, PRODUCT_STDLIB_FILES) + if record["aliases_digest"] is None: + raise stdlib_bundle.BundleError( + f"{root / 'stdlib.json'} declares no aliases_digest" + ) + info = { + "name": record["name"], + "version": record["version"], + "tree_digest": record["tree_digest"], + "aliases_digest": record["aliases_digest"], + "file_count": record["file_count"], + "files": record["files"], + } + if pin_path is not None: + pin = stdlib_bundle.load_pin(pin_path) + stdlib_bundle.verify_pin(record, pin) + source = pin["source"] + info["source"] = { + "kind": source.get("kind"), + "repository": source.get("repository"), + "commit": source.get("commit"), + "path": source.get("path"), + } + return info + except stdlib_bundle.BundleError as error: + fail(str(error)) def host_target() -> str: @@ -206,7 +187,14 @@ def copy_tree(source: Path, destination: Path) -> None: shutil.copytree(source, destination, dirs_exist_ok=True) -def stage(stage_dir: Path, version: str, source_sha: str, target: str) -> dict: +def stage( + stage_dir: Path, + version: str, + source_sha: str, + target: str, + stdlib_dir: Path, + stdlib_info: dict, +) -> dict: stage_dir.mkdir(parents=True) release_dir = ROOT / "target" / "release" for name in BINARIES: @@ -226,7 +214,7 @@ def stage(stage_dir: Path, version: str, source_sha: str, target: str) -> dict: # The bundled stdlib is a required runtime artifact, not a build-machine # side effect: copy the verified tree next to the binary (ADR/SPEC H-08). - copy_tree(STDLIB, stage_dir / "stdlib") + copy_tree(stdlib_dir, stage_dir / "stdlib") # Examples without local build output, then the freshly built extension # artifacts so a clean install can run every example without a compiler. @@ -242,7 +230,6 @@ def stage(stage_dir: Path, version: str, source_sha: str, target: str) -> dict: shutil.copy2(limitations, stage_dir / "KNOWN_LIMITATIONS.md") commit_time = int(git("show", "-s", "--format=%ct", "HEAD")) - stdlib_info = verify_stdlib() binaries = { name: { "sha256": sha256_file(stage_dir / name), @@ -326,6 +313,8 @@ def main(argv: list[str]) -> int: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--source-sha", required=True) parser.add_argument("--version", required=True) + parser.add_argument("--stdlib-dir", required=True) + parser.add_argument("--bundle-pin", default=None) parser.add_argument("--target", default=None) parser.add_argument("--out-dir", default=str(ROOT / "dist")) parser.add_argument("--skip-example-build", action="store_true") @@ -335,6 +324,10 @@ def main(argv: list[str]) -> int: ch not in "0123456789abcdef" for ch in args.source_sha ): fail("--source-sha must be a full lowercase 40-character commit SHA") + stdlib_dir = Path(args.stdlib_dir) + stdlib_info = verify_stdlib( + stdlib_dir, Path(args.bundle_pin) if args.bundle_pin else None + ) check_clean(args.source_sha) version = workspace_version() if version != args.version: @@ -349,7 +342,7 @@ def main(argv: list[str]) -> int: out_dir.mkdir(parents=True, exist_ok=True) stage_dir = out_dir / f"marqdo-{version}-{target}" shutil.rmtree(stage_dir, ignore_errors=True) - staged = stage(stage_dir, version, args.source_sha, target) + staged = stage(stage_dir, version, args.source_sha, target, stdlib_dir, stdlib_info) archive = out_dir / f"marqdo-{version}-{target}.tar.gz" archive.unlink(missing_ok=True) make_archive(stage_dir, archive, staged["commit_time"]) -- 2.54.1 From 3a68260cf2b6f4679e8a41e34e1e329d636125d6 Mon Sep 17 00:00:00 2001 From: cflmy Date: Thu, 26 Nov 2026 15:15:59 +0800 Subject: [PATCH 4/9] tests: resolve one pinned Bundle and separate the loader lane Add crates/cli/tests/support/stdlib.rs as the product/conformance test resolver: explicit MARQDO_TEST_STDLIB_BUNDLE or the pinned path, always verified against bundle-pin.json (name/version/commit/digests), with a bad explicit override failing closed. Route stdlib_product, stdlib_bundle, http, table, alias routing, p2_closure, conformance_semantics and architecture_boundaries through it. Loader unit tests now build small synthetic Bundles; discovery is split into discover_with so the bad-override-no-fallback rule is testable. --- crates/cli/src/stdlib.rs | 105 +++--- crates/cli/tests/architecture_boundaries.rs | 16 +- crates/cli/tests/conformance_semantics.rs | 7 +- crates/cli/tests/p2_closure.rs | 10 +- crates/cli/tests/stdlib_alias_routing.rs | 14 +- crates/cli/tests/stdlib_bundle.rs | 14 +- crates/cli/tests/stdlib_http.rs | 18 +- crates/cli/tests/stdlib_product.rs | 16 +- crates/cli/tests/stdlib_table.rs | 18 +- crates/cli/tests/support/stdlib.rs | 356 ++++++++++++++++++++ 10 files changed, 467 insertions(+), 107 deletions(-) create mode 100644 crates/cli/tests/support/stdlib.rs diff --git a/crates/cli/src/stdlib.rs b/crates/cli/src/stdlib.rs index 476beca..7421398 100644 --- a/crates/cli/src/stdlib.rs +++ b/crates/cli/src/stdlib.rs @@ -51,14 +51,24 @@ impl StdlibBundle { /// machine path: the release archive must ship a verified `stdlib/` next to /// the binary (RFC-EXT-0003 H-08, ADR). pub fn discover() -> Result, String> { - if let Some(dir) = std::env::var_os(STDLIB_DIR_ENV) { - return Self::load(PathBuf::from(dir)).map(Some); + let override_dir = std::env::var_os(STDLIB_DIR_ENV).map(PathBuf::from); + let exe_dir = std::env::current_exe() + .ok() + .and_then(|exe| exe.parent().map(Path::to_path_buf)); + Self::discover_with(override_dir, exe_dir) + } + + /// Discovery with the explicit override and the executable directory passed + /// in. The override is authoritative: a bad `MARQDO_STDLIB_DIR` fails even + /// when a valid sibling Bundle exists (no silent fallback). + fn discover_with( + override_dir: Option, + exe_dir: Option, + ) -> Result, String> { + if let Some(dir) = override_dir { + return Self::load(dir).map(Some); } - Self::discover_from_exe_dir( - std::env::current_exe() - .ok() - .and_then(|exe| exe.parent().map(Path::to_path_buf)), - ) + Self::discover_from_exe_dir(exe_dir) } /// Discover from the directory that holds the executable, without the explicit @@ -454,21 +464,41 @@ pub fn aliases_digest(aliases: &[PublicAlias]) -> String { mod tests { use super::*; - fn dev_bundle() -> PathBuf { - PathBuf::from(env!("CARGO_MANIFEST_DIR")) - .join("..") - .join("..") - .join("stdlib") + /// A small synthetic Bundle so loader unit tests never depend on the + /// product tree (ADR-0070 test-lane separation). + fn write_synthetic_bundle(root: &Path) { + for (relative, body) in [ + ("io.mq.md", "## @knowledge test\n"), + ("io/console.mq.md", "## @knowledge console\n"), + ] { + let path = root.join(relative); + std::fs::create_dir_all(path.parent().unwrap()).unwrap(); + std::fs::write(path, body).unwrap(); + } + let digest = tree_digest(root).unwrap(); + let manifest = serde_json::json!({ + "name": "test-stdlib", + "version": "0.0.0-test", + "digest": digest, + }); + std::fs::write( + root.join("stdlib.json"), + serde_json::to_vec(&manifest).unwrap(), + ) + .unwrap(); } #[test] - fn dev_bundle_verifies_and_resolves() { - let bundle = StdlibBundle::load(dev_bundle()).unwrap(); - assert!(bundle.digest.starts_with("sha256:")); + fn synthetic_bundle_verifies_and_resolves() { + let dir = tempfile::tempdir().unwrap(); + write_synthetic_bundle(dir.path()); + let bundle = StdlibBundle::load(dir.path()).unwrap(); + assert_eq!(bundle.version(), "0.0.0-test"); let io = bundle.resolve("io").unwrap(); assert_eq!(io.relative_path, "io.mq.md"); - assert!(io.package.instance_id.starts_with("std:marqdo-stdlib@")); + assert!(io.package.instance_id.starts_with("std:test-stdlib@")); assert!(bundle.resolve("../escape").is_err()); + assert!(bundle.resolve("/absolute").is_err()); } #[test] @@ -476,44 +506,31 @@ mod tests { let dir = tempfile::tempdir().unwrap(); let bundle = dir.path().join("stdlib"); std::fs::create_dir_all(&bundle).unwrap(); - for entry in std::fs::read_dir(dev_bundle()).unwrap() { - let entry = entry.unwrap(); - let target = bundle.join(entry.file_name()); - if entry.path().is_dir() { - copy_dir(&entry.path(), &target); - } else { - std::fs::copy(entry.path(), target).unwrap(); - } - } + write_synthetic_bundle(&bundle); let found = StdlibBundle::discover_from_exe_dir(Some(dir.path().to_path_buf())) .unwrap() .expect("sibling stdlib"); - assert_eq!(found.root, bundle.canonicalize().unwrap()); + assert_eq!(found.root(), bundle.canonicalize().unwrap()); } - fn copy_dir(source: &std::path::Path, target: &std::path::Path) { - std::fs::create_dir_all(target).unwrap(); - for entry in std::fs::read_dir(source).unwrap() { - let entry = entry.unwrap(); - let destination = target.join(entry.file_name()); - if entry.path().is_dir() { - copy_dir(&entry.path(), &destination); - } else { - std::fs::copy(entry.path(), destination).unwrap(); - } - } + #[test] + fn bad_override_fails_closed_even_with_a_valid_sibling() { + let dir = tempfile::tempdir().unwrap(); + let sibling = dir.path().join("stdlib"); + std::fs::create_dir_all(&sibling).unwrap(); + write_synthetic_bundle(&sibling); + let error = StdlibBundle::discover_with( + Some(dir.path().join("missing")), + Some(dir.path().to_path_buf()), + ) + .unwrap_err(); + assert!(error.contains("cannot open stdlib directory"), "{error}"); } #[test] fn digest_tamper_is_rejected() { let dir = tempfile::tempdir().unwrap(); - let source = dev_bundle(); - for entry in std::fs::read_dir(&source).unwrap() { - let entry = entry.unwrap(); - if entry.path().is_file() { - std::fs::copy(entry.path(), dir.path().join(entry.file_name())).unwrap(); - } - } + write_synthetic_bundle(dir.path()); std::fs::write(dir.path().join("io.mq.md"), "## @knowledge tampered\n").unwrap(); let error = StdlibBundle::load(dir.path()).unwrap_err(); assert!(error.contains("digest mismatch"), "{error}"); diff --git a/crates/cli/tests/architecture_boundaries.rs b/crates/cli/tests/architecture_boundaries.rs index 45061d6..ed33384 100644 --- a/crates/cli/tests/architecture_boundaries.rs +++ b/crates/cli/tests/architecture_boundaries.rs @@ -6,6 +6,9 @@ //! stdio/file/TCP resource endpoints. They are source and digest checks, not an //! OS-sandbox proof. +#[path = "support/stdlib.rs"] +pub mod stdlib_support; + use std::path::{Path, PathBuf}; use sha2::{Digest, Sha256}; @@ -88,7 +91,14 @@ fn runtime_depends_on_the_host_platform_layer_without_a_cycle() { #[test] fn bundled_stdlib_stays_in_this_repository_and_matches_its_digest() { - let root = repo_root().join("stdlib"); + let root = stdlib_support::bundle_dir(); + // Phase A (ADR-0070): the pinned Bundle is still the checkout tree. Phase B + // replaces this assertion when the ecosystem Bundle becomes the input. + assert_eq!( + root, + repo_root().join("stdlib").canonicalize().unwrap(), + "the Phase A stdlib pin must resolve to the in-repo stdlib tree" + ); let manifest: serde_json::Value = serde_json::from_slice(&std::fs::read(root.join("stdlib.json")).unwrap()).unwrap(); assert_eq!(manifest["name"], "marqdo-stdlib"); @@ -103,7 +113,7 @@ fn bundled_stdlib_stays_in_this_repository_and_matches_its_digest() { #[test] fn stdlib_imports_resolve_inside_the_bundle() { - let root = repo_root().join("stdlib"); + let root = stdlib_support::bundle_dir(); for entry in walk_markdown(&root) { let is_test = entry.starts_with(root.join("tests")); let text = read(&entry); @@ -439,7 +449,7 @@ const _: fn(marqdo_value::Value) = |value| match value { /// hard-coded runtime names. Recompute the canonical metadata digest. #[test] fn official_stdlib_public_aliases_are_verified_metadata() { - let root = repo_root().join("stdlib"); + let root = stdlib_support::bundle_dir(); let manifest: serde_json::Value = serde_json::from_slice(&std::fs::read(root.join("stdlib.json")).unwrap()).unwrap(); let aliases = manifest["public_aliases"] diff --git a/crates/cli/tests/conformance_semantics.rs b/crates/cli/tests/conformance_semantics.rs index 6ef7a19..0bcffc5 100644 --- a/crates/cli/tests/conformance_semantics.rs +++ b/crates/cli/tests/conformance_semantics.rs @@ -20,6 +20,9 @@ //! expectation; the checked-in goldens were reviewed individually. use std::fs; +#[path = "support/stdlib.rs"] +pub mod stdlib_support; + use std::path::{Path, PathBuf}; use marqdo_host::{Capabilities, Host, StdHost}; @@ -291,7 +294,7 @@ fn normalise_relative(path: &Path) -> String { /// unique registry, run the single binding pass and install its table. There is /// no `print_override` and no runtime name guessing. fn bind_calls_with_stdlib_aliases(program: &mut Program) { - let root = repo_root().join("stdlib"); + let root = stdlib_support::bundle_dir(); let mut loaded = std::collections::BTreeSet::new(); let mut official = Vec::new(); if root.join("stdlib.json").is_file() { @@ -428,7 +431,7 @@ fn install_entry_stdlib_imports( module_id: &ModuleId, analysis: &marqdo_frontend::AnalysisResult, ) { - let root = repo_root().join("stdlib"); + let root = stdlib_support::bundle_dir(); let Some(imports) = analysis .document .frontmatter() diff --git a/crates/cli/tests/p2_closure.rs b/crates/cli/tests/p2_closure.rs index 12be670..a7014d3 100644 --- a/crates/cli/tests/p2_closure.rs +++ b/crates/cli/tests/p2_closure.rs @@ -3,6 +3,9 @@ #[path = "support/observation.rs"] pub mod observation; +#[path = "support/stdlib.rs"] +pub mod stdlib_support; + use std::path::{Path, PathBuf}; use std::process::Command; @@ -109,7 +112,8 @@ fn p2_algorithms_run_in_a_pure_no_foreign_no_plugin_host() { #[test] fn p2_stdlib_table_also_runs_in_pure_mode() { - let path = repo_root().join("stdlib").join("tests").join("table.mq.md"); + let bundle = stdlib_support::bundle_dir(); + let path = bundle.join("tests").join("table.mq.md"); let output = Command::new(env!("CARGO_BIN_EXE_marqdo")) .args([ "run", @@ -119,8 +123,8 @@ fn p2_stdlib_table_also_runs_in_pure_mode() { "--output", "json", ]) - .current_dir(repo_root().join("stdlib")) - .env("MARQDO_STDLIB_DIR", repo_root().join("stdlib")) + .current_dir(&bundle) + .env("MARQDO_STDLIB_DIR", &bundle) .output() .expect("run table self-test"); assert_eq!( diff --git a/crates/cli/tests/stdlib_alias_routing.rs b/crates/cli/tests/stdlib_alias_routing.rs index 5747ec5..3493948 100644 --- a/crates/cli/tests/stdlib_alias_routing.rs +++ b/crates/cli/tests/stdlib_alias_routing.rs @@ -5,6 +5,9 @@ //! runtime name special case and no hard-coded per-function scan. #![cfg(unix)] +#[path = "support/stdlib.rs"] +pub mod stdlib_support; + use std::path::{Path, PathBuf}; use std::process::{Command, Output}; use std::sync::atomic::{AtomicU32, Ordering}; @@ -35,15 +38,6 @@ impl Drop for TempDir { } } -fn repo() -> PathBuf { - Path::new(env!("CARGO_MANIFEST_DIR")) - .parent() - .unwrap() - .parent() - .unwrap() - .to_path_buf() -} - fn cli(args: &[&str], dir: &Path, env: &[(&str, &Path)]) -> Output { let mut command = Command::new(env!("CARGO_BIN_EXE_marqdo")); command.args(args).current_dir(dir); @@ -62,7 +56,7 @@ fn stdout(output: &Output) -> String { } fn copy_stdlib(target: &Path) { - let source = repo().join("stdlib"); + let source = stdlib_support::bundle_dir(); std::fs::create_dir_all(target).unwrap(); for entry in std::fs::read_dir(&source).unwrap() { let entry = entry.unwrap(); diff --git a/crates/cli/tests/stdlib_bundle.rs b/crates/cli/tests/stdlib_bundle.rs index 65f2bc9..f95ea04 100644 --- a/crates/cli/tests/stdlib_bundle.rs +++ b/crates/cli/tests/stdlib_bundle.rs @@ -1,23 +1,17 @@ //! Bundled stdlib (`std:`) and frozen-CLI closure tests (CM-A10). +#[path = "support/stdlib.rs"] +pub mod stdlib_support; + use std::path::{Path, PathBuf}; use std::process::Command; -fn repo_root() -> PathBuf { - Path::new(env!("CARGO_MANIFEST_DIR")) - .parent() - .unwrap() - .parent() - .unwrap() - .to_path_buf() -} - fn binary() -> &'static str { env!("CARGO_BIN_EXE_marqdo") } fn stdlib_dir() -> PathBuf { - repo_root().join("stdlib") + stdlib_support::bundle_dir() } fn run(dir: &Path, stdlib: &Path, args: &[&str]) -> std::process::Output { diff --git a/crates/cli/tests/stdlib_http.rs b/crates/cli/tests/stdlib_http.rs index 570400b..cddcf97 100644 --- a/crates/cli/tests/stdlib_http.rs +++ b/crates/cli/tests/stdlib_http.rs @@ -3,24 +3,18 @@ #[path = "support/observation.rs"] pub mod observation; -use std::path::Path; -use std::process::Command; +#[path = "support/stdlib.rs"] +pub mod stdlib_support; -fn repo_root() -> std::path::PathBuf { - Path::new(env!("CARGO_MANIFEST_DIR")) - .parent() - .unwrap() - .parent() - .unwrap() - .to_path_buf() -} +use std::process::Command; #[test] fn stdlib_http_parses_chunked_responses_and_builds_requests() { + let bundle = stdlib_support::bundle_dir(); let output = Command::new(env!("CARGO_BIN_EXE_marqdo")) .args(["run", "tests/http.mq.md", "--output", "json"]) - .current_dir(repo_root().join("stdlib")) - .env("MARQDO_STDLIB_DIR", repo_root().join("stdlib")) + .current_dir(&bundle) + .env("MARQDO_STDLIB_DIR", &bundle) .output() .expect("run http self-test"); assert_eq!( diff --git a/crates/cli/tests/stdlib_product.rs b/crates/cli/tests/stdlib_product.rs index 6b64505..fc3a2e4 100644 --- a/crates/cli/tests/stdlib_product.rs +++ b/crates/cli/tests/stdlib_product.rs @@ -8,20 +8,14 @@ #[path = "support/observation.rs"] pub mod observation; +#[path = "support/stdlib.rs"] +pub mod stdlib_support; + use std::io::Write; -use std::path::{Path, PathBuf}; +use std::path::PathBuf; use std::process::{Command, Stdio}; use std::sync::{Mutex, MutexGuard}; -fn repo_root() -> PathBuf { - Path::new(env!("CARGO_MANIFEST_DIR")) - .parent() - .unwrap() - .parent() - .unwrap() - .to_path_buf() -} - static FS_LOCK: Mutex<()> = Mutex::new(()); fn lock_fs(name: &str) -> Option> { @@ -33,7 +27,7 @@ fn lock_fs(name: &str) -> Option> { } fn stdlib_dir() -> PathBuf { - repo_root().join("stdlib") + stdlib_support::bundle_dir() } struct TestFile { diff --git a/crates/cli/tests/stdlib_table.rs b/crates/cli/tests/stdlib_table.rs index a1ca0a1..2603c01 100644 --- a/crates/cli/tests/stdlib_table.rs +++ b/crates/cli/tests/stdlib_table.rs @@ -3,23 +3,17 @@ #[path = "support/observation.rs"] pub mod observation; -use std::path::Path; +#[path = "support/stdlib.rs"] +pub mod stdlib_support; + use std::process::Command; -fn repo_root() -> std::path::PathBuf { - Path::new(env!("CARGO_MANIFEST_DIR")) - .parent() - .unwrap() - .parent() - .unwrap() - .to_path_buf() -} - fn run_table_self_test() -> serde_json::Value { + let bundle = stdlib_support::bundle_dir(); let output = Command::new(env!("CARGO_BIN_EXE_marqdo")) .args(["run", "tests/table.mq.md", "--output", "json"]) - .current_dir(repo_root().join("stdlib")) - .env("MARQDO_STDLIB_DIR", repo_root().join("stdlib")) + .current_dir(&bundle) + .env("MARQDO_STDLIB_DIR", &bundle) .output() .expect("run table self-test"); assert_eq!( diff --git a/crates/cli/tests/support/stdlib.rs b/crates/cli/tests/support/stdlib.rs new file mode 100644 index 0000000..0782a08 --- /dev/null +++ b/crates/cli/tests/support/stdlib.rs @@ -0,0 +1,356 @@ +//! Pinned stdlib Bundle resolver shared by test harnesses (ADR-0070). +//! +//! Product tests consume one explicit Bundle whose identity is pinned in +//! `tools/stdlib/bundle-pin.json` (name, version, source commit, tree digest and +//! alias digest). `MARQDO_TEST_STDLIB_BUNDLE` may change the location, but the +//! Bundle must still match the pin; `MARQDO_TEST_BUNDLE_PIN` may change the pin +//! file. A bad explicit input fails even when the default location is valid — +//! there is no silent fallback. + +use std::path::{Component, Path, PathBuf}; + +use sha2::{Digest, Sha256}; + +pub const BUNDLE_ENV: &str = "MARQDO_TEST_STDLIB_BUNDLE"; +pub const PIN_ENV: &str = "MARQDO_TEST_BUNDLE_PIN"; + +/// The checkout root (this test support module lives in `crates/cli/tests`). +pub fn repo_root() -> PathBuf { + Path::new(env!("CARGO_MANIFEST_DIR")) + .parent() + .expect("crates directory") + .parent() + .expect("repository root") + .to_path_buf() +} + +/// Pin file path, overridable for a candidate Bundle. +pub fn pin_path() -> PathBuf { + std::env::var_os(PIN_ENV) + .map(PathBuf::from) + .unwrap_or_else(|| { + repo_root() + .join("tools") + .join("stdlib") + .join("bundle-pin.json") + }) +} + +/// One pinned Bundle identity (`tools/stdlib/bundle-pin.json`). +#[derive(Debug, Clone)] +pub struct BundlePin { + pub name: String, + pub version: String, + pub source_commit: String, + pub source_path: PathBuf, + pub tree_digest: String, + pub aliases_digest: String, +} + +impl BundlePin { + pub fn load(path: &Path) -> Self { + let text = std::fs::read_to_string(path) + .unwrap_or_else(|error| panic!("cannot read Bundle pin {}: {error}", path.display())); + let value: serde_json::Value = serde_json::from_str(&text) + .unwrap_or_else(|error| panic!("invalid Bundle pin {}: {error}", path.display())); + assert_eq!( + value.get("schema").and_then(serde_json::Value::as_str), + Some("marqdo.stdlib-bundle-pin"), + "{} must use the marqdo.stdlib-bundle-pin schema", + path.display() + ); + assert_eq!( + value + .get("schema_version") + .and_then(serde_json::Value::as_u64), + Some(1), + "{} must use pin schema_version 1", + path.display() + ); + let source = value + .get("source") + .unwrap_or_else(|| panic!("Bundle pin {} has no source object", path.display())); + let source_path = source + .get("path") + .and_then(serde_json::Value::as_str) + .unwrap_or_else(|| panic!("Bundle pin {} has no source.path", path.display())); + validate_relative(source_path) + .unwrap_or_else(|error| panic!("Bundle pin {} source.path: {error}", path.display())); + Self { + name: required_str(&value, "name", path), + version: required_str(&value, "version", path), + source_commit: required_str(source, "commit", path), + source_path: PathBuf::from(source_path), + tree_digest: required_str(&value, "tree_digest", path), + aliases_digest: required_str(&value, "aliases_digest", path), + } + } + + /// The committed pin for the current checkout. + pub fn committed() -> Self { + Self::load(&pin_path()) + } +} + +fn required_str(value: &serde_json::Value, field: &str, path: &Path) -> String { + value + .get(field) + .and_then(serde_json::Value::as_str) + .filter(|text| !text.is_empty()) + .unwrap_or_else(|| panic!("Bundle pin {} has no `{field}`", path.display())) + .to_string() +} + +/// One verified Bundle on disk. +#[derive(Debug, Clone)] +pub struct Bundle { + root: PathBuf, + pub name: String, + pub version: String, + pub tree_digest: String, + pub aliases_digest: String, +} + +impl Bundle { + /// Resolve the Bundle for a product test: explicit override or pinned path, + /// verified against the pin. + pub fn pinned() -> Self { + let pin = BundlePin::committed(); + let explicit = std::env::var_os(BUNDLE_ENV).map(PathBuf::from); + let root = explicit + .clone() + .unwrap_or_else(|| repo_root().join(&pin.source_path)); + let bundle = Self::verify(&root).unwrap_or_else(|error| match &explicit { + Some(_) => panic!( + "{BUNDLE_ENV} does not name a valid stdlib Bundle at {}: {error}", + root.display() + ), + None => panic!( + "pinned stdlib Bundle at {} is invalid: {error}", + root.display() + ), + }); + let mismatches = [ + ("name", &pin.name, &bundle.name), + ("version", &pin.version, &bundle.version), + ("tree_digest", &pin.tree_digest, &bundle.tree_digest), + ( + "aliases_digest", + &pin.aliases_digest, + &bundle.aliases_digest, + ), + ]; + for (field, expected, actual) in mismatches { + assert_eq!( + expected, + actual, + "stdlib Bundle at {} does not match the pin field `{field}`", + root.display() + ); + } + for required in ["stdlib.json", "io.mq.md", "io/console.mq.md"] { + assert!( + bundle.root.join(required).is_file(), + "stdlib Bundle at {} is missing required file {required}", + bundle.root.display() + ); + } + assert_eq!( + pin.source_commit.len(), + 40, + "the pin must record a full source commit, got {:?}", + pin.source_commit + ); + bundle + } + + /// Verify one unpacked Bundle root. + pub fn verify(root: &Path) -> Result { + if !root.is_dir() { + return Err(format!("not a directory: {}", root.display())); + } + let manifest_path = root.join("stdlib.json"); + if !manifest_path.is_file() { + return Err(format!("missing manifest: {}", manifest_path.display())); + } + let text = std::fs::read_to_string(&manifest_path) + .map_err(|error| format!("cannot read {}: {error}", manifest_path.display()))?; + let manifest: serde_json::Value = serde_json::from_str(&text) + .map_err(|error| format!("invalid {}: {error}", manifest_path.display()))?; + let name = manifest + .get("name") + .and_then(serde_json::Value::as_str) + .ok_or_else(|| format!("{} has no name", manifest_path.display()))? + .to_string(); + let version = manifest + .get("version") + .and_then(serde_json::Value::as_str) + .ok_or_else(|| format!("{} has no version", manifest_path.display()))? + .to_string(); + let declared = manifest + .get("digest") + .and_then(serde_json::Value::as_str) + .ok_or_else(|| format!("{} has no digest", manifest_path.display()))? + .to_string(); + let actual = tree_digest(root)?; + if declared != actual { + return Err(format!( + "tree digest mismatch: stdlib.json declares {declared}, the files are {actual}" + )); + } + let aliases = manifest + .get("public_aliases") + .and_then(serde_json::Value::as_array) + .cloned() + .unwrap_or_default(); + let declared_aliases = manifest + .get("aliases_digest") + .and_then(serde_json::Value::as_str) + .map(ToString::to_string); + let actual_aliases = aliases_digest(&aliases); + match (declared_aliases, aliases.is_empty()) { + (Some(declared_aliases), _) => { + if declared_aliases != actual_aliases { + return Err(format!( + "alias digest mismatch: stdlib.json declares {declared_aliases}, \ + the alias table is {actual_aliases}" + )); + } + } + (None, false) => { + return Err(format!( + "{} declares public_aliases without aliases_digest", + manifest_path.display() + )); + } + (None, true) => {} + } + Ok(Self { + root: root + .canonicalize() + .map_err(|error| format!("cannot canonicalize {}: {error}", root.display()))?, + name, + version, + tree_digest: actual, + aliases_digest: actual_aliases, + }) + } + + pub fn root(&self) -> &Path { + &self.root + } +} + +/// Resolve and verify the pinned Bundle once per test process. +pub fn bundle() -> &'static Bundle { + static BUNDLE: std::sync::OnceLock = std::sync::OnceLock::new(); + BUNDLE.get_or_init(Bundle::pinned) +} + +/// Bundle root for fixtures and `MARQDO_STDLIB_DIR`. +pub fn bundle_dir() -> PathBuf { + bundle().root().to_path_buf() +} + +/// Content digest over all `.mq.md` files: sorted relative path, NUL, bytes, NUL. +pub fn tree_digest(root: &Path) -> Result { + let mut files = Vec::new(); + collect_markdown(root, root, &mut files)?; + files.sort(); + let mut hasher = Sha256::new(); + for (relative, path) in files { + let bytes = std::fs::read(&path) + .map_err(|error| format!("cannot read {}: {error}", path.display()))?; + hasher.update(relative.as_bytes()); + hasher.update([0]); + hasher.update(&bytes); + hasher.update([0]); + } + Ok(format!("sha256:{}", hex(&hasher.finalize()))) +} + +/// Canonical digest over the official public-alias table. +pub fn aliases_digest(aliases: &[serde_json::Value]) -> String { + let mut entries: Vec<&serde_json::Value> = aliases.iter().collect(); + entries.sort_by_key(|alias| { + ( + alias["target_module"].as_str().unwrap_or("").to_string(), + alias["target_function"].as_str().unwrap_or("").to_string(), + ) + }); + let mut hasher = Sha256::new(); + for alias in entries { + if let Some(module) = alias["target_module"].as_str() { + hasher.update(module.as_bytes()); + } + hasher.update([0]); + if let Some(function) = alias["target_function"].as_str() { + hasher.update(function.as_bytes()); + } + hasher.update([0]); + let mut names: Vec<&str> = alias["public_names"] + .as_array() + .map(|names| names.iter().filter_map(serde_json::Value::as_str).collect()) + .unwrap_or_default(); + names.sort(); + for name in names { + hasher.update(name.as_bytes()); + hasher.update([0]); + } + } + format!("sha256:{}", hex(&hasher.finalize())) +} + +fn collect_markdown( + root: &Path, + dir: &Path, + out: &mut Vec<(String, PathBuf)>, +) -> Result<(), String> { + let entries = std::fs::read_dir(dir) + .map_err(|error| format!("cannot read {}: {error}", dir.display()))?; + for entry in entries { + let entry = entry.map_err(|error| format!("cannot read {}: {error}", dir.display()))?; + let path = entry.path(); + if path.is_dir() { + collect_markdown(root, &path, out)?; + } else if path + .file_name() + .is_some_and(|name| name.to_string_lossy().ends_with(".mq.md")) + { + let relative = path + .strip_prefix(root) + .map_err(|_| "stdlib file escaped its root".to_string())? + .components() + .map(|component| component.as_os_str().to_string_lossy().to_string()) + .collect::>() + .join("/"); + out.push((relative, path)); + } + } + Ok(()) +} + +fn validate_relative(path: &str) -> Result<(), String> { + let mut normalised = PathBuf::new(); + for component in Path::new(path).components() { + match component { + Component::Normal(part) => normalised.push(part), + Component::CurDir => {} + Component::ParentDir | Component::RootDir | Component::Prefix(_) => { + return Err("must be a relative path inside the repository".to_string()) + } + } + } + if normalised.as_os_str().is_empty() { + return Err("must not be empty".to_string()); + } + Ok(()) +} + +fn hex(bytes: &[u8]) -> String { + let mut out = String::with_capacity(bytes.len() * 2); + for byte in bytes { + out.push_str(&format!("{byte:02x}")); + } + out +} -- 2.54.1 From ab6b6b1a23ec064fbc7de943c52befca18142a56 Mon Sep 17 00:00:00 2001 From: cflmy Date: Thu, 26 Nov 2026 15:25:40 +0800 Subject: [PATCH 5/9] ci: add the independent-build lane and pin the perf Bundle Add tools/ci/independent_build.py: export HEAD without stdlib/, build both shipped binaries with --locked, run a language-only check/call, and require a stdlib-dependent run to fail closed with no sibling stdlib. Add tests/independent/language-only.mq.md and run the lane as its own GitHub job and Woodpecker step. Perf runner resolves the pinned Bundle (--stdlib-dir/--bundle-pin), exports it to every workload and records it in the report; GitHub and Woodpecker lanes verify the pin and pass the product tests an explicit Bundle. docs/ci.md and performance docs describe the lanes. --- .github/workflows/ci.yml | 23 ++- .woodpecker/main.yml | 11 +- .woodpecker/performance.yml | 4 +- docs/ci.md | 21 ++- docs/performance.md | 9 +- tests/independent/language-only.mq.md | 12 ++ tools/ci/independent_build.py | 217 ++++++++++++++++++++++++++ tools/perf/README.md | 5 + tools/perf/runner.py | 27 +++- 9 files changed, 316 insertions(+), 13 deletions(-) create mode 100644 tests/independent/language-only.mq.md create mode 100644 tools/ci/independent_build.py 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": { -- 2.54.1 From 0e1efc713e16eeaaceb7dc369f58c3f587f4837d Mon Sep 17 00:00:00 2001 From: cflmy Date: Thu, 26 Nov 2026 15:51:39 +0800 Subject: [PATCH 6/9] smoke: keep language-only execution after removing the Bundle Moving the shipped stdlib aside must fail the print program with an explicit diagnostic and still run a language-only program. The archive smoke and the cold-install container now both call the factorial example after the move, and the archive contract test pins the new message. --- tools/ci/test_release_archive.py | 1 + tools/release/cold-install.sh | 1 + tools/release/smoke.py | 10 ++++++++++ 3 files changed, 12 insertions(+) diff --git a/tools/ci/test_release_archive.py b/tools/ci/test_release_archive.py index ae8c430..c41bb9c 100644 --- a/tools/ci/test_release_archive.py +++ b/tools/ci/test_release_archive.py @@ -134,6 +134,7 @@ class ReleaseArchiveContractTest(unittest.TestCase): self.assertIn("verify_stdlib_bundle(install, info)", source) self.assertIn("verify_stdlib_bundle", source) self.assertIn("stdlib.hidden", source) + self.assertIn("language-only program runs without the bundled stdlib", source) self.assertIn("expected 6", source) self.assertIn("permission.denied", source) diff --git a/tools/release/cold-install.sh b/tools/release/cold-install.sh index 8f2e03c..30c1827 100644 --- a/tools/release/cold-install.sh +++ b/tools/release/cold-install.sh @@ -51,4 +51,5 @@ docker run --rm --network none --user 65534:65534 \ exit 1 fi grep -E "stdlib|symbol\.unknown|打印" /tmp/missing-stdlib.log + test "$(./marqdo call examples/factorial.mq.md 阶乘 --arg n=5)" = 120 ' sh "$version" "$source_sha" diff --git a/tools/release/smoke.py b/tools/release/smoke.py index 912c54d..dc59ae2 100644 --- a/tools/release/smoke.py +++ b/tools/release/smoke.py @@ -281,6 +281,16 @@ def main(argv: list[str]) -> int: if "stdlib" not in message and "打印" not in message and "symbol.unknown" not in message: fail(f"missing-stdlib failure is not explicit: {message!r}") print("smoke: bundled stdlib missing -> fail-closed OK") + # A program that uses only the language must still run. + language_only = runner.run( + ["call", "examples/factorial.mq.md", "阶乘", "--arg", "n=5"] + ).stdout.strip() + if language_only != "120": + fail( + f"language-only call failed without the bundled stdlib: " + f"{language_only!r}" + ) + print("smoke: language-only program runs without the bundled stdlib") finally: hidden.rename(install / "stdlib") factor = runner.run( -- 2.54.1 From 88ce91a9e1ce133dc6cf932e5379846a3713eaee Mon Sep 17 00:00:00 2001 From: cflmy Date: Thu, 26 Nov 2026 15:52:04 +0800 Subject: [PATCH 7/9] docs: record the issue #11 Phase A state and evidence Update STATUS, the architecture overview, README and tests/README with the explicit Bundle input, pinned test/perf lanes and the independent build. Add the Phase A evidence record: bundle identity, failure paths, deterministic pack/package digests, independent build, archive smoke, cold install and the 634-passed workspace gate. Phase B remains explicitly unclaimed. --- README.md | 15 ++ docs/STATUS.md | 55 +++++- docs/architecture/CURRENT.md | 9 +- docs/evidence/2026-11-26-issue-11-phase-a.md | 190 +++++++++++++++++++ tests/README.md | 18 ++ 5 files changed, 280 insertions(+), 7 deletions(-) create mode 100644 docs/evidence/2026-11-26-issue-11-phase-a.md diff --git a/README.md b/README.md index c0c36f1..e628e0f 100644 --- a/README.md +++ b/README.md @@ -63,6 +63,21 @@ cargo build -p marqdo-cli # binary: target/debug/marqdo (or $CARGO_TARGET_DIR/debug/marqdo) ``` +The CLI and Provider Worker compile without the stdlib sources. A release is +assembled from one explicit, verified Bundle (ADR-0070); the debug CLI still +discovers the checkout's `stdlib/` for the development loop, and +`MARQDO_STDLIB_DIR` is the explicit runtime override: + +```bash +cargo build --release --locked -p marqdo-cli -p marqdo-provider-worker +python3 tools/stdlib/bundle.py --print-path +python3 tools/release/package.py --source-sha "$(git rev-parse HEAD)" \ + --version --stdlib-dir stdlib \ + --bundle-pin tools/stdlib/bundle-pin.json +``` + +See [`docs/releasing.md`](docs/releasing.md) for the full procedure. + ## Quickstart ```bash diff --git a/docs/STATUS.md b/docs/STATUS.md index edd5a26..d6b14a8 100644 --- a/docs/STATUS.md +++ b/docs/STATUS.md @@ -75,6 +75,47 @@ The `spec/` tree contains only current contracts; retired specifications are in Git history and tagged archives. The earlier release records below describe their tagged binaries and are not current protocol claims. +## 0.11 Explicit stdlib Bundle input — issue #11 Phase A (unreleased) + +Phase A lands the build-input boundary only: the stdlib production sources and +the debug source fallback are still in this repository, and Phase B (the +ecosystem-assembled Bundle, source removal and `std:` replacement) is **not** +claimed. Executed candidate: +`ab6b6b1a23ec064fbc7de943c52befca18142a56`; bundle source commit +`2cbde54602c07f62a62f341400bc9cb4764a93f8`. + +* `tools/stdlib/bundle-pin.json` pins `marqdo-stdlib@0.1.0` with tree digest + `sha256:5407d3665ba2fe105820d0f1af5efaafa10c277a69eb819c3225719813c8c713` + and alias digest + `sha256:5f513c0fdbb3c1e9829be3c9fa23a2d1e89cb8510073fb5eb1e8e2f5265a83bb`; + `tools/stdlib/bundle.py` is the single resolver/verifier. +* `tools/pack-stdlib.py` and `tools/release/package.py` require + `--stdlib-dir` and accept `--bundle-pin`. A missing directory, missing + manifest, tree/alias digest mismatch, pin mismatch or symlink fails before + an archive is written; `RELEASE_INFO.json.stdlib.source` records the pinned + kind/repository/commit/path. +* Product, performance and release lanes resolve that Bundle + (`crates/cli/tests/support/stdlib.rs`, `tools/perf/runner.py`). An explicit + `MARQDO_TEST_STDLIB_BUNDLE`/`--stdlib-dir` changes the location but must match + the pin; a bad override fails even when the default is valid. Loader unit + tests build small synthetic Bundles. +* `tools/ci/independent_build.py` exports a clean copy without `stdlib/`, + builds `marqdo-cli` + `marqdo-provider-worker` with `--locked`, runs the + language-only `tests/independent/language-only.mq.md`, and requires a + stdlib-dependent run to fail closed with no sibling `stdlib/`. GitHub and + Woodpecker run the lane. +* Archive smoke and cold-install keep the missing-Bundle failure and now also + require the language-only `factorial` call to succeed after the shipped + `stdlib/` is moved aside. Two packaging runs from the same input and + toolchain are byte-identical. + +Evidence: +[`evidence/2026-11-26-issue-11-phase-a.md`](evidence/2026-11-26-issue-11-phase-a.md). +Runtime discovery is unchanged: `MARQDO_STDLIB_DIR` (invalid values still fail +hard), then `stdlib/` next to the executable, then the debug-only source +fallback. Phase B is gated on ecosystem issue #2 and the extension replacement +evidence named by issue #11. + ## 0.10 Closed public Analysis boundary — issue #10 (RC.4 released) The candidate replaces the program-only Analysis projection in place under @@ -356,6 +397,9 @@ ownership / core resource kinds), ADR-0063 (foreign F-A). Executed evidence: recompute both digests with the runtime algorithm and fail on mismatch; smoke removes the bundle and requires a fail-closed run (no source fallback). Release discovery only falls back to the compile-time source tree in debug builds. + Since issue #11 Phase A the Bundle is one required explicit build input + (`--stdlib-dir`) with a pinned identity and a recorded source commit + (ADR-0070); see §0.11. - **H-04 core resource kinds:** `marqdo_host::CORE_RESOURCE_KINDS` is the single registry used by the CLI manifest validator and every trusted host registration path; all six core kinds are rejected as a provider name and as a declared kind @@ -683,9 +727,11 @@ This is still a **local VM lane**, not a self-hosted GitHub Actions security URL routed to the bundled stdlib (Compat-C, ADR-0030/0031); there is no legacy host formatter. `tools/pack-stdlib.py` additionally emits a byte-deterministic offline archive + descriptor as an extraction-ready artifact - ([evidence](evidence/2026-11-20-stdlib-package.md)). The stdlib intentionally - stays in this repository for now (ADR-0039); extraction is a future option - when size/release cadence requires it, not a pending gate. + ([evidence](evidence/2026-11-20-stdlib-package.md)). Issue #11 Phase A now + consumes the Bundle through one explicit `--stdlib-dir` and one pinned + identity (ADR-0070, §0.11); the production sources still stay in this + repository until Phase B, which is gated on ecosystem issue #2 and the + extension replacement evidence. - Resource streams (RFC-CM CM-A06, ADR-0025/0026/0040): opaque host-issued `Resource` handles with `resource.open/read/write/close`; bytes move only through `Memory`; stdin is read-only over one shared run cursor; stdout and @@ -703,7 +749,8 @@ This is still a **local VM lane**, not a self-hosted GitHub Actions security URL pins the workspace graph, `marqdo-runtime -> marqdo-host`, the bundled stdlib digest and the stdio/file/TCP endpoints; `crates/cli/tests/stdlib_product.rs` runs every public stdlib module (`clock/compress/console/csv/datetime/demo/env/format/fs/http/io/json/path/process/random/regex/stream/table/text/utf8`) - through `std:` imports over `stdlib/tests/*.mq.md`. `tools/pack-stdlib.py` + through `std:` imports over `stdlib/tests/*.mq.md` resolved from the pinned + Bundle (`crates/cli/tests/support/stdlib.rs`). `tools/pack-stdlib.py` now sorts `.mq.md` by the same relative path key as the CLI. Source/test baseline `0d40de7`; later docs-only commits keep code/test bytes identical. Evidence: [`docs-and-test-migration`](evidence/2026-11-21-docs-and-test-migration.md). diff --git a/docs/architecture/CURRENT.md b/docs/architecture/CURRENT.md index 88df4a6..aca640c 100644 --- a/docs/architecture/CURRENT.md +++ b/docs/architecture/CURRENT.md @@ -140,8 +140,11 @@ Layer rules: or a third-party plugin path. 2. The platform layer owns I/O, clocks, entropy, sockets and file handles. It must not own JSON parsing, text formatting or memory allocation policy. -3. The stdlib is `.mq.md` and ships in this repository. New ordinary algorithms - go to `stdlib/` + tests + docs; they do not become Rust builtins. +3. The stdlib is `.mq.md` and ships in this repository during Phase A of + issue #11. New ordinary algorithms go to `stdlib/` + tests + docs; they do + not become Rust builtins. Packaging and product tests take it as one + explicit, pinned Bundle input (ADR-0070); Phase B moves the production + sources to the ecosystem assembly after issue #2 acceptance. 4. The CLI selects inputs, resolves configuration, assembles the host and routes human/machine output. It is not a semantic policy centre. 5. Callable Plugin and Resource Provider share one registry/authorization/audit @@ -229,7 +232,7 @@ that a phase is complete. | Priority | Gap | State | |---|---|---| | P0 | **Language syntax migration**: RFC-LANG-0002 single contract | **closed at `9c1723d`**; implementation, stdlib digest, examples and fixtures green; platform/strict evidence remains separate | -| P0 | Stdlib release is a bundle in this repo; extraction is deferred (ADR-0039) | accepted, keep in repo | +| P0 | Stdlib extraction (issue #11): explicit `--stdlib-dir` + one pinned Bundle for tests/perf/release CI | **Phase A implemented** (ADR-0070); Phase B (ecosystem assembly, source removal) waits on ecosystem issue #2 and the extension replacement evidence | | P0 | Documentation drift between `STATUS.md`, the architecture index and the evidence | being fixed by this migration and the docs gate | | P1 | `std:fs/file` read/write/copy, metadata/directory, append/read_at/walk are implemented; watch and binary offset reads remain open | open | | P1 | No file watch or binary `read_at` | open; future Resource Operation extension | diff --git a/docs/evidence/2026-11-26-issue-11-phase-a.md b/docs/evidence/2026-11-26-issue-11-phase-a.md new file mode 100644 index 0000000..afbc678 --- /dev/null +++ b/docs/evidence/2026-11-26-issue-11-phase-a.md @@ -0,0 +1,190 @@ +# Issue #11 Phase A — one explicit stdlib Bundle input + +Date: 2026-11-26. +Implementation baseline: `4bbefc92449ee480c8a2c89b0308feb4cda8d0e7`. +Bundle source commit: `2cbde54602c07f62a62f341400bc9cb4764a93f8`. +Decision: [ADR-0070](../adr/0070-explicit-stdlib-bundle-build-input.md). +Inventory: +[`2026-11-26-stdlib-source-coupling-inventory.md`](2026-11-26-stdlib-source-coupling-inventory.md). + +Candidate commits (in order): + +| Commit | Change | +|---|---| +| `b9c72e1` | ADR-0070 + source-coupling inventory | +| `1b9d9c4` | `tools/stdlib/bundle.py`, `bundle-pin.json`, required `pack-stdlib.py --stdlib-dir` | +| `422b9de` | `package.py --stdlib-dir/--bundle-pin`, `RELEASE_INFO.stdlib.source` | +| `3a68260` | pinned test resolver, synthetic loader tests, product/conformance rewiring | +| `ab6b6b1` | independent-build lane, perf Bundle pin, CI and docs | +| this docs commit | STATUS/README/tests/CURRENT + this evidence | + +Executed host: Linux x86_64 (glibc 2.43), `rustc 1.100.0 (0ef1bc386 +2026-11-09)`, `cargo 1.100.0 (3acc79c0c 2026-11-05)`, Python 3.14.4; the +cold-install container is `ubuntu:24.04` (glibc 2.39) with `--network none`. + +## 1. Pinned Bundle identity + +```console +$ python3 tools/stdlib/bundle.py +{ + "aliases_digest": "sha256:5f513c0fdbb3c1e9829be3c9fa23a2d1e89cb8510073fb5eb1e8e2f5265a83bb", + "file_count": 42, + "name": "marqdo-stdlib", + "root": "/stdlib", + "source_commit": "2cbde54602c07f62a62f341400bc9cb4764a93f8", + "tree_digest": "sha256:5407d3665ba2fe105820d0f1af5efaafa10c277a69eb819c3225719813c8c713", + "version": "0.1.0" +} +``` + +`tools/stdlib/bundle-pin.json` records the same identity. The resolver accepts +an explicit location but never an explicit identity: a valid-but-unpinned +Bundle is rejected. + +## 2. Failure paths (tools/ci/test_stdlib_bundle_tools.py) + +64 `tools/ci` unit tests pass. The new cases cover: + +* `--stdlib-dir` is required and a missing input fails before any output; +* a missing `stdlib.json`, a tree-digest mismatch, an alias-digest mismatch and + `public_aliases` without `aliases_digest` fail; +* a symlink inside the Bundle is rejected; +* an explicit Bundle that does not match the pin fails, even when the pinned + default is valid; +* a bad pin schema fails; +* the `bundle.py` CLI exits 1 on an invalid explicit input and 0 with + `--print-path` otherwise. + +The runtime override rule is pinned by the loader unit test +`bad_override_fails_closed_even_with_a_valid_sibling` (a bad +`MARQDO_STDLIB_DIR` fails although a valid sibling `stdlib/` exists). + +## 3. Deterministic packaging + +Two standalone stdlib packs from the same explicit input and toolchain are +byte-identical: + +```console +$ python3 tools/pack-stdlib.py --stdlib-dir stdlib \ + --bundle-pin tools/stdlib/bundle-pin.json --out-dir +$ python3 tools/pack-stdlib.py --stdlib-dir stdlib \ + --bundle-pin tools/stdlib/bundle-pin.json --out-dir +$ sha256sum /marqdo-stdlib-0.1.0.tar.gz /marqdo-stdlib-0.1.0.tar.gz +f6dc8e7ad92bc58b815635aea923069919d6f5495078e53828ae4723d925a565 /marqdo-stdlib-0.1.0.tar.gz +f6dc8e7ad92bc58b815635aea923069919d6f5495078e53828ae4723d925a565 /marqdo-stdlib-0.1.0.tar.gz +``` + +Two release archives built from `ab6b6b1` with `--skip-example-build` (the +host-built example artifacts were already present) are byte-identical: +`f37e01c44e668a6daf0538b32e9825cc74392f0ccbd65362af2783629b6d2c48`. +`RELEASE_INFO.json.stdlib.source` records +`{"kind":"in-repo","repository":"cflmy/marqdo-cli","commit":"2cbde54602c07f62a62f341400bc9cb4764a93f8","path":"stdlib"}` +and the tree/alias digests equal `stdlib.json`. + +## 4. Product and performance lanes + +The product, HTTP, table, alias-routing, P2 closure and semantic harnesses +resolve the pinned Bundle through `crates/cli/tests/support/stdlib.rs` +(`MARQDO_TEST_STDLIB_BUNDLE`/`MARQDO_TEST_BUNDLE_PIN` overrides are verified +against the pin). Loader unit tests build synthetic Bundles instead of the +product tree. + +```console +$ cargo test -p marqdo-cli --bin marqdo stdlib --offline +4 passed (synthetic loader tests) +$ cargo test -p marqdo-cli --test stdlib_product --offline +16 passed +$ cargo test -p marqdo-cli --test stdlib_bundle --test stdlib_http \ + --test stdlib_table --test stdlib_alias_routing --offline +13 passed +$ cargo test -p marqdo-cli --test architecture_boundaries \ + --test conformance_semantics --test p2_closure --offline +16 passed +$ python3 tools/perf/runner.py --no-build --binary target/debug/marqdo \ + --warmups 1 --samples 3 --allow-smoke --only hello-check ... +correctness=VERIFIED status=SMOKE +stdlib={... "source_commit":"2cbde54602c07f62a62f341400bc9cb4764a93f8" ...} +``` + +## 5. Independent build (clean copy without stdlib) + +`tools/ci/independent_build.py` exported `ab6b6b1` with `git archive`, removed +`stdlib/`, and built both binaries with `--locked`: + +```json +{ + "status": "PASS", + "source_sha": "ab6b6b1a23ec064fbc7de943c52befca18142a56", + "binaries": { + "marqdo": {"sha256": "428c25c60caa7762348bcffad96558591adf52440d44549a645390c927558757"}, + "marqdo-provider-worker": {"sha256": "3787942de6d35ce1c7f03c0848c8e08b6037495e98005c62704d34e664da795c"} + }, + "checks": { + "stdlib_source_removed": true, + "language_only_check": "PASS", + "language_only_call": "PASS:3", + "stdlib_dependent_missing_bundle": "PASS", + "no_sibling_stdlib": true + } +} +``` + +The stdlib-dependent `run examples/hello.mq.md` failed with an explicit +stdlib/print diagnostic instead of falling back to a source tree; the built +`target/debug` directory contains no `stdlib/`. + +## 6. Archive smoke and cold install + +```console +$ python3 tools/release/smoke.py --archive +smoke: verified stdlib 0.1.0 tree=sha256:5407d36... aliases=sha256:5f513c0... files=42 +smoke: archive version 3.0.0-rc.4, source ab6b6b1a23ec064fbc7de943c52befca18142a56 +smoke: bundled stdlib missing -> fail-closed OK +smoke: language-only program runs without the bundled stdlib +smoke: PASS +``` + +```console +$ bash tools/release/cold-install.sh ab6b6b1a23ec064fbc7de943c52befca18142a56 +你好,Marqdo +checked 2 module(s): ok +checked 1 module(s): ok +6 +runtime error[kernel.unavailable]: 打印 requires the bundled stdlib print module; install the official CLI bundle + +``` + +The container is `ubuntu:24.04`, `--network none`, user `65534:65534`, with no +Cargo and no source checkout; only the archive bytes are mounted. Moving the +shipped `stdlib/` aside keeps the language-only factorial call working and +makes the `打印` program fail with the explicit `kernel.unavailable` message. + +## 7. Gates on the candidate tree + +```console +$ cargo fmt --all -- --check +FMT_OK +$ cargo clippy --workspace --all-targets --offline -- -D warnings +exit=0 +$ cargo test --workspace --locked --offline +exit=0 +634 passed, 0 failed, 2 ignored across 72 test binaries +``` + +The workspace run includes `docs_consistency` (7 passed), +`architecture_boundaries`, the frozen conformance suites and every product +lane. It was executed on the candidate tree plus this documentation change and +is reproducible with `cargo test --workspace --locked`. Platform-native +Windows/macOS runs were not re-executed for this docs-only candidate; the +existing GitHub matrix remains the lane for them. + +## 8. Not claimed + +* Phase B: switching to the ecosystem-assembled Bundle, removing the in-repo + production sources, removing the debug source fallback and deleting replaced + `std:` entries. It is gated on ecosystem issue #2 and the extension + replacement evidence named by issue #11. +* Any `std:`/`stdlib.json`/`marqdo.stdlib-package`/Analysis/Observation shape + change; none was made. +* A docker cold-install on a Windows/macOS host or a native Windows/macOS + product run for this candidate. diff --git a/tests/README.md b/tests/README.md index 3d723c8..f7557e9 100644 --- a/tests/README.md +++ b/tests/README.md @@ -53,6 +53,24 @@ Rust harnesses (all in `crates/cli/tests/`): | `integration_cli.rs` | Real CLI contract: `init`, `check`, `run`, `call`, `inspect`, `fmt`, multi-module imports/cycles, `lock`/`sync --locked`, plugin inspection and explicitly trusted plugin invocation. | | `execution_events.rs` | Execution Events v1 black-box contract: pure JSONL, seq/terminal ordering, byte-exact base64 chunks, live delivery before exit, value redaction/selection, trace coexistence, truncation, output budget and broken-pipe failure. | +## Stdlib Bundle lanes (ADR-0070) + +The product lane consumes one pinned Bundle, never an implicit checkout path: + +* `tools/stdlib/bundle-pin.json` pins the Bundle name, version, source commit, + tree digest and alias digest; `tools/stdlib/bundle.py` resolves and verifies + it. +* `crates/cli/tests/support/stdlib.rs` gives the product/conformance harnesses + the same Bundle. `MARQDO_TEST_STDLIB_BUNDLE` or `--stdlib-dir` changes the + location but the Bundle must still match the pin; `MARQDO_TEST_BUNDLE_PIN` + changes the pin file. A bad explicit input fails even when the default + location is valid. +* Loader unit tests in `crates/cli/src/stdlib.rs` build small synthetic + Bundles, so loader logic does not depend on the product tree. +* `tests/independent/language-only.mq.md` is the program + `tools/ci/independent_build.py` runs through a CLI built from a copy without + `stdlib/`; a stdlib-dependent program must fail closed in that copy. + ## Running Use the workspace cargo cache/target as documented in `AGENTS.md`: -- 2.54.1 From 2acaaefe774726aa664181768ab730045b35e73f Mon Sep 17 00:00:00 2001 From: cflmy Date: Thu, 26 Nov 2026 15:56:20 +0800 Subject: [PATCH 8/9] ci: fold the independent build into the linux evidence gate tools/ci/release_evidence.py accepts only its declared gate names; the extra independent_build gate would have failed the release-evidence job. The job still depends on independent-build and marks linux FAIL when it does not pass. --- .github/workflows/ci.yml | 1 - 1 file changed, 1 deletion(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 0416cac..c105c20 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -284,7 +284,6 @@ jobs: 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" \ -- 2.54.1 From c769eafc607a5bf968af934b5940e83898e1b4f6 Mon Sep 17 00:00:00 2001 From: cflmy Date: Thu, 26 Nov 2026 15:59:07 +0800 Subject: [PATCH 9/9] docs: list the Phase A commits in the evidence record Add the smoke commit and the CI gate follow-up so the evidence names the reviewed implementation sequence instead of a relative commit. --- docs/evidence/2026-11-26-issue-11-phase-a.md | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/docs/evidence/2026-11-26-issue-11-phase-a.md b/docs/evidence/2026-11-26-issue-11-phase-a.md index afbc678..03f1316 100644 --- a/docs/evidence/2026-11-26-issue-11-phase-a.md +++ b/docs/evidence/2026-11-26-issue-11-phase-a.md @@ -16,7 +16,12 @@ Candidate commits (in order): | `422b9de` | `package.py --stdlib-dir/--bundle-pin`, `RELEASE_INFO.stdlib.source` | | `3a68260` | pinned test resolver, synthetic loader tests, product/conformance rewiring | | `ab6b6b1` | independent-build lane, perf Bundle pin, CI and docs | -| this docs commit | STATUS/README/tests/CURRENT + this evidence | +| `0e1efc7` | archive smoke/cold-install keep the language-only run after removing the Bundle | + +The documentation commit that adds this record also updates `STATUS.md`, the +architecture overview, `README.md` and `tests/README.md`. CI follow-up commit +`2acaaef` folds the `independent-build` job into the existing `linux` evidence +gate (the release-evidence schema accepts only its declared gate names). Executed host: Linux x86_64 (glibc 2.43), `rustc 1.100.0 (0ef1bc386 2026-11-09)`, `cargo 1.100.0 (3acc79c0c 2026-11-05)`, Python 3.14.4; the -- 2.54.1