diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 006941de..95677d30 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -32,11 +32,46 @@ jobs: - name: Lint maintained Python trees run: ruff check --select E,F,W --ignore E501 spark_transport runtime scripts performance integrations + shellcheck: + name: shellcheck + runs-on: ubuntu-latest + timeout-minutes: 10 + steps: + - uses: actions/checkout@v7 + - name: Check active shell scripts with bash -n and shellcheck + run: | + # Scope shellcheck -S warning to top-level active entry points so CI stays green while + # historical performance/records and jovian-r33 build scripts remain untouched. Run bash -n + # syntax checks across active entry points, launcher scripts, and transport tools. + entry_scripts=( + install.sh + bootstrap.sh + ) + syntax_scripts=( + "${entry_scripts[@]}" + scripts/nccl_ib_gid_policy.sh + scripts/deepseek_v41_cycle_serve.sh + scripts/deepseek_v4_cycle_serve.sh + scripts/deepseek_v4_pair_serve.sh + scripts/qwen38_dgx2_serve.sh + scripts/qwen38_dgx4_serve.sh + scripts/qwen38_pair_serve.sh + scripts/qwen38_ring4_serve.sh + spark_transport/libsircl/tools/emulation_suite.sh + spark_transport/libsircl/tools/nccl_tests_pair.sh + spark_transport/nccl/probe_dcp4_entrypoint.sh + spark_transport/nccl/probe_entrypoint.sh + ) + for script in "${syntax_scripts[@]}"; do + bash -n "$script" + done + shellcheck -S warning "${entry_scripts[@]}" + tests: name: tests runs-on: ubuntu-latest - # The suite took 26 to 39 minutes in October 2026 runs; 60 leaves room without hiding a hang. - timeout-minutes: 60 + # Runs parallelized across all runner cores with pytest-xdist (-n auto --dist loadfile). + timeout-minutes: 30 steps: - uses: actions/checkout@v7 - uses: actions/setup-python@v7 @@ -52,6 +87,7 @@ jobs: - name: Install test dependencies run: | python -m pip install --disable-pip-version-check -r requirements-dev.txt + python -m pip install --disable-pip-version-check pytest-xdist==3.6.1 python -m pip install --disable-pip-version-check \ --index-url https://download.pytorch.org/whl/cpu \ "torch==${TORCH_VERSION}" @@ -63,19 +99,56 @@ jobs: - name: Check image composition contracts run: | python runtime/images/composition.py runtime/images/sparkring-r35 - python -m pytest runtime/images -q - - name: Test maintained Python trees + python -m pytest -n auto --dist loadfile runtime/images -q -rs + - name: Test isolated-import Python suites + run: | + # runtime/glm53-flash-e10536a/test_contract.py shares a module basename with + # runtime/glm53-spark-mtp3-mesh/performance/reasoning/test_contract.py. + python -m pytest runtime/glm53-flash-e10536a -q -rs + # Vendored SparkCache deploy/contract tests expect integrations/sparkcache/4a17f1f5198e on PYTHONPATH. + # The two omitted files require unvendored upstream sparkcache repository files + # (RELEASING.md/.github/workflows/ci.yml and sparkcache.test_qwen38_installer_topology). + PYTHONPATH=integrations/sparkcache/4a17f1f5198e python -m pytest -n auto --dist loadfile \ + integrations/sparkcache/4a17f1f5198e/deploy \ + --ignore=integrations/sparkcache/4a17f1f5198e/deploy/deployment_contract/test_release_hardening.py \ + -q -rs + - name: Test auto-discovered Python suites run: | - # The glm53full_speedups and glm_dsa_indexer_split tests import the GLM-5.3 image's vLLM and B12X - # sources while they are collected, from the directory SPARKRING_GLM53_IMAGE_SOURCES names (their - # READMEs). The runner has no image, so without that variable they are left out, with a notice; - # the glm_dcp_decode_comm tests skip the checks that need the image themselves. + # Auto-discover all Python tests from the repository root so newly added test_*.py files + # are never silently skipped (enforced by scripts/test_ci_checks.py). + # + # Excluded here because another step or dedicated CI job owns them (zero duplicate runs): + # - runtime/images, runtime/glm53-flash-e10536a, integrations/sparkcache/4a17f1f5198e (steps above) + # - spark_transport/sircl (sircl job: isolated /sys/class/infiniband mount namespace) + # - integrations/lil (lil-bridge job: built pinned Go CLI) + # - scripts/compose_builder (compose-builder job: Node 22 + SPARKRING_REQUIRE_NODE=1) + # - runtime/common/test_compose*.py, runtime/common/test_toolchain_profiles.py, + # scripts/test_sparkring_compose.py (compose-profiles job: Docker Compose + SPARKRING_REQUIRE_COMPOSE=1) + # + # Excluded because they require external container/GPU/image sources unavailable on CPU runners: + # - runtime/deepseek-v41-gb10/tools/test_engram_packed.py (imports container-only vllm.models.deepseek_v4_1) + # - runtime/releases/shared-2026.09.0-rc.1/qualification (frozen b12x/GPU qualification fixtures) + # - integrations/vllm/glm53full_speedups/tests and integrations/vllm/glm_dsa_indexer_split/tests + # (require SPARKRING_GLM53_IMAGE_SOURCES pointing to the target image's vllm/ and b12x/ Python sources) image_tests=() if [ -z "${SPARKRING_GLM53_IMAGE_SOURCES:-}" ]; then echo "::notice title=GLM-5.3 plugin tests skipped::integrations/vllm/glm53full_speedups/tests and integrations/vllm/glm_dsa_indexer_split/tests need SPARKRING_GLM53_IMAGE_SOURCES, a directory of the target image's vllm/ and b12x/ Python sources" image_tests=(--ignore=integrations/vllm/glm53full_speedups/tests --ignore=integrations/vllm/glm_dsa_indexer_split/tests) fi - python -m pytest spark_transport --ignore=spark_transport/sircl runtime/exl3-r7 runtime/glm53-flash runtime/glm53-flash-jj-r8-gb10 runtime/glm53-spark-mtp3-mesh runtime/deepseek0731-gb10 runtime/qwen38 runtime/sparkring runtime/profiles runtime/transport_profiles runtime/test_public_overlay.py performance/harnesses scripts integrations/lil integrations/vllm integrations/b12x runtime/common runtime/host runtime/deepseek-v41-gb10/tools/test_packed_output_policy.py runtime/deepseek-v41-gb10/tools/test_prewarm5.py "${image_tests[@]}" -q -rs + python -m pytest . -n auto --dist loadfile \ + --ignore=runtime/images \ + --ignore=runtime/glm53-flash-e10536a \ + --ignore=integrations/sparkcache/4a17f1f5198e \ + --ignore=spark_transport/sircl \ + --ignore=integrations/lil \ + --ignore=scripts/compose_builder \ + --ignore=runtime/common/test_compose.py \ + --ignore=runtime/common/test_compose_envelope.py \ + --ignore=runtime/common/test_toolchain_profiles.py \ + --ignore=scripts/test_sparkring_compose.py \ + --ignore=runtime/deepseek-v41-gb10/tools/test_engram_packed.py \ + --ignore=runtime/releases/shared-2026.09.0-rc.1/qualification \ + "${image_tests[@]}" -q -rs sircl: name: SIRCL ring sessions diff --git a/README.md b/README.md index b4fb55cd..aa46e9c4 100644 --- a/README.md +++ b/README.md @@ -1,19 +1,20 @@ # SparkRing -*If you're not looking for vllm/sglang/other specific ring support, I highly recommend [Hyperflare](https://github.com/NVIDIA/hyperflare-inference)* - -SparkRing's profiles run three models created by Local Inference Lab, Inc. and -licensed under the Local Inference Lab License, Version 1.0: -[GLM-5.3-Flash-NVFP4-MXFP8-CSF-QAD](https://huggingface.co/local-inference-lab/GLM-5.3-Flash-NVFP4-MXFP8-CSF-QAD) -(`glm53-flash-tp2`, `glm53-flash-tp4`, `glm53-flash-tp2-dcp2`), -[GLM-5.3-NVFP4-CSF](https://huggingface.co/local-inference-lab/GLM-5.3-NVFP4-CSF) -(`glm53-nvfp4-csf-tp6`, `glm53-nvfp4-csf-tp8`) and -[Qwen3.8-Flash-Next-NVFP4-MXFP8-CSF-QAD](https://huggingface.co/local-inference-lab/Qwen3.8-Flash-Next-NVFP4-MXFP8-CSF-QAD) -(`qwen38-flash-next-tp2`). https://local-inference-lab.ai/ - -SparkRing serves large language models on two to eight NVIDIA DGX Sparks -cabled directly over ConnectX-7, with no switch. One command installs a model -on all of them, or several models on separate groups of them. +SparkRing is a switchless ring and chain RDMA collective transport (`libsircl`, +a drop-in `libnccl.so.2` library) and ConnectX-7 host fabric + launcher layer +for accelerating **vLLM, SGLang, and custom PyTorch/NCCL workloads** across two +to eight directly cabled NVIDIA DGX Sparks with no switch. + +> **Using [Hyperflare](https://github.com/NVIDIA/hyperflare-inference) (Flare)?** +> SparkRing owns the switchless ring/chain RDMA transport (`libsircl`) and +> multi-Spark host/launcher support for vLLM, SGLang, and custom NCCL +> containers. Hyperflare owns the custom native inference engine — if you do +> not need vLLM, SGLang, or custom NCCL ring support, start with +> [Hyperflare](https://github.com/NVIDIA/hyperflare-inference). + +One command cables, enrolls, and configures a pair, line, or ring of two to +eight DGX Sparks over ConnectX-7, then deploys one model across all of them or +several models on separate groups. ## Quick start @@ -44,11 +45,17 @@ More: [documentation](docs/README.md) · [commands](docs/operations/commands.md) ## SIRCL -SIRCL, the Switchless Inference RDMA Collective Layer, carries the model's -collectives between Sparks, including Sparks reached through another Spark's -ConnectX-7 relay ([architecture](docs/architecture/sircl.md)). -[net-sircl](https://github.com/FujitsuPolycom/net-sircl) brings it to any NCCL -application as a network plugin (research-only). +SIRCL (the Switchless Inference RDMA Collective Layer) carries collectives and +point-to-point exchanges between directly cabled Sparks, including peers +reached through another Spark's ConnectX-7 hardware relay +([architecture](docs/architecture/sircl.md)). + +- **[`libsircl`](spark_transport/libsircl/README.md)** is SparkRing's primary + drop-in `libnccl.so.2` implementation: preload it into stock vLLM, SGLang, or + PyTorch `ProcessGroupNCCL` containers to run switchless pair, chain, and ring + RDMA collectives over ConnectX-7. +- **[net-sircl](https://github.com/FujitsuPolycom/net-sircl)** exposes SIRCL as + an NCCL network plugin for custom NCCL applications (research-only). ## Profiles @@ -74,11 +81,16 @@ research-only; the other rows are implemented. The six-Spark GLM-5.3 profile ## Speed -Output tok/s, measured with llm-inference-bench 0.7.6 at temperature 1 on -release 2026.10.2's image, one start per profile installed without research -options; decode and prefill at 32K context. The default image, release -2026.10.5's, has no speed record of its own, nor has its parent, release -2026.10.4's. Records: +> **Historical baseline (release `2026.10.2` only):** The table below records +> output tok/s measured with `llm-inference-bench 0.7.6` at temperature 1 and +> 32K context on release `2026.10.2`'s image (one start per profile without +> research options). Releases `2026.10.4` and `2026.10.5` do not have a +> matching full-matrix speed sweep yet; treat these numbers as a historical +> reference for `2026.10.2`, not current release benchmarks. See +> [Benchmarks and test results](performance/benchmarks.md) for methodology and +> per-profile receipts. + +Records: [every cell's raw source](performance/records/images/release-2026.10.2-speed-32k-20261012.md), [rings of four](performance/records/images/dev-20261010-kraken-csf-sircl032-libsircl060cd-plugins-status036-release-2026.10.3-plain-ring4-20261012.md), [ring of eight](performance/records/images/dev-20261010-kraken-csf-sircl032-libsircl060cd-plugins-status036-release-2026.10.3-plain-ring8-20261012.md), @@ -104,7 +116,17 @@ options; decode and prefill at 32K context. The default image, release - [Contributing](CONTRIBUTING.md) and [repository layout](docs/development/layout.md) - [Community discussions](https://github.com/FujitsuPolycom/sparkring/discussions) -## Acknowledgements +## Attribution & Licenses + +SparkRing's profiles reference three models created by Local Inference Lab, Inc. +and licensed under the Local Inference Lab License, Version 1.0 +(https://local-inference-lab.ai/): +[GLM-5.3-Flash-NVFP4-MXFP8-CSF-QAD](https://huggingface.co/local-inference-lab/GLM-5.3-Flash-NVFP4-MXFP8-CSF-QAD) +(`glm53-flash-tp2`, `glm53-flash-tp4`, `glm53-flash-tp2-dcp2`), +[GLM-5.3-NVFP4-CSF](https://huggingface.co/local-inference-lab/GLM-5.3-NVFP4-CSF) +(`glm53-nvfp4-csf-tp6`, `glm53-nvfp4-csf-tp8`), and +[Qwen3.8-Flash-Next-NVFP4-MXFP8-CSF-QAD](https://huggingface.co/local-inference-lab/Qwen3.8-Flash-Next-NVFP4-MXFP8-CSF-QAD) +(`qwen38-flash-next-tp2`). SparkRing builds on [Local Inference Lab](https://local-inference-lab.ai/) ([GitHub](https://github.com/local-inference-lab) · @@ -128,10 +150,10 @@ licensed under Apache-2.0; b12x now lives in FlashInfer at SparkRing's NCCL patches follow Joseph Rose's [nccl-spark-switchless](https://github.com/josephdrose/nccl-spark-switchless). Thanks to Eugene Rakhmatulin for the `eugr/spark-vllm-b12x` base image, and to -the vLLM, NVIDIA NCCL and ExLlamaV3 contributors. The +the vLLM, SGLang, NVIDIA NCCL and ExLlamaV3 contributors. The [third-party notices](THIRD_PARTY_NOTICES.md) give origins and licenses. -## License +### License SparkRing code is [Apache-2.0](LICENSE). Model weights and bundled components keep their own terms; check the model cards and diff --git a/docs/CI.md b/docs/CI.md index 48c62806..7007826d 100644 --- a/docs/CI.md +++ b/docs/CI.md @@ -4,11 +4,30 @@ Status: **implemented**. `.github/workflows/ci.yml` runs on pull requests and pushes to `main`. Feature-branch pushes without a pull request do not run this workflow. Jobs use read-only repository permissions. -- `lint` checks maintained Python source with Ruff. -- `tests` runs GPU-free contracts, including serving configuration and - measurement-receipt checks. README tests check navigation rather than - requiring a particular prose or table layout. -- `SIRCL ring sessions` runs the CPU tests of the +- `lint` checks maintained Python trees (`spark_transport`, `runtime`, + `scripts`, `performance`, `integrations`) with Ruff (`--select E,F,W --ignore E501`). +- `shellcheck` validates syntax (`bash -n`) across active entry points, + launcher scripts, and transport tools, and runs `shellcheck -S warning` on + `install.sh` and `bootstrap.sh`. +- `tests` runs GPU-free Python contracts across the repository in parallel + using `pytest-xdist` (`-n auto --dist loadfile`): + - Image composition contracts (`runtime/images/composition.py` and + `pytest runtime/images`). + - Isolated-import suites (`runtime/glm53-flash-e10536a` and the vendored + SparkCache deploy/contract tests under + `integrations/sparkcache/4a17f1f5198e/deploy` with `PYTHONPATH` set). + - Auto-discovered Python tests from the repository root (`python -m pytest .`), + including SGLang tests (`runtime/deepseek-v41-sglang/`), with explicit + `--ignore` entries only for suites owned by dedicated jobs below (zero + duplicate runs) and external image/GPU/upstream-only tests + (`integrations/vllm/glm53full_speedups/tests`, + `integrations/vllm/glm_dsa_indexer_split/tests`, + `runtime/deepseek-v41-gb10/tools/test_engram_packed.py`, and + `runtime/releases/shared-2026.09.0-rc.1/qualification`). + - `scripts/test_ci_checks.py` enforces that every tracked `test_*.py` file + is either covered once by CI or explicitly listed as an external-artifact + exclusion, so newly added tests cannot be silently orphaned. +- `SIRCL ring sessions` (`sircl`) runs the CPU tests of the [SIRCL ring-session package](../spark_transport/sircl/README.md) from the repository layout, with its own pytest settings. Its native tests compile the progress-thread source with GCC against an in-memory verbs stand-in; @@ -16,34 +35,52 @@ run this workflow. Jobs use read-only repository permissions. namespace whose `/sys/class/infiniband` is empty, because a session checks its route map against the host's active RDMA devices whenever the host lists any, and a hosted runner's network adapter can list one. -- `pinned LIL bridge` builds the source-pinned - [LIL deployment companion](../integrations/lil/README.md) and exercises - its SparkRing integration. -- `profile and repository contracts` validates deployment profiles, generated - exports, references, immutable release inputs, and image-builder contracts. -- `docs links` checks tracked inline Markdown links and ATX heading anchors, - including duplicate-heading suffixes. Front-page lists without a separating - blank line produce advisory warnings. External links, reference-style links, - HTML anchors, and rendered visual layout are not validated by this checker. - Inline-code exclusion recognizes single-backtick spans. Use percent-encoded - destinations for filenames containing spaces or parentheses. -- `release safety` scans tracked nonbinary files for configured site-address - and credential shapes. It prints only path, line number, and rule identifier. - Findings exit with status 1; scan failures exit with status 2. The rule file - itself is excluded. Shapes include local Windows user paths. On an - operator's machine the scan also reports the site's own host names and MAC - addresses (with their IPv6 link-local forms), read from the untracked file +- `libsircl C library` (`libsircl`) builds + [`spark_transport/libsircl`](../spark_transport/libsircl/README.md) and its + four CUDA 13.3 kernel packs (`nvcc`), checks exported library symbols + (`tools/check_exports.py`), and runs `make check`, `make check-asan`, and + the CMake `ctest` suite against the shared-memory verbs stand-in. +- `pinned LIL bridge` (`lil-bridge`) builds the source-pinned + [LIL deployment companion](../integrations/lil/README.md) with Go and + exercises `integrations/lil` against the built CLI. +- `generated Compose equivalence` (`compose-profiles`) validates + `scripts/generate_compose_examples.py --check` and runs the Compose and + toolchain profile suites with Docker Compose (`SPARKRING_REQUIRE_COMPOSE=1`). +- `Install Builder` (`compose-builder`) compares the Install Builder + JavaScript engine against `compose.build` under Node 22 + (`SPARKRING_REQUIRE_NODE=1`). +- `docs links` (`docs-links`) checks tracked inline Markdown links and ATX + heading anchors, including duplicate-heading suffixes. Front-page lists + without a separating blank line produce advisory warnings. External links, + reference-style links, HTML anchors, and rendered visual layout are not + validated by this checker. Inline-code exclusion recognizes single-backtick + spans. Use percent-encoded destinations for filenames containing spaces or + parentheses. +- `release safety` (`release-safety`) scans tracked text files and bounded + `.gz`/`.tar.gz` archive text members for private LAN addresses (including + bare RFC 1918 `10/8` addresses outside SparkRing's built-in admin default and + documented fixture allowlists), provider secret tokens (`hf_`, `sk-`, `AKIA`, + `gh*_`, `xox*`), credential assignments, private/SSH keys, and local user + paths without printing matched content. It prints only path, line number, and + rule identifier. Findings exit with status 1; scan failures exit with status + 2. The rule file itself is excluded. On an operator's machine the scan also + reports the site's own host names and MAC addresses (with their IPv6 + link-local forms), read from the untracked file `scripts/config/site-values.txt` (one value per line) or `--site-values FILE`; CI has no such file. This bounded pattern scan is not a security certification. +- `profile and repository contracts` (`repository-layout`) validates + deployment profiles, generated exports, catalogued enhancements, immutable + release inputs, locked profile assets, maintained imports, and image-builder + contracts. -Run the documentation and release checks locally from the repository root: +Run the documentation, workflow, and release checks locally from the repository root: ```bash python scripts/check_markdown_links.py . python scripts/check_release_safety.py . python scripts/check_repository_layout.py -python -m pytest scripts/test_ci_checks.py scripts/test_glm53_flash_profile.py -q +python -m pytest scripts/test_ci_checks.py scripts/test_release_safety.py scripts/test_build_deb.py scripts/test_glm53_flash_profile.py -q ``` The full lint and test commands are defined in the workflow. Hardware-dependent diff --git a/runtime/common/distribution.py b/runtime/common/distribution.py index 0b49fd7d..2f18d3d7 100644 --- a/runtime/common/distribution.py +++ b/runtime/common/distribution.py @@ -27,8 +27,12 @@ def installed(root, *, verify=True): or target.is_symlink() or not target.resolve().is_relative_to(root) or digest(target) != expected): raise ValueError("Installed SparkRing file differs: " + name) - if digest(root / "source.bundle") != record["bundle_sha256"]: - raise ValueError("Installed source bundle differs") + expected_bundle = record.get("bundle_sha256") + if expected_bundle is not None: + if digest(root / "source.bundle") != expected_bundle: + raise ValueError("Installed source bundle differs") + elif (root / "source.bundle").exists(): + raise ValueError("Installed source bundle is unrecorded") return record @@ -49,7 +53,13 @@ def bundle(root, output): if output.exists(): raise ValueError("Source bundle output already exists") if record: - shutil.copyfile(Path(root) / "source.bundle", output) + source_bundle = Path(root) / "source.bundle" + if not record.get("bundle_sha256") or not source_bundle.is_file(): + raise ValueError( + "Installed SparkRing package was built without source.bundle; " + "rebuild with scripts/build_deb.py --include-source-bundle" + ) + shutil.copyfile(source_bundle, output) else: subprocess.run(["git", "bundle", "create", str(output), "HEAD"], cwd=root, check=True, capture_output=True) output.chmod(0o600) diff --git a/runtime/common/test_distribution.py b/runtime/common/test_distribution.py index e34d9510..556bc2d8 100644 --- a/runtime/common/test_distribution.py +++ b/runtime/common/test_distribution.py @@ -18,3 +18,17 @@ def test_installed_source_and_bundle_are_verified_without_git(tmp_path): (tmp_path / "source.py").write_text("# changed\n") with pytest.raises(ValueError, match="file differs"): distribution.identity(tmp_path) + + +def test_installed_slim_manifest_verifies_without_source_bundle(tmp_path): + (tmp_path / "source.py").write_text("# slim fixture\n") + record = {"schema": "sparkring-distribution/v1", "revision": "b" * 40, + "files": {"source.py": distribution.digest(tmp_path / "source.py")}} + (tmp_path / "distribution.json").write_text(json.dumps(record)) + assert distribution.identity(tmp_path) == "b" * 40 + with pytest.raises(ValueError, match="--include-source-bundle"): + distribution.bundle(tmp_path, tmp_path / "copy.bundle") + # Dropping an unrecorded source.bundle into a slim install fails verification. + (tmp_path / "source.bundle").write_bytes(b"unrecorded") + with pytest.raises(ValueError, match="unrecorded"): + distribution.identity(tmp_path) diff --git a/runtime/host/test_progress.py b/runtime/host/test_progress.py index 528742df..c5645bf0 100644 --- a/runtime/host/test_progress.py +++ b/runtime/host/test_progress.py @@ -7,10 +7,18 @@ import pytest -from runtime.host import progress +from runtime.host import colour, progress from runtime.host.terminal import Console +@pytest.fixture(autouse=True) +def reset_colour_mode(monkeypatch): + colour.set_mode(None) + monkeypatch.delenv("SPARKRING_COLOR", raising=False) + yield + colour.set_mode(None) + + class TerminalBuffer(io.StringIO): def isatty(self): return True diff --git a/scripts/build_deb.py b/scripts/build_deb.py index 43570a98..82f7ced7 100644 --- a/scripts/build_deb.py +++ b/scripts/build_deb.py @@ -1,10 +1,19 @@ #!/usr/bin/env python3 """Build a reproducible Linux ARM64 control-plane package from a clean commit. -The package carries the commit's source tree, its history as a Git bundle and -one program built from C: the relay marker (``sparkring-relay-marker``, from -``spark_transport/fabric/relay_marker.c``), which the fabric relay table runs -on every Spark. The marker ships prebuilt, so no Spark compiles it: +By default the package stages an explicit runtime manifest (runtime code, +transport, integrations, packaging, profiles, recipes, scripts, active release +selection JSONs, and root license/entry-point files) and omits benchmark dumps +(``performance/``), historical ``runtime/releases/*`` payloads, raw +``.tar.gz``/``.gz`` archives, and the full Git history bundle +(``source.bundle``). Pass ``--include-source-bundle`` to build the legacy +full-source package carrying the entire ``git archive`` tree plus +``source.bundle``. + +The package also carries one program built from C: the relay marker +(``sparkring-relay-marker``, from ``spark_transport/fabric/relay_marker.c``), +which the fabric relay table runs on every Spark. The marker ships prebuilt, so +no Spark compiles it: - ``--relay-marker prebuilt`` (the default, and what ``install.sh`` runs) takes the published binary that the marker record @@ -20,9 +29,9 @@ Every mode except ``skip`` also writes the binary and its ``.sha256`` file beside the package, for publication. ``distribution.json`` records the -binary's SHA-256 (``relay_marker``); the package's installation checks the -installed binary against it, and every Spark checks it again before it runs -the marker. +SHA-256 of every packaged file and the binary's SHA-256 (``relay_marker``); +the package's installation checks the installed tree and binary against it, +and every Spark checks the marker again before it runs it. """ import argparse import hashlib @@ -54,6 +63,44 @@ MARKER_MAX_BYTES = 1 << 20 # ELF header: 64-bit, little-endian, machine 183 (AArch64). AARCH64 = 183 +# Explicit runtime manifest for the default slim .deb payload. +RUNTIME_TOP_DIRS = frozenset({ + "runtime", "spark_transport", "integrations", "packaging", + "profiles", "recipes", "scripts", "third_party", +}) +RUNTIME_ROOT_FILES = frozenset({ + "LICENSE", "THIRD_PARTY_NOTICES.md", "README.md", + "install.sh", "bootstrap.sh", "requirements-dev.txt", +}) +ACTIVE_RELEASE_CONFIG_NAMES = frozenset({ + "installer-image.json", "release.json", "publication.json", "glm-profile-contract.json", +}) +EXCLUDED_ARCHIVE_SUFFIXES = (".tar.gz", ".tgz", ".gz") +EXCLUDED_SUBTREES = ( + "performance/", + "runtime/glm53-spark-mtp3-mesh/performance/", +) + + +def is_runtime_manifest_path(relative): + """Whether ``relative`` (a POSIX archive member path) belongs in the slim runtime payload.""" + normalized = str(relative).lstrip("./").rstrip("/") + if not normalized: + return False + if any(normalized == prefix.rstrip("/") or normalized.startswith(prefix) for prefix in EXCLUDED_SUBTREES): + return False + if normalized.lower().endswith(EXCLUDED_ARCHIVE_SUFFIXES): + return False + parts = normalized.split("/") + if len(parts) == 1: + return normalized in RUNTIME_ROOT_FILES + if parts[0] not in RUNTIME_TOP_DIRS: + return False + if parts[0] == "runtime" and len(parts) >= 2 and parts[1] == "releases": + if normalized == "runtime/releases/installer-releases.json": + return True + return len(parts) == 4 and parts[3] in ACTIVE_RELEASE_CONFIG_NAMES + return True def marker_record(root): @@ -194,7 +241,8 @@ def package_file_name(version): return f"sparkring_{version.replace('~', '.')}_arm64.deb" -def build(root, output, *, version=None, marker="prebuilt", marker_binary=None): +def build(root, output, *, version=None, marker="prebuilt", marker_binary=None, + include_source_bundle=False): root, output = Path(root).resolve(), Path(output).resolve() revision = distribution.identity(root) epoch = int(subprocess.check_output(["git", "show", "-s", "--format=%ct", revision], cwd=root, text=True)) @@ -213,20 +261,27 @@ def build(root, output, *, version=None, marker="prebuilt", marker_binary=None): archive = work / "source.tar" subprocess.run(["git", "archive", "--format=tar", "-o", str(archive), revision], cwd=root, check=True) with tarfile.open(archive) as tar: + members = tar.getmembers() # Files shipped by the package must be regular source files. - if any(not m.isfile() and not m.isdir() for m in tar.getmembers()): + if any(not m.isfile() and not m.isdir() for m in members): raise ValueError("Distribution source contains nonregular entries") - tar.extractall(payload, filter="data") + if include_source_bundle: + tar.extractall(payload, filter="data") + else: + selected = [m for m in members if m.isfile() and is_runtime_manifest_path(m.name)] + tar.extractall(payload, members=selected, filter="data") files = {p.relative_to(payload).as_posix(): distribution.digest(p) for p in sorted(payload.rglob("*")) if p.is_file()} # Built after the source files are recorded: distribution.installed # verifies the source tree, and relays.marker_artifact the binary. built = relay_marker(payload, mode=marker, binary=marker_binary) - bundle = payload / "source.bundle" - # A single-tip, deterministic pack avoids reflog/other-branch identities. - subprocess.run(["git", "-c", "pack.threads=1", "bundle", "create", str(bundle), "HEAD"], cwd=root, check=True, capture_output=True) record = {"schema": "sparkring-distribution/v1", "revision": revision, "version": version, - "source_date_epoch": epoch, "architecture": "arm64", "files": files, - "bundle_sha256": distribution.digest(bundle)} + "source_date_epoch": epoch, "architecture": "arm64", "files": files} + if include_source_bundle: + bundle = payload / "source.bundle" + # A single-tip, deterministic pack avoids reflog/other-branch identities. + subprocess.run(["git", "-c", "pack.threads=1", "bundle", "create", str(bundle), "HEAD"], + cwd=root, check=True, capture_output=True) + record["bundle_sha256"] = distribution.digest(bundle) if built is not None: record["relay_marker"] = built (payload / "distribution.json").write_text(json.dumps(record, sort_keys=True, indent=2) + "\n", encoding="utf-8") @@ -312,10 +367,14 @@ def main(argv=None): parser.add_argument("--relay-marker-binary", type=Path, metavar="PATH", help="with prebuilt: ship this relay marker binary instead of downloading the published one; " "it must equal the published binary when the marker record names one") + parser.add_argument("--include-source-bundle", action="store_true", + help="pack the full git archive tree (including performance/ and historical releases) and " + "embed source.bundle instead of the slim runtime manifest") args = parser.parse_args(argv) try: print(json.dumps(build(ROOT, args.output, version=args.version, marker=args.relay_marker, - marker_binary=args.relay_marker_binary), indent=2)) + marker_binary=args.relay_marker_binary, + include_source_bundle=args.include_source_bundle), indent=2)) return 0 except (ValueError, OSError, subprocess.SubprocessError) as error: print("Package build: " + str(error), file=sys.stderr) diff --git a/scripts/check_release_safety.py b/scripts/check_release_safety.py index 2efeba66..32afa95f 100644 --- a/scripts/check_release_safety.py +++ b/scripts/check_release_safety.py @@ -1,4 +1,4 @@ -"""Scan tracked text for site/credential shapes without printing matched content. +"""Scan tracked text and gzip/tar.gz archives for site/credential shapes without printing matched content. Besides the shapes in RULES, the scan looks for the operator's own site values when a local, untracked file lists them: one host name or MAC address per line @@ -11,11 +11,15 @@ """ from pathlib import Path import argparse +import gzip +import io import ipaddress import json import math import re import subprocess +import tarfile +import zlib RULES = { @@ -28,9 +32,52 @@ "private-key": r"-----BEGIN [A-Z ]*PRIVATE KEY-----", "ssh-public-key": r"ssh-(?:rsa|ed25519|dss) AAAA", "credential-assignment": r"(?:pass(?:word|wd)|secret|api[_-]?key|access[_-]?token|auth[_-]?token|client[_-]?secret|bearer)[\"']?\s*[:=]\s*[\"']?[A-Za-z0-9/+_.-]{12,}", - "provider-token": r"AWS_SECRET_ACCESS_KEY|GITHUB_TOKEN\s*[:=]|xox[baprs]-|gh[pousr]_[A-Za-z0-9]{20,}", + "provider-token": ( + r"AWS_SECRET_ACCESS_KEY|GITHUB_TOKEN\s*[:=]|xox[baprs]-|gh[pousr]_[A-Za-z0-9]{20,}" + r"|(? exact allowed IP literals so unrelated line edits do not break the scan +# and any newly added 10.x.x.x address in these or other files is still caught. +PRIVATE_10_ALLOWED = { + "docs/operations/bootstrap.md": frozenset({"10.77.0.0"}), + "runtime/common/test_serving.py": frozenset({"10.1.2.3"}), + "runtime/host/test_checkpoint_search.py": frozenset({"10.0.0.5"}), + "runtime/host/test_control.py": frozenset({"10.0.0.0"}), + "runtime/host/test_placement.py": frozenset({"10.42.0.1", "10.42.0.3"}), + "runtime/images/upgrades/checks/image-metadata-labels-a75bd02f.json": frozenset({"10.4.3.29"}), + "scripts/compose_builder/page.html": frozenset({"10.0.0.10"}), + "scripts/compose_builder/test_site.py": frozenset({"10.0.0.5"}), + "scripts/test_deepseek_v4_pair_launcher.py": frozenset({ + "10.0.0.0", "10.42.0.0", "10.42.0.1", "10.42.0.2", "10.42.0.8", "10.42.0.9", + "10.43.0.0", "10.43.0.1", "10.43.0.4", "10.44.0.1", "10.45.0.1", "10.46.0.1", "10.99.0.0", + }), + "scripts/test_preflight.py": frozenset({"10.9.9.9"}), + "scripts/test_qwen38_launcher_preflight.py": frozenset({"10.42.1.1", "10.42.2.1"}), + "scripts/test_ring_doctor.py": frozenset({ + "10.0.0.0", "10.0.1.0", "10.0.1.1", "10.0.1.10", "10.0.1.11", "10.0.1.2", "10.0.1.20", + "10.0.2.0", "10.0.2.1", "10.0.2.10", "10.0.2.11", "10.0.2.2", "10.0.3.0", "10.0.3.1", + "10.0.3.11", "10.0.3.12", "10.0.3.2", "10.0.4.0", "10.0.4.1", "10.0.4.10", "10.0.4.12", + "10.0.4.13", "10.0.4.2", "10.99.0.1", + }), + "scripts/test_sparkring_cluster.py": frozenset({"10.99.0.0"}), + "scripts/test_sparkring_site.py": frozenset({"10.0.0.1", "10.1.2.3"}), + "spark_transport/sircl/tests/test_fabric_ops.py": frozenset({"10.9.9.9"}), + "spark_transport/tests/test_nccl_probe_validation.py": frozenset({"10.0.0.1"}), +} +_SPDX_NUMERIC_VERSION = re.compile(r"^\d+(?:\.\d+)+(?:[-+~][A-Za-z0-9.+~:%-]+)?$") +_SPDX_CPE = re.compile(r"^cpe:2\.3:[aho]:[A-Za-z0-9._-]+:[A-Za-z0-9._-]+:[A-Za-z0-9._:*~+-]+$") +_SPDX_PURL = re.compile(r"^pkg:[a-z0-9+.-]+/[^@\s]+@[0-9][A-Za-z0-9._:%+~-]*(\?[^\s]*)?$") # The untracked file of site values (.gitignore lists it). SITE_VALUES = Path("scripts/config/site-values.txt") # Lines that keep a site value on purpose: path -> {line: reason}. A file listed here is bound by SHA-256 @@ -42,6 +89,10 @@ _MAC = re.compile(r"[0-9a-f]{2}(?::[0-9a-f]{2}){5}") +class ArchiveLimitError(ValueError): + """Raised when a compressed archive exceeds bounded decompression limits.""" + + def site_patterns(path): """One compiled pattern per value of the site-value file at ``path``; none when the file is absent. @@ -117,17 +168,125 @@ class JsonNumber(str): return text -def findings(text, site=()): +def spdx_scan_text(text): + """Strip numeric version/CPE/PURL metadata in single-line SPDX JSON documents only. + + Leaves all other fields (names, descriptions, URLs, suppliers, tokens, IPs) untouched + so real credentials or addresses inside an SBOM still trigger findings. + """ + if len(text.splitlines()) != 1 or not text.lstrip().startswith("{"): + return text + if '"spdxVersion"' not in text: + return text + try: + document = json.loads(text) + except (ValueError, TypeError): + return text + if (not isinstance(document, dict) + or not isinstance(document.get("spdxVersion"), str) + or not document["spdxVersion"].startswith("SPDX-") + or not isinstance(document.get("packages"), list)): + return text + for package in document["packages"]: + if not isinstance(package, dict): + continue + version = package.get("versionInfo") + if isinstance(version, str) and _SPDX_NUMERIC_VERSION.fullmatch(version): + package["versionInfo"] = "" + refs = package.get("externalRefs") + if not isinstance(refs, list): + continue + for ref in refs: + if not isinstance(ref, dict): + continue + locator = ref.get("referenceLocator") + if not isinstance(locator, str): + continue + if _SPDX_CPE.fullmatch(locator): + ref["referenceLocator"] = "" + elif _SPDX_PURL.fullmatch(locator): + # Keep the package name scannable while removing the @version suffix. + ref["referenceLocator"] = locator.split("@", 1)[0] + return json.dumps(document, ensure_ascii=False) + + +def _has_disallowed_private_10(line, allowed_private_10=()): + """Whether ``line`` contains a bare 10.0.0.0/8 IPv4 address outside built-in and file allowlists.""" + for match in _PRIVATE_10.finditer(line): + ip = match.group(1) + if ip in allowed_private_10: + continue + if ipaddress.ip_address(ip) in ADMIN_DEFAULT_SUBNET: + continue + return True + return False + + +def findings(text, site=(), *, allowed_private_10=()): + spdx_text = spdx_scan_text(text) + if spdx_text != text: + text = spdx_text credential_text = credential_scan_text(text) for number, line in enumerate(text.splitlines(), 1): for name, pattern in RULES.items(): - scanned = credential_text if name == 'credential-assignment' and credential_text != text else line + scanned = credential_text if name == "credential-assignment" and credential_text != text else line if re.search(pattern, scanned, re.I): yield number, name + elif name == "private-lan-address" and _has_disallowed_private_10(line, allowed_private_10): + yield number, name if any(pattern.search(line) for pattern in site): yield number, "site-value" +def _read_bounded(stream, limit, label): + data = stream.read(limit + 1) + if len(data) > limit: + raise ArchiveLimitError(f"{label} exceeds decompressed limit of {limit} bytes") + return data + + +def iter_text_members(relative, data, *, member_limit=MAX_ARCHIVE_MEMBER_BYTES, + total_limit=MAX_ARCHIVE_TOTAL_BYTES, max_members=MAX_ARCHIVE_MEMBERS): + """Yield ``(label, text)`` pairs for a plain text file or text members inside ``.gz``/``.tar.gz``. + + Binary non-archive files and binary tar members (containing NUL bytes) are skipped. + Decompression is strictly bounded against gzip/tar bombs via ``ArchiveLimitError``. + """ + lower = relative.lower() + if lower.endswith((".tar.gz", ".tgz")): + total = 0 + count = 0 + with tarfile.open(fileobj=io.BytesIO(data), mode="r:gz") as archive: + for member in archive.getmembers(): + if not member.isfile(): + continue + count += 1 + if count > max_members: + raise ArchiveLimitError(f"{relative} exceeds maximum member count {max_members}") + remaining = total_limit - total + cap = min(member_limit, remaining) + extracted = archive.extractfile(member) + if extracted is None: + continue + with extracted: + raw = _read_bounded(extracted, cap, f"{relative}!{member.name}") + total += len(raw) + if b"\0" in raw: + continue + yield f"{relative}!{member.name}", raw.decode("utf-8", errors="replace") + return + if lower.endswith(".gz"): + with gzip.GzipFile(fileobj=io.BytesIO(data), mode="rb") as stream: + raw = _read_bounded(stream, member_limit, relative) + if b"\0" in raw: + return + yield relative, raw.decode("utf-8", errors="replace") + return + if b"\0" in data: + return + yield relative, data.decode("utf-8", errors="replace") + + def main(root, site_values=None): site = site_patterns(site_values if site_values is not None else root / SITE_VALUES) try: @@ -140,18 +299,24 @@ def main(root, site_values=None): if relative in EXCLUDES: continue data = (root / relative).read_bytes() - if b"\0" in data: - continue - allowed = SITE_VALUE_ALLOWED.get(relative, {}) - for line, rule in findings(data.decode("utf-8", errors="replace"), site): - if rule == "site-value" and line in allowed: - continue - # JSON escapes control characters in paths, preventing log injection. - print(json.dumps({"path": relative, "line": line, "rule": rule})) + allowed_site = SITE_VALUE_ALLOWED.get(relative, {}) + allowed_10 = PRIVATE_10_ALLOWED.get(relative, ()) + try: + members = list(iter_text_members(relative, data)) + except ArchiveLimitError: + print(json.dumps({"path": relative, "line": 0, "rule": "archive-limit-exceeded"})) count += 1 + continue + for label, text in members: + for line, rule in findings(text, site, allowed_private_10=allowed_10): + if rule == "site-value" and line in allowed_site: + continue + # JSON escapes control characters in paths, preventing log injection. + print(json.dumps({"path": label, "line": line, "rule": rule})) + count += 1 print(f"Release-safety findings: {count}; matched content is withheld. Site values: {len(site)}.") return int(count > 0) - except (OSError, subprocess.SubprocessError): + except (OSError, EOFError, zlib.error, tarfile.TarError, subprocess.SubprocessError): # Exception strings can contain command output or sensitive paths. print("Release-safety scan failed; tracked content could not be fully inspected.") return 2 diff --git a/scripts/compose_builder/site.py b/scripts/compose_builder/site.py index eb75ef29..804d67bf 100644 --- a/scripts/compose_builder/site.py +++ b/scripts/compose_builder/site.py @@ -284,7 +284,7 @@ def installed_cells(profile): def landing(value): meta = value["meta"] - license_notice = read("README.md").split("\n## Quick start", 1)[0].split("\n\n")[1] + license_notice = section(read("README.md"), "Attribution & Licenses").split("\n\n", 1)[0] # The site's own install.sh copy (hosted_installer) on the site; landing.js shows it there. cmd = (f"curl -fsSL https://raw.githubusercontent.com/{meta['repository']}/{meta['ref']}/install.sh " f"| bash -s -- --ref {meta['ref']} --profile PROFILE") diff --git a/scripts/test_build_deb.py b/scripts/test_build_deb.py index 0e6a0220..b10811e7 100644 --- a/scripts/test_build_deb.py +++ b/scripts/test_build_deb.py @@ -282,3 +282,92 @@ def run(argv, **kwargs): asset_hash, asset_filename = asset_checksum_content.split(" ") assert asset_filename == asset_path.name assert "~" not in asset_filename, "Relay marker filename should not contain ~" + + +def test_default_build_stages_slim_runtime_manifest_and_excludes_performance_and_bundle(tmp_path, monkeypatch): + import io + import tarfile + + source = tmp_path / "source.tar" + with tarfile.open(source, "w") as tar: + tar.add(ROOT / "packaging/debian", arcname="packaging/debian") + for name, data in ( + ("runtime/common/example.py", b"# runtime code\n"), + ("spark_transport/libsircl/README.md", b"# libsircl\n"), + ("profiles/catalog.json", b"{}\n"), + ("runtime/releases/installer-releases.json", b"{}\n"), + ("runtime/releases/dev-20261016/installer-image.json", b"{}\n"), + ("runtime/releases/shared-2026.09.3/sources/vllm.patch", b"historical patch\n"), + ("runtime/releases/glm53-dflash-sircl-overlay/overlay.tar.gz", b"gzblob"), + ("runtime/sparkring/sbom.spdx.json.gz", b"sbomblob"), + ("performance/records/big-dump.json", b"benchmark dump\n"), + ("docs/architecture/overview.md", b"# doc\n"), + ): + info = tarfile.TarInfo(name=name) + info.size = len(data) + tar.addfile(info, io.BytesIO(data)) + + def run_build(include_bundle, out_dir): + seen = {"bundle_called": False} + + def run(argv, **kwargs): + if argv[:2] == ["git", "archive"]: + shutil.copyfile(source, argv[argv.index("-o") + 1]) + elif "bundle" in argv: + seen["bundle_called"] = True + Path(argv[argv.index("create") + 1]).write_bytes(b"git-bundle-bytes") + elif argv[0] == "dpkg-deb": + payload = Path(argv[-2]) / "usr/lib/sparkring" + seen["record"] = json.loads((payload / "distribution.json").read_text(encoding="utf-8")) + seen["has_bundle"] = (payload / "source.bundle").exists() + seen["verified"] = build_deb.distribution.installed(payload) + Path(argv[-1]).write_bytes(b"deb") + return SimpleNamespace(returncode=0, stdout="", stderr="") + + monkeypatch.setattr(build_deb.distribution, "identity", lambda root: "a" * 40) + monkeypatch.setattr(build_deb, "subprocess", SimpleNamespace(run=run, check_output=lambda *a, **k: "1790000000\n")) + build_deb.build(tmp_path, out_dir, version="1.0", marker="skip", include_source_bundle=include_bundle) + return seen + + # Default slim build: excludes performance/, historical release payloads, .gz archives, and source.bundle. + slim = run_build(False, tmp_path / "dist-slim") + assert slim["bundle_called"] is False + assert slim["has_bundle"] is False + assert "bundle_sha256" not in slim["record"] + assert slim["verified"]["revision"] == "a" * 40 + slim_files = set(slim["record"]["files"]) + assert "runtime/common/example.py" in slim_files + assert "spark_transport/libsircl/README.md" in slim_files + assert "profiles/catalog.json" in slim_files + assert "runtime/releases/installer-releases.json" in slim_files + assert "runtime/releases/dev-20261016/installer-image.json" in slim_files + assert "performance/records/big-dump.json" not in slim_files + assert "runtime/releases/shared-2026.09.3/sources/vllm.patch" not in slim_files + assert "runtime/releases/glm53-dflash-sircl-overlay/overlay.tar.gz" not in slim_files + assert "runtime/sparkring/sbom.spdx.json.gz" not in slim_files + assert "docs/architecture/overview.md" not in slim_files + + # Opt-in --include-source-bundle: retains full archive (including performance/) and source.bundle. + full = run_build(True, tmp_path / "dist-full") + assert full["bundle_called"] is True + assert full["has_bundle"] is True + assert full["record"]["bundle_sha256"] == sha(b"git-bundle-bytes") + assert full["verified"]["revision"] == "a" * 40 + full_files = set(full["record"]["files"]) + assert "performance/records/big-dump.json" in full_files + assert "runtime/releases/shared-2026.09.3/sources/vllm.patch" in full_files + + +def test_cli_include_source_bundle_flag_forwards_to_build(tmp_path, monkeypatch): + captured = {} + + def fake_build(root, output, *, version=None, marker="prebuilt", marker_binary=None, + include_source_bundle=False): + captured["include_source_bundle"] = include_source_bundle + return {"path": str(output / "fake.deb")} + + monkeypatch.setattr(build_deb, "build", fake_build) + assert build_deb.main(["--output", str(tmp_path), "--relay-marker", "skip"]) == 0 + assert captured["include_source_bundle"] is False + assert build_deb.main(["--output", str(tmp_path), "--relay-marker", "skip", "--include-source-bundle"]) == 0 + assert captured["include_source_bundle"] is True diff --git a/scripts/test_ci_checks.py b/scripts/test_ci_checks.py index 578d20e8..74797d82 100644 --- a/scripts/test_ci_checks.py +++ b/scripts/test_ci_checks.py @@ -153,3 +153,126 @@ def tracked(*args, **kwargs): monkeypatch.setattr(sys, "argv", ["check", str(tmp_path)]) assert markdown.main() == 0 assert safety.main(tmp_path) == 0 + + +def test_ci_workflow_has_no_orphaned_or_duplicated_python_tests(): + """Every tracked test_*.py file is either executed once in CI or explicitly ignored for external artifacts.""" + import re + import yaml + + root = Path(__file__).resolve().parents[1] + workflow_path = root / ".github/workflows/ci.yml" + workflow = yaml.safe_load(workflow_path.read_text(encoding="utf-8")) + jobs = workflow["jobs"] + + # Documented external-artifact / upstream-only exclusions that cannot run on stock CPU runners. + external_exclusions = ( + "integrations/vllm/glm53full_speedups/tests", + "integrations/vllm/glm_dsa_indexer_split/tests", + "runtime/deepseek-v41-gb10/tools/test_engram_packed.py", + "runtime/releases/shared-2026.09.0-rc.1/qualification", + "integrations/sparkcache/4a17f1f5198e/deploy/deployment_contract/test_release_hardening.py", + "integrations/sparkcache/4a17f1f5198e/sparkcache/test_deepseek_v41_topology.py", + ) + for excluded in external_exclusions: + assert (root / excluded).exists(), f"stale external exclusion: {excluded}" + + def _matches(path: str, prefix: str) -> bool: + return prefix == "." or path == prefix or path.startswith(prefix + "/") + + # Extract every pytest invocation's targets and --ignore flags from workflow steps. + invocations: list[tuple[str, list[str], list[str]]] = [] + all_ignores: set[str] = set() + for job_id, job in jobs.items(): + for idx, step in enumerate(job.get("steps", ())): + run_text = step.get("run", "") + if not run_text: + continue + # Collapse backslash line continuations so multi-line pytest commands parse cleanly. + collapsed = re.sub(r"\\\r?\n\s*", " ", run_text) + step_ignores = re.findall(r"--ignore=([^\s\"')]+)", collapsed) + all_ignores.update(step_ignores) + for line in collapsed.splitlines(): + stripped = line.strip() + if stripped.startswith("#") or "pytest" not in stripped: + continue + match = re.search(r"\bpython\s+-m\s+pytest\s+(.*)$", stripped) + if not match: + continue + tokens = match.group(1).split() + targets = [] + line_ignores = list(re.findall(r"--ignore=([^\s\"')]+)", match.group(1))) + if '"${image_tests[@]}"' in tokens: + line_ignores.extend(step_ignores) + skip_next = False + for tok in tokens: + if skip_next: + skip_next = False + continue + if tok in ("-n", "--dist", "-k", "-m"): + skip_next = True + continue + if tok.startswith("-") or tok.startswith('"${') or tok.startswith("${"): + continue + targets.append(tok) + if targets: + invocations.append((f"{job_id}[{idx}]", targets, line_ignores)) + + # Every --ignore= path in ci.yml must point to an existing file or directory. + for ignored in sorted(all_ignores): + assert (root / ignored).exists(), f"ci.yml ignores missing path: {ignored}" + + # Verify spark_transport/conftest.py ignores libsircl (covered by the libsircl CMake/make check job). + assert "libsircl" in (root / "spark_transport/conftest.py").read_text(encoding="utf-8") + assert "libsircl" in jobs + + tracked = [ + f + for f in subprocess.check_output(["git", "ls-files", "-z"], cwd=root) + .decode("utf-8", "surrogateescape") + .split("\0") + if f + ] + test_files = sorted( + f + for f in tracked + if f.endswith(".py") + and (Path(f).name.startswith("test_") or Path(f).name.endswith("_test.py")) + ) + assert test_files + + orphaned = [] + duplicated = [] + for test_file in test_files: + if _matches(test_file, "spark_transport/libsircl"): + # Covered by the libsircl job (make check / ctest). + continue + runners = [] + for label, targets, ignores in invocations: + # spark_transport/conftest.py excludes libsircl from pytest auto-discovery. + if any(_matches(test_file, ig) for ig in ignores): + continue + if any(_matches(test_file, target) for target in targets): + runners.append(label) + if not runners: + if not any(_matches(test_file, ex) for ex in external_exclusions): + orphaned.append(test_file) + elif len(runners) > 1: + duplicated.append((test_file, runners)) + + assert orphaned == [], f"Orphaned test files not covered by ci.yml: {orphaned}" + assert duplicated == [], f"Test files executed more than once across ci.yml jobs: {duplicated}" + + # Confirm SGLang tests are actively covered (not excluded). + assert any( + any(_matches("runtime/deepseek-v41-sglang/test_bounded_prefill_patch.py", t) for t in targets) + and not any(_matches("runtime/deepseek-v41-sglang/test_bounded_prefill_patch.py", ig) for ig in ignores) + for _, targets, ignores in invocations + ) + + # Confirm pytest-xdist parallelization and shellcheck job are configured. + tests_script = "\n".join(s.get("run", "") for s in jobs["tests"]["steps"]) + assert "pytest-xdist" in tests_script and "-n auto" in tests_script + shellcheck_script = "\n".join(s.get("run", "") for s in jobs["shellcheck"]["steps"]) + assert "shellcheck -S warning" in shellcheck_script + assert "install.sh" in shellcheck_script and "bootstrap.sh" in shellcheck_script diff --git a/scripts/test_glm53_flash_profile.py b/scripts/test_glm53_flash_profile.py index d6a077f1..4d9f2714 100644 --- a/scripts/test_glm53_flash_profile.py +++ b/scripts/test_glm53_flash_profile.py @@ -566,13 +566,15 @@ def test_operator_docs_state_status_invariants_and_full_provenance() -> None: def test_ci_runs_glm53_runtime_contracts() -> None: workflow = (ROOT / ".github" / "workflows" / "ci.yml").read_text(encoding="utf-8") - pytest_command = next( - line for line in workflow.splitlines() if "python -m pytest spark_transport" in line - ) - assert "runtime/exl3-r7" in pytest_command - assert "runtime/glm53-flash" in pytest_command - assert "runtime/glm53-flash-jj-r8-gb10" in pytest_command - assert "runtime/deepseek0731-gb10" in pytest_command + assert "python -m pytest . " in workflow + ignored = set(re.findall(r"--ignore=([^\s\"')]+)", workflow)) + for path in ( + "runtime/exl3-r7", + "runtime/glm53-flash", + "runtime/glm53-flash-jj-r8-gb10", + "runtime/deepseek0731-gb10", + ): + assert not any(path == ig or path.startswith(ig + "/") for ig in ignored), path def test_glm53_quickstarts_state_dynamic_depth_unsupported() -> None: diff --git a/scripts/test_release_safety.py b/scripts/test_release_safety.py index a985849b..3bb6ab2b 100644 --- a/scripts/test_release_safety.py +++ b/scripts/test_release_safety.py @@ -90,3 +90,126 @@ def test_the_site_value_allowlist_names_only_frozen_inputs(): frozen = (Path(__file__).resolve().parents[1] / "runtime/releases/preserved-inputs.json").read_text(encoding="utf-8") for path, lines in SITE_VALUE_ALLOWED.items(): assert f'"{path}"' in frozen and all(isinstance(line, int) and reason for line, reason in lines.items()) + + +def test_bare_private_10_addresses_are_findings(): + # Assembled from pieces so that this test file holds no 10.x.x.x literal. + ten = "10" + for text in ( + f"host = {ten}.0.0.5", + f"server {ten}.42.1.19:8000", + f'"{ten}.253.255.20"', + ): + assert (1, "private-lan-address") in findings(text), text + # SparkRing's built-in default admin CIDR (10.253.255.0/28) and non-IPv4 tokens are not findings. + for text in ( + f"default {ten}.253.255.0/29", + f"admin {ten}.253.255.2", + f"version 2{ten}.1.2.3", + f"invalid {ten}.999.1.1", + f"dotted {ten}.1.2.3.4", + ): + assert (1, "private-lan-address") not in findings(text), text + # Per-file allowlist permits only its exact literals; another 10.x.x.x on the same line still fires. + allowed = frozenset({f"{ten}.0.0.1"}) + assert list(findings(f"ok {ten}.0.0.1", allowed_private_10=allowed)) == [] + assert (1, "private-lan-address") in findings(f"ok {ten}.0.0.1 bad {ten}.50.0.2", allowed_private_10=allowed) + + +def test_provider_secret_tokens_are_findings(): + # Assembled from pieces so that this test file holds no token literal. + hf_tok = "hf" + "_" + "A1b2C3d4E5f6G7h8I9j0K1" + sk_tok = "sk" + "-" + "proj_0123456789abcdef012345" + aws_tok = "AK" + "IA" + "IOSFODNN7EXAMPLE" + for text in (f"export HF_TOKEN={hf_tok}", f'"{sk_tok}"', f"key={aws_tok}"): + assert (1, "provider-token") in findings(text), text + # Word prefixes, lowercase AWS prefixes, and short strings are not findings. + for text in ( + "disk" + "-0123456789abcdef0123456789", + "ak" + "ia" + "0123456789abcdef", + "hf" + "_short", + "sk" + "-short", + ): + assert (1, "provider-token") not in findings(text), text + + +def test_gz_and_tar_gz_archives_are_scanned_with_bomb_bounds(tmp_path, monkeypatch, capsys): + import gzip + import io + import subprocess + import tarfile + import check_release_safety as safety + + hf_tok = "hf" + "_" + "Z9y8X7w6V5u4T3s2R1q0P9" + ten_ip = "10" + ".88.77.66" + + # Plain .gz text member with a secret token is caught without disclosing the token. + gz_path = tmp_path / "fixture.txt.gz" + gz_path.write_bytes(gzip.compress(f"line1\ntoken={hf_tok}\n".encode("utf-8"))) + + # .tar.gz with a clean text member, a binary member, and a member leaking a 10.x.x.x IP. + tgz_path = tmp_path / "bundle.tar.gz" + with tarfile.open(tgz_path, "w:gz") as tf: + for name, raw in ( + ("clean.txt", b"nothing sensitive here\n"), + ("blob.bin", b"\x00\x01\x02" + ten_ip.encode("utf-8")), + ("nested/conf.txt", f"endpoint={ten_ip}\n".encode("utf-8")), + ): + info = tarfile.TarInfo(name=name) + info.size = len(raw) + tf.addfile(info, io.BytesIO(raw)) + + tracked = b"fixture.txt.gz\0bundle.tar.gz\0" + monkeypatch.setattr( + safety.subprocess, + "run", + lambda *a, **k: subprocess.CompletedProcess(a, 0, tracked, b""), + ) + assert safety.main(tmp_path) == 1 + out = capsys.readouterr().out + assert hf_tok not in out and ten_ip not in out + records = [json.loads(line) for line in out.splitlines() if line.startswith("{")] + assert {"path": "fixture.txt.gz", "line": 2, "rule": "provider-token"} in records + assert {"path": "bundle.tar.gz!nested/conf.txt", "line": 1, "rule": "private-lan-address"} in records + assert all("blob.bin" not in r["path"] for r in records) + + # Bounded decompression refuses oversized payloads fail-closed. + bomb = gzip.compress(b"A" * 4096) + try: + list(safety.iter_text_members("bomb.txt.gz", bomb, member_limit=1024)) + except safety.ArchiveLimitError: + pass + else: + raise AssertionError("Expected ArchiveLimitError for oversized gzip member") + + # Corrupt .gz fails closed with exit status 2. + (tmp_path / "corrupt.gz").write_bytes(b"not-a-valid-gzip-stream") + monkeypatch.setattr( + safety.subprocess, + "run", + lambda *a, **k: subprocess.CompletedProcess(a, 0, b"corrupt.gz\0", b""), + ) + assert safety.main(tmp_path) == 2 + + +def test_spdx_normalization_avoids_version_false_positives_but_catches_real_leaks(): + ten = "10" + clean_spdx = json.dumps({ + "spdxVersion": "SPDX-2.3", + "packages": [{ + "name": "libcurand-13-0", + "versionInfo": f"{ten}.4.0.35-1", + "externalRefs": [ + {"referenceLocator": f"pkg:deb/ubuntu/libcurand-13-0@{ten}.4.0.35-1?arch=arm64"}, + {"referenceLocator": "cpe:2.3:a:" + "secret" + ":" + "secret-service:5.1.0:*:*:*:*:rust:*:*"}, + ], + }], + }) + assert list(findings(clean_spdx)) == [] + + hf_tok = "hf" + "_" + "A1b2C3d4E5f6G7h8I9j0K1" + leaked_spdx = json.dumps({ + "spdxVersion": "SPDX-2.3", + "packages": [{"name": "pkg", "downloadLocation": f"https://{hf_tok}@example.invalid"}], + }) + assert (1, "provider-token") in findings(leaked_spdx) diff --git a/spark_transport/README.md b/spark_transport/README.md index bcfdf5f3..09ed3933 100644 --- a/spark_transport/README.md +++ b/spark_transport/README.md @@ -1,9 +1,12 @@ # Spark Transport -`spark_transport` is SparkRing's communication layer for inference over directly -connected RDMA over Converged Ethernet (RoCE) links. It contains native -collectives, runtime adapters, patched NCCL integration, and tools for checking -the fabric and collective protocols. +`spark_transport` is SparkRing's switchless RDMA communication layer for +directly connected ConnectX-7 RoCE fabrics across two to eight DGX Sparks. Its +primary transport is **[`libsircl/`](libsircl/README.md)** (Gen 4), a drop-in +`libnccl.so.2` C library with embedded CUDA kernel packs that accelerates vLLM, +SGLang, and PyTorch `ProcessGroupNCCL` workloads on pairs, paths, and rings. +Earlier generations (`sircl/`, `src/`, `nccl/`) remain in this tree to support +route planning, retained images, and legacy profiles. The transport exchanges tensor buffers between ranks. Model profiles select the runtime adapter, tensor signatures, topology, and verified artifacts needed @@ -18,13 +21,14 @@ Hardware-forwarded mesh composition and six-node model profiles remain ## Communication components -| Component | Purpose | Implementation and contract | -|---|---|---| -| **SIRCL — Switchless Inference RDMA Collective Layer: four-rank native sessions** | Collectives for exactly four ranks on a four-Spark cycle, with persistent RDMA sessions, CUDA-graph submission, and eager prefill paths; kept for retained images and profiles. | [SIRCL overview](../docs/SIRCL.md), [C/C++ interfaces](include/spark_transport/), and [native source](src/) | -| **SIRCL ring sessions** | SIRCL's default session generation: collectives for groups of 2 to 8 Sparks on pairs, paths and cycles, independent groups on one fabric and DCP subgroups, with NIC relays for members that share no cable; a vLLM adapter, a serve launcher and a standalone ring harness. Status per component: [status table](sircl/STATUS.md#component-status). | [Ring sessions](sircl/README.md) and their [design section](../docs/architecture/sircl.md#ring-sessions) | -| **RoCEnante integration** | Selected all-reduces over direct and hardware-forwarded opposite-peer paths in the four-rank mesh composition. | [Runtime overlay](../integrations/vllm/rocenante/README.md) and [adapted Local Inference Lab source and attribution](../third_party/b12x_roce/README.md) | -| **Patched NVIDIA NCCL** | Pair/cycle communication and fallback for collectives outside custom transport admission. Some model profiles use NCCL for all their collectives. | [Library patches, topology-specific environments, and invariants](nccl/README.md) | -| **Runtime adapters** | Select a collective implementation by process group, tensor geometry, execution mode, and enabled profile capabilities. | [vLLM adapter contract](../integrations/vllm/README.md) and [mesh composition](../runtime/glm53-spark-mtp3-mesh/README.md) | +| Component | Generation / role | Purpose | Implementation and contract | +|---|---|---|---| +| **[`libsircl`](libsircl/README.md)** | **Primary (Gen 4)** | Drop-in `libnccl.so.2` C library with embedded CUDA kernel packs for pair, chain, and ring collectives plus point-to-point channels over RoCE verbs (and shared-memory emulation for single-GPU testing); powers stock vLLM, SGLang, and PyTorch `ProcessGroupNCCL`. | [`libsircl/README.md`](libsircl/README.md) and [status](libsircl/STATUS.md) | +| **SIRCL ring sessions** | Legacy (Gen 3) | Python/C ring-session package (`sparkring_sircl`) for 2 to 8 Sparks on pairs, paths, and cycles, with route planning, standalone ring harness, and vLLM adapter. Status per component: [status table](sircl/STATUS.md#component-status). | [Ring sessions](sircl/README.md) and their [design section](../docs/architecture/sircl.md#ring-sessions) | +| **SIRCL four-rank native sessions** | Legacy (Gen 2) | Collectives for exactly four ranks on a four-Spark cycle (`libspark_transport_capi.so`), with persistent RDMA sessions, CUDA-graph submission, and eager prefill paths; kept for retained images and profiles. | [SIRCL overview](../docs/SIRCL.md), [C/C++ interfaces](include/spark_transport/), and [native source](src/) | +| **Patched NVIDIA NCCL** | Legacy (Gen 1) | Pair/cycle NCCL patches and topology-specific environments for profiles that use patched NCCL directly or as fallback outside custom transport admission. | [Library patches, topology-specific environments, and invariants](nccl/README.md) | +| **RoCEnante integration** | Specialized mesh | Selected all-reduces over direct and hardware-forwarded opposite-peer paths in the four-rank mesh composition. | [Runtime overlay](../integrations/vllm/rocenante/README.md) and [adapted Local Inference Lab source and attribution](../third_party/b12x_roce/README.md) | +| **Runtime adapters** | Integration | Select a collective implementation by process group, tensor geometry, execution mode, and enabled profile capabilities. | [vLLM adapter contract](../integrations/vllm/README.md) and [mesh composition](../runtime/glm53-spark-mtp3-mesh/README.md) | SIRCL's native library is `libspark_transport_capi.so`. It provides BF16 all-reduce and specialized vocabulary all-gather interfaces. Its native @@ -91,25 +95,39 @@ instructions belong to the selected [profile quickstart](../docs/profiles/README ## Directory map -| Path | Contents | -|---|---| -| [`include/spark_transport/`](include/spark_transport/) | Public C/C++ interfaces and protocol contracts | -| [`sircl/`](sircl/) | SIRCL ring sessions: Python package `sparkring_sircl`, its native progress thread, CPU simulator and ring harness (`pyproject.toml`, `RUNBOOK.md`) | -| [`src/`](src/) | Sessions, verbs endpoints, CUDA operations, command rings, and topology checks | -| [`../integrations/vllm/`](../integrations/vllm/) | Maintained vLLM tensor admission, dispatch, and native-session checks; `spark_transport/integrations/vllm/` contains compatibility exports | -| [`nccl/`](nccl/) | Patched NCCL configuration and compatibility requirements | -| [`app/`](app/) and [`scripts/`](scripts/) | Collective probes and cable/rank qualification tools | -| [`tests/`](tests/) | Protocol, ABI, configuration, and source-contract checks | -| [`fabric/`](fabric/) | Maintained hardware-forwarding topology and planning | -| [`experiments/`](experiments/) | Transport variants and retained experimental interfaces | - -Selected kernels under `experiments/tiled_prefill/` are linked into the native -library by [CMakeLists.txt](CMakeLists.txt). Directory placement alone does not -identify whether code participates in a serving artifact; use its build -targets and profile receipts. +| Path | Role | Contents | +|---|---|---| +| [`libsircl/`](libsircl/) | **Primary (Gen 4)** | Drop-in `libnccl.so.2` C library, embedded CUDA kernel packs, RoCE verbs & emulation transports, MPI shim, and Make/CMake CPU test suites ([README](libsircl/README.md)) | +| [`fabric/`](fabric/) | Maintained host fabric | Hardware-forwarding topology, relay-table planning, and `relay_marker.c` | +| [`../integrations/vllm/`](../integrations/vllm/) | Maintained adapters | Framework tensor admission, dispatch, and native-session checks (`spark_transport/integrations/vllm/` holds compatibility exports) | +| [`sircl/`](sircl/) | Legacy (Gen 3) | SIRCL ring sessions: Python package `sparkring_sircl`, route planner, native progress thread, CPU simulator, and ring harness (`pyproject.toml`, `RUNBOOK.md`) | +| [`src/`](src/) and [`include/spark_transport/`](include/spark_transport/) | Legacy (Gen 2) | Four-rank native `libspark_transport_capi.so` sessions, verbs endpoints, CUDA operations, command rings, and public C/C++ interfaces | +| [`nccl/`](nccl/) | Legacy (Gen 1) | Patched NVIDIA NCCL source patches, topology configurations, and compatibility probes | +| [`app/`](app/) and [`scripts/`](scripts/) | Probes & tools | Collective probes and cable/rank qualification tools | +| [`tests/`](tests/) | Contract tests | Protocol, ABI, configuration, and source-contract checks | +| [`experiments/`](experiments/) | Retained kernels | Transport variants and retained experimental interfaces linked into legacy targets | + +Selected kernels under `experiments/tiled_prefill/` are linked into the legacy +Gen-2 native library by [CMakeLists.txt](CMakeLists.txt). Directory placement +alone does not identify whether code participates in a serving artifact; use +its build targets and profile receipts. ## Build and validation +### Primary Gen-4 drop-in (`libsircl`) + +On a Linux host with `gcc`, `libibverbs-dev`, and `nvcc` 13.3: + +```bash +make -C spark_transport/libsircl -j BUILD=build +make -C spark_transport/libsircl check BUILD=build +``` + +See [`libsircl/README.md`](libsircl/README.md) for CMake builds, ASan checks, +and single-GPU emulation runs. + +### Legacy Gen-2 native library (`libspark_transport_capi.so`) + Run these commands from the repository root on an ARM64 CUDA environment with CMake, a C++17 compiler, and libibverbs development headers: