WIP: STRA-104: Read Qwen tokenizer metadata from GGUF #1

Closed
admin wants to merge 58 commits from codex/stra-104-gguf-tokenizer into main
35 changed files with 17672 additions and 2924 deletions
+196 -144
View File
@@ -15,8 +15,8 @@ on:
description: Build actual CUDA package on isolated hosted CPU (no GPU, private artifact)
type: boolean
default: false
static_cuda_package:
description: Build and audit static CUDA toolkit linkage on the private Linux runner (no inference)
changed_scope_coverage:
description: Run exact changed-production Rust line, function and branch coverage on Linux CPU
type: boolean
default: false
@@ -25,105 +25,76 @@ permissions:
jobs:
verify:
runs-on: ubuntu-24.04
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262
# The configured Gitea ubuntu-latest label runs a root node:24-bookworm job container;
# sudo is not installed there, so install packages directly.
- name: Install build tools
run: sudo apt-get update && sudo apt-get install -y cmake ninja-build g++ python3-numpy
run: apt-get update && apt-get install -y ca-certificates curl cmake ninja-build g++ python3-numpy
- name: Install pinned Rust
run: rustup toolchain install 1.99.0 --profile minimal --component rustfmt --component clippy
run: |
scripts/install-pinned-rustup.sh rustup toolchain install 1.99.0 --profile minimal --component rustfmt --component clippy
- name: Local checks
run: scripts/check-local.sh
changed-scope-coverage:
if: github.event_name == 'workflow_dispatch' && inputs.changed_scope_coverage
needs: verify
runs-on: ubuntu-latest
timeout-minutes: 120
permissions:
contents: read
steps:
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262
with:
fetch-depth: 0
- name: Install parser runtime
run: apt-get update && apt-get install -y ca-certificates curl python3
- name: Install pinned Rust nightly with LLVM coverage tools
run: |
scripts/install-pinned-rustup.sh rustup toolchain install nightly-2026-10-05 --profile minimal --component llvm-tools-preview
- name: Test coverage parser and workflow contract
run: python3 scripts/test-changed-scope-coverage.py
- name: Run exact changed-production coverage gate
run: python3 scripts/check-changed-scope-coverage.py --root "$GITHUB_WORKSPACE" --output-dir "$RUNNER_TEMP/changed-scope-coverage"
keyless-cuda:
if: github.event_name == 'workflow_dispatch' && inputs.keyless_gpu
if: github.event_name == 'workflow_dispatch' && github.event.inputs.keyless_gpu == 'true'
needs: verify
runs-on: [self-hosted, linux, x64, strata-gpu]
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262
- name: Query-routing, streaming and snapshot GPU tests
run: scripts/check-keyless-gpu.sh
- name: Bounded KAR expert component GPU tests
run: scripts/check-kar-expert-gpu.sh
static-cuda-package:
if: github.event_name == 'workflow_dispatch' && inputs.static_cuda_package && github.event.repository.private
needs: verify
runs-on: [self-hosted, linux, x64, strata-gpu]
steps:
- uses: actions/checkout@v4
- name: Build and audit engine without GPU inference
env:
CUDA_VISIBLE_DEVICES: ''
BUILD_JOBS: '2'
STRATA_BUILD_DIR: ${{ runner.temp }}/strata-static-cuda-${{ github.run_id }}
run: nice -n 10 scripts/build-static-cuda.sh
- name: Install pinned Rust and musl target
run: |
rustup toolchain install 1.99.0 --profile minimal
rustup target add --toolchain 1.99.0 x86_64-unknown-linux-musl
command -v musl-gcc
- name: Assemble combined private package
run: |
engine="${RUNNER_TEMP}/strata-static-cuda-${GITHUB_RUN_ID}/strata"
python3 scripts/build-linux-package.py --engine "$engine" \
--sha256 "$(sha256sum "$engine" | cut -d ' ' -f 1)" --revision "$GITHUB_SHA" \
--cargo-target-dir "${RUNNER_TEMP}/strata-package-build-${GITHUB_RUN_ID}" \
--output "${RUNNER_TEMP}/strata-package-${GITHUB_RUN_ID}"
- name: Build compatible private runtime image without GPU inference
run: |
package="${RUNNER_TEMP}/strata-package-${GITHUB_RUN_ID}"
python3 scripts/build-runtime-image.py --package "$package" \
--receipt-sha256 "$(sha256sum "$package/SHA256SUMS" | cut -d ' ' -f 1)" \
> "${RUNNER_TEMP}/strata-image-${GITHUB_RUN_ID}.json"
image="$(python3 -c 'import json,sys; print(json.load(open(sys.argv[1]))["image"])' "${RUNNER_TEMP}/strata-image-${GITHUB_RUN_ID}.json")"
docker save --output "$package/runtime-image.tar" "$image"
cp "${RUNNER_TEMP}/strata-image-${GITHUB_RUN_ID}.json" "$package/IMAGE-PROVENANCE.json"
(cd "$package" && sha256sum runtime-image.tar IMAGE-PROVENANCE.json > IMAGE-SHA256SUMS)
- uses: actions/upload-artifact@v4
with:
name: strata-next-static-cuda-preview
path: ${{ runner.temp }}/strata-package-${{ github.run_id }}/
if-no-files-found: error
retention-days: 7
- name: Remove uploaded package copy
run: rm -rf -- "${RUNNER_TEMP}/strata-package-${GITHUB_RUN_ID}"
- name: Remove owned runtime image
if: always()
run: |
receipt="${RUNNER_TEMP}/strata-image-${GITHUB_RUN_ID}.json"
if test -s "$receipt"; then
image="$(python3 -c 'import json,sys; print(json.load(open(sys.argv[1]))["image"])' "$receipt")"
docker image rm "$image"
rm "$receipt"
fi
- name: Remove private build intermediates
if: always()
run: rm -rf -- "${RUNNER_TEMP}/strata-static-cuda-${GITHUB_RUN_ID}" "${RUNNER_TEMP}/strata-package-build-${GITHUB_RUN_ID}"
hosted-cuda-package:
if: github.event_name == 'workflow_dispatch' && inputs.hosted_cuda_package && github.event.repository.private
needs: verify
runs-on: ubuntu-24.04
runs-on: ubuntu-latest
timeout-minutes: 150
permissions:
contents: read
releases: write
env:
CUDA_VISIBLE_DEVICES: ''
BUILD_JOBS: '1'
CARGO_BUILD_JOBS: '2'
CUDA_ARCHITECTURES: '120'
steps:
- uses: actions/checkout@v4
- name: Install compatible host tools (no drivers)
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262
- name: Install Docker and package tools (no drivers)
run: |
echo "CUDACXX=$RUNNER_TEMP/strata-cuda-toolkit/bin/nvcc" >> "$GITHUB_ENV"
echo "CUDAToolkit_ROOT=$RUNNER_TEMP/strata-cuda-toolkit" >> "$GITHUB_ENV"
echo "STRATA_BUILD_DIR=$RUNNER_TEMP/strata-hosted-cuda-engine" >> "$GITHUB_ENV"
sudo apt-get update && sudo apt-get install -y gcc-13 g++-13 cmake ninja-build musl-tools binutils
apt-get update && apt-get install -y ca-certificates curl docker.io musl-tools binutils python3-numpy time
- name: Assemble pinned build-only CUDA components
run: python3 scripts/bootstrap-cuda-toolkit.py --output "$CUDAToolkit_ROOT"
- name: Record actual toolchain
run: |
"$CUDACXX" --version
g++-13 --version
df -h "$RUNNER_TEMP"
free -h
python3 - <<'PYTOOL'
@@ -131,21 +102,20 @@ jobs:
from pathlib import Path
info=json.loads((Path(os.environ['CUDAToolkit_ROOT'])/'TOOLKIT-PROVENANCE.json').read_text())
info.update(source=os.environ['GITHUB_SHA'], runner_os=platform.platform(),
gcc=subprocess.check_output(['g++-13','--version'],text=True),
nvcc=subprocess.check_output([os.environ['CUDACXX'],'--version'],text=True),
cuda_architectures=os.environ['CUDA_ARCHITECTURES'], driver_tested=False, model_tested=False)
(Path(os.environ['RUNNER_TEMP'])/'CUDA-TOOLCHAIN.json').write_text(json.dumps(info,indent=2)+'\n')
PYTOOL
- name: Build actual static CUDA engine and audit without GPU
env:
CC: gcc-13
CXX: g++-13
CUDAHOSTCXX: g++-13
run: scripts/build-static-cuda.sh
- name: Compile and audit actual CUDA engine in CPU-only Docker
run: |
python3 scripts/build-cuda-engine-in-docker.py \
--toolkit "$CUDAToolkit_ROOT" \
--build-dir "$RUNNER_TEMP/strata-hosted-cuda-build" \
--output "$STRATA_BUILD_DIR/strata" \
--metadata "$RUNNER_TEMP/strata-hosted-cuda-metadata/CUDA-BUILDER.json" \
--image-tag "${GITHUB_RUN_ID}-${GITHUB_RUN_ATTEMPT}"
- name: Install pinned Rust and musl target
run: |
rustup toolchain install 1.99.0 --profile minimal
rustup target add --toolchain 1.99.0 x86_64-unknown-linux-musl
scripts/install-pinned-rustup.sh rustup toolchain install 1.99.0 --profile minimal --target x86_64-unknown-linux-musl
- name: Assemble actual combined executable and runtime image
run: |
# Keep resource evidence even if the hosted runner terminates this job.
@@ -161,23 +131,36 @@ jobs:
package="$RUNNER_TEMP/strata-hosted-cuda-package"
/usr/bin/time -v python3 scripts/build-linux-package.py --engine "$engine" \
--sha256 "$(sha256sum "$engine" | cut -d ' ' -f 1)" --revision "$GITHUB_SHA" \
--cargo-target-dir "$RUNNER_TEMP/strata-hosted-package-build" --output "$package"
--cargo-target-dir "$RUNNER_TEMP/strata-hosted-package-build" --output "$package" \
--defer-engine-help-probe-to-runtime-image
python3 scripts/build-runtime-image.py --package "$package" \
--receipt-sha256 "$(sha256sum "$package/SHA256SUMS" | cut -d ' ' -f 1)" \
> "$RUNNER_TEMP/strata-hosted-image.json"
image="$(python3 -c 'import json,sys; print(json.load(open(sys.argv[1]))["image"])' "$RUNNER_TEMP/strata-hosted-image.json")"
docker save --output "$package/runtime-image.tar" "$image"
cp "$RUNNER_TEMP/strata-hosted-image.json" "$package/IMAGE-PROVENANCE.json"
cp "$RUNNER_TEMP/CUDA-TOOLCHAIN.json" "$package/CUDA-TOOLCHAIN.json"
python3 - "$RUNNER_TEMP/CUDA-TOOLCHAIN.json" "$RUNNER_TEMP/strata-hosted-cuda-metadata/CUDA-BUILDER.json" "$package/CUDA-TOOLCHAIN.json" <<'PYTOOL'
import json, sys
from pathlib import Path
bootstrap=json.loads(Path(sys.argv[1]).read_text())
builder=json.loads(Path(sys.argv[2]).read_text())
bootstrap['docker_builder']=builder
Path(sys.argv[3]).write_text(json.dumps(bootstrap,indent=2)+'\n')
PYTOOL
tar -C "$CUDAToolkit_ROOT" -cf "$package/CUDA-LICENSES.tar" licenses
(cd "$package" && sha256sum runtime-image.tar IMAGE-PROVENANCE.json CUDA-TOOLCHAIN.json CUDA-LICENSES.tar > IMAGE-SHA256SUMS)
- uses: actions/upload-artifact@v4
with:
name: strata-next-hosted-cuda-preview
path: ${{ runner.temp }}/strata-hosted-cuda-package/
if-no-files-found: error
retention-days: 7
- name: Remove uploaded package copy
- name: Publish private CUDA preview release
env:
GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }}
GITHUB_API_URL: ${{ github.api_url }}
run: |
tag="cuda-preview-${GITHUB_RUN_ID}-${GITHUB_RUN_ATTEMPT}"
python3 scripts/publish-gitea-release.py \
--tag "$tag" --target "$GITHUB_SHA" \
--title "CUDA build preview ${GITHUB_RUN_ID}.${GITHUB_RUN_ATTEMPT}" \
--notes 'Actual CUDA compilation and packaging from this commit. Built in a GPU-hidden Docker container. This is not driver, inference, model-quality or performance qualification.' \
--directory "$RUNNER_TEMP/strata-hosted-cuda-package"
- name: Remove privately published package copy
run: rm -rf -- "$RUNNER_TEMP/strata-hosted-cuda-package"
- name: Remove owned intermediate image and build files
if: always()
@@ -185,26 +168,31 @@ jobs:
receipt="$RUNNER_TEMP/strata-hosted-image.json"
if test -s "$receipt"; then
image="$(python3 -c 'import json,sys; print(json.load(open(sys.argv[1]))["image"])' "$receipt")"
docker image rm "$image"
docker image rm "$image" || true
fi
rm -rf -- "$RUNNER_TEMP/strata-cuda-toolkit" "$RUNNER_TEMP/strata-hosted-cuda-engine" "$RUNNER_TEMP/strata-hosted-package-build"
builder_label="leleka.cuda-builder.run=${GITHUB_RUN_ID}-${GITHUB_RUN_ATTEMPT}"
if command -v docker >/dev/null 2>&1; then
docker ps -aq --filter "label=$builder_label" | xargs -r docker rm -f || true
docker volume ls -q --filter "label=$builder_label" | xargs -r docker volume rm --force || true
docker image ls -q --filter "label=$builder_label" | sort -u | xargs -r docker image rm || true
fi
rm -rf -- "$RUNNER_TEMP/strata-cuda-toolkit" "$RUNNER_TEMP/strata-hosted-cuda-engine" "$RUNNER_TEMP/strata-hosted-cuda-build" "$RUNNER_TEMP/strata-hosted-cuda-metadata" "$RUNNER_TEMP/strata-hosted-package-build"
linux-static-cli:
needs: verify
runs-on: ubuntu-24.04
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262
- name: Install musl toolchain
run: sudo apt-get update && sudo apt-get install -y musl-tools cmake binutils python3-numpy
run: apt-get update && apt-get install -y ca-certificates curl docker.io musl-tools cmake binutils python3-numpy
- name: Install pinned Rust and target
run: |
rustup toolchain install 1.99.0 --profile minimal
rustup target add --toolchain 1.99.0 x86_64-unknown-linux-musl
scripts/install-pinned-rustup.sh rustup toolchain install 1.99.0 --profile minimal --target x86_64-unknown-linux-musl
- name: Build static CLI
run: cargo build --manifest-path control-plane/Cargo.toml --locked --release --target x86_64-unknown-linux-musl --bin strata-next
- name: Verify ELF and checksum
run: |
binary=control-plane/target/x86_64-unknown-linux-musl/release/strata-next
binary=target/x86_64-unknown-linux-musl/release/strata-next
if readelf -l "$binary" | grep -q INTERP; then
echo 'ELF has a dynamic interpreter' >&2
exit 1
@@ -232,69 +220,103 @@ jobs:
cd dist
sha256sum strata-next-linux-x86_64-musl BUILD-PROVENANCE.txt ELF-AUDIT.txt > SHA256SUMS
- name: Static CLI model smoke
run: python3 scripts/smoke-static-cli.py control-plane/target/x86_64-unknown-linux-musl/release/strata-next
run: python3 scripts/smoke-static-cli.py target/x86_64-unknown-linux-musl/release/strata-next
- name: Engine loader probe before model acquisition
run: python3 scripts/smoke-engine-probe.py control-plane/target/x86_64-unknown-linux-musl/release/strata-next
run: python3 scripts/smoke-engine-probe.py target/x86_64-unknown-linux-musl/release/strata-next
- name: Explicit GPU profile driver policy without GPU
run: python3 scripts/smoke-gpu-requirement.py control-plane/target/x86_64-unknown-linux-musl/release/strata-next
run: python3 scripts/smoke-gpu-requirement.py target/x86_64-unknown-linux-musl/release/strata-next
- name: Declared GPU memory admission and child UUID pin without GPU
run: python3 scripts/smoke-cuda-memory.py control-plane/target/x86_64-unknown-linux-musl/release/strata-next
run: python3 scripts/smoke-cuda-memory.py target/x86_64-unknown-linux-musl/release/strata-next
- name: Atomic pinned assets before native serving
run: python3 scripts/smoke-asset-bootstrap.py control-plane/target/x86_64-unknown-linux-musl/release/strata-next
run: python3 scripts/smoke-asset-bootstrap.py target/x86_64-unknown-linux-musl/release/strata-next
- name: Native GGUF pack preparation against upstream oracle
run: python3 scripts/smoke-native-pack.py control-plane/target/x86_64-unknown-linux-musl/release/strata-next
run: python3 scripts/smoke-native-pack.py target/x86_64-unknown-linux-musl/release/strata-next
- name: Native fetch prepare serve and verified offline reuse
run: python3 scripts/smoke-native-bootstrap.py control-plane/target/x86_64-unknown-linux-musl/release/strata-next
run: python3 scripts/smoke-native-bootstrap.py target/x86_64-unknown-linux-musl/release/strata-next
- name: Pinned MTP structural preflight and native bootstrap
run: python3 scripts/smoke-mtp-pack.py control-plane/target/x86_64-unknown-linux-musl/release/strata-next
run: python3 scripts/smoke-mtp-pack.py target/x86_64-unknown-linux-musl/release/strata-next
- name: Native runtime profile metadata admission
run: python3 scripts/smoke-runtime-profile.py control-plane/target/x86_64-unknown-linux-musl/release/strata-next
- name: Native systemd unit syntax and path safety
run: python3 scripts/smoke-service-unit.py control-plane/target/x86_64-unknown-linux-musl/release/strata-next
- name: Native installer with actual isolated systemd user service
run: python3 scripts/smoke-runtime-profile.py target/x86_64-unknown-linux-musl/release/strata-next
- name: Native systemd unit and lifecycle tests in isolated container
run: |
uid=$(id -u)
sudo systemctl start "user@$uid.service"
export XDG_RUNTIME_DIR="/run/user/$uid"
export DBUS_SESSION_BUS_ADDRESS="unix:path=$XDG_RUNTIME_DIR/bus"
python3 scripts/smoke-service-unit.py control-plane/target/x86_64-unknown-linux-musl/release/strata-next --lifecycle
python3 scripts/smoke-native-switch.py control-plane/target/x86_64-unknown-linux-musl/release/strata-next
image="leleka-systemd-smoke:${GITHUB_RUN_ID}"
container="leleka-systemd-smoke-${GITHUB_RUN_ID}"
cleanup() {
docker rm --force "$container" >/dev/null 2>&1 || true
docker image rm "$image" >/dev/null 2>&1 || true
}
trap cleanup EXIT
docker build --file deploy/Dockerfile.systemd-smoke --tag "$image" .
docker run --detach --privileged --cgroupns=private --name "$container" \
--tmpfs /run --tmpfs /run/lock \
--stop-signal SIGRTMIN+3 "$image"
for attempt in $(seq 1 30); do
if docker exec "$container" systemctl show-environment >/dev/null 2>&1; then break; fi
test "$attempt" -lt 30 || { docker logs "$container"; exit 1; }
sleep 1
done
uid=1000
docker exec "$container" systemctl start "user@$uid.service"
for attempt in $(seq 1 30); do
if docker exec "$container" test -S "/run/user/$uid/bus"; then break; fi
test "$attempt" -lt 30 || { docker logs "$container"; exit 1; }
sleep 1
done
docker cp target/x86_64-unknown-linux-musl/release/strata-next "$container:/tmp/strata-next"
docker cp scripts/smoke-service-unit.py "$container:/tmp/smoke-service-unit.py"
docker cp scripts/smoke-native-switch.py "$container:/tmp/smoke-native-switch.py"
docker cp scripts/smoke-worker-cancel.py "$container:/tmp/smoke-worker-cancel.py"
docker exec --user "$uid" \
--env HOME=/home/leleka \
--env XDG_RUNTIME_DIR="/run/user/$uid" \
--env DBUS_SESSION_BUS_ADDRESS="unix:path=/run/user/$uid/bus" \
"$container" python3 /tmp/smoke-service-unit.py /tmp/strata-next
docker exec --user "$uid" \
--env HOME=/home/leleka \
--env XDG_RUNTIME_DIR="/run/user/$uid" \
--env DBUS_SESSION_BUS_ADDRESS="unix:path=/run/user/$uid/bus" \
"$container" python3 /tmp/smoke-service-unit.py /tmp/strata-next --lifecycle
docker exec --user "$uid" \
--env HOME=/home/leleka \
--env XDG_RUNTIME_DIR="/run/user/$uid" \
--env DBUS_SESSION_BUS_ADDRESS="unix:path=/run/user/$uid/bus" \
"$container" python3 /tmp/smoke-native-switch.py /tmp/strata-next
- name: Native deployment configuration without worker launch
run: python3 scripts/smoke-config-check.py control-plane/target/x86_64-unknown-linux-musl/release/strata-next
run: python3 scripts/smoke-config-check.py target/x86_64-unknown-linux-musl/release/strata-next
- name: Native deployment readiness deadline without GPU
run: python3 scripts/smoke-wait-ready.py control-plane/target/x86_64-unknown-linux-musl/release/strata-next
run: python3 scripts/smoke-wait-ready.py target/x86_64-unknown-linux-musl/release/strata-next
- name: Native API authentication without GPU
run: python3 scripts/smoke-native-auth.py control-plane/target/x86_64-unknown-linux-musl/release/strata-next
run: python3 scripts/smoke-native-auth.py target/x86_64-unknown-linux-musl/release/strata-next
- name: Native custom text and regex tools without GPU
run: python3 scripts/smoke-custom-tools.py control-plane/target/x86_64-unknown-linux-musl/release/strata-next
run: python3 scripts/smoke-custom-tools.py target/x86_64-unknown-linux-musl/release/strata-next
- name: Native auto/none/required/forced tool policy without GPU
run: python3 scripts/smoke-tool-policy.py control-plane/target/x86_64-unknown-linux-musl/release/strata-next
run: python3 scripts/smoke-tool-policy.py target/x86_64-unknown-linux-musl/release/strata-next
- name: Live Responses replay and corrupt SSE evidence without GPU
run: PYTHONDONTWRITEBYTECODE=1 python3 scripts/test-live-responses-replay.py control-plane/target/x86_64-unknown-linux-musl/release/strata-next
run: PYTHONDONTWRITEBYTECODE=1 python3 scripts/test-live-responses-replay.py target/x86_64-unknown-linux-musl/release/strata-next
- name: Input token count exact GEN wire parity without inference
run: python3 scripts/smoke-input-tokens.py control-plane/target/x86_64-unknown-linux-musl/release/strata-next
run: python3 scripts/smoke-input-tokens.py target/x86_64-unknown-linux-musl/release/strata-next
- name: Chat Completions live protocol and wire parity
run: python3 scripts/smoke-chat-completions.py control-plane/target/x86_64-unknown-linux-musl/release/strata-next
run: python3 scripts/smoke-chat-completions.py target/x86_64-unknown-linux-musl/release/strata-next
- name: Messages named SSE and tool protocol without GPU
run: python3 scripts/smoke-messages.py control-plane/target/x86_64-unknown-linux-musl/release/strata-next
run: python3 scripts/smoke-messages.py target/x86_64-unknown-linux-musl/release/strata-next
- name: SSE idle keep-alive, terminal parity and disconnect without GPU
run: PYTHONDONTWRITEBYTECODE=1 python3 scripts/smoke-sse-keepalive.py control-plane/target/x86_64-unknown-linux-musl/release/strata-next
run: PYTHONDONTWRITEBYTECODE=1 python3 scripts/smoke-sse-keepalive.py target/x86_64-unknown-linux-musl/release/strata-next
- name: Stored Responses retrieval and deletion without GPU
run: python3 scripts/smoke-response-history.py control-plane/target/x86_64-unknown-linux-musl/release/strata-next
run: python3 scripts/smoke-response-history.py target/x86_64-unknown-linux-musl/release/strata-next
- name: Durable Responses restart and disk failure gate
run: python3 scripts/smoke-response-history.py control-plane/target/x86_64-unknown-linux-musl/release/strata-next --durable
run: python3 scripts/smoke-response-history.py target/x86_64-unknown-linux-musl/release/strata-next --durable
- name: Native drain and resume without GPU
run: python3 scripts/smoke-native-drain.py control-plane/target/x86_64-unknown-linux-musl/release/strata-next
run: python3 scripts/smoke-native-drain.py target/x86_64-unknown-linux-musl/release/strata-next
- name: Native signal shutdown grace without GPU
run: python3 scripts/smoke-signal-drain.py control-plane/target/x86_64-unknown-linux-musl/release/strata-next
run: python3 scripts/smoke-signal-drain.py target/x86_64-unknown-linux-musl/release/strata-next
- name: Native generation deadline and recovery without GPU
run: python3 scripts/smoke-generation-deadline.py control-plane/target/x86_64-unknown-linux-musl/release/strata-next
run: python3 scripts/smoke-generation-deadline.py target/x86_64-unknown-linux-musl/release/strata-next
- name: Native queue deadline without expiring active work
run: python3 scripts/smoke-queue-deadline.py control-plane/target/x86_64-unknown-linux-musl/release/strata-next
run: python3 scripts/smoke-queue-deadline.py target/x86_64-unknown-linux-musl/release/strata-next
- name: Static CLI HTTP cancellation failure isolation
run: python3 scripts/smoke-worker-cancel.py control-plane/target/x86_64-unknown-linux-musl/release/strata-next
run: python3 scripts/smoke-worker-cancel.py target/x86_64-unknown-linux-musl/release/strata-next
- name: Static CLI HTTP crash recovery without request replay
run: python3 scripts/smoke-worker-cancel.py control-plane/target/x86_64-unknown-linux-musl/release/strata-next --restart
run: python3 scripts/smoke-worker-cancel.py target/x86_64-unknown-linux-musl/release/strata-next --restart
- name: Embedded CPU worker packaging without GPU
run: |
musl-gcc -O2 -static scripts/fixtures/embedded-worker.c -o "$RUNNER_TEMP/embedded-worker"
@@ -320,16 +342,13 @@ jobs:
docker image rm "$image"
rm "$receipt"
fi
- uses: actions/upload-artifact@v4
with:
name: strata-next-linux-x86_64-musl
path: dist/
linux-cli-container:
needs: verify
runs-on: ubuntu-24.04
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262
- name: Install the Docker CLI
run: command -v docker >/dev/null 2>&1 || { apt-get update -qq && DEBIAN_FRONTEND=noninteractive apt-get install -y -qq docker.io >/dev/null; }
- name: Build actual CLI-only scratch image
run: docker build --file deploy/Dockerfile.static-cli --tag strata-cli-check .
- name: Check isolated CLI container startup and shutdown
@@ -341,18 +360,51 @@ jobs:
release-cli:
if: startsWith(github.ref, 'refs/tags/v')
needs: [linux-static-cli, linux-cli-container]
runs-on: ubuntu-24.04
runs-on: ubuntu-latest
permissions:
contents: write
steps:
- uses: actions/download-artifact@v4
with:
name: strata-next-linux-x86_64-musl
path: dist/
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262
- name: Install release build tools
run: apt-get update && apt-get install -y ca-certificates curl gh musl-tools cmake binutils python3-numpy
- name: Install pinned Rust and target
run: |
scripts/install-pinned-rustup.sh rustup toolchain install 1.99.0 --profile minimal --target x86_64-unknown-linux-musl
- name: Rebuild release CLI assets on the tag commit
run: |
cargo build --manifest-path control-plane/Cargo.toml --locked --release --target x86_64-unknown-linux-musl --bin strata-next
binary=target/x86_64-unknown-linux-musl/release/strata-next
if readelf -l "$binary" | grep -q INTERP; then
echo 'ELF has a dynamic interpreter' >&2
exit 1
fi
if readelf -d "$binary" | grep -q NEEDED; then
echo 'ELF has a dynamic library dependency' >&2
exit 1
fi
"$binary" --version
mkdir -p dist
cp "$binary" dist/strata-next-linux-x86_64-musl
{
echo "Commit: $GITHUB_SHA"
echo "Workflow: $GITHUB_SERVER_URL/$GITHUB_REPOSITORY/actions/runs/$GITHUB_RUN_ID"
rustc --version
cargo --version
musl-gcc --version
readelf --version
} > dist/BUILD-PROVENANCE.txt
{
readelf -h "$binary"
readelf -l "$binary"
readelf -d "$binary"
} > dist/ELF-AUDIT.txt
(cd dist && sha256sum strata-next-linux-x86_64-musl BUILD-PROVENANCE.txt ELF-AUDIT.txt > SHA256SUMS)
- name: Publish CLI preview release
env:
GH_TOKEN: ${{ github.token }}
run: |
export GH_HOST="${GITHUB_SERVER_URL#https://}"
export GH_HOST="${GH_HOST#http://}"
gh release create "${GITHUB_REF_NAME}" dist/strata-next-linux-x86_64-musl dist/SHA256SUMS dist/BUILD-PROVENANCE.txt dist/ELF-AUDIT.txt \
--repo "${GITHUB_REPOSITORY}" --title "Strata Next ${GITHUB_REF_NAME}" \
--notes 'CLI/control-plane preview. CUDA engine and model files are not included.' --prerelease
+9 -6
View File
@@ -17,7 +17,8 @@ performance gain is claimed for Leleka until its real-model gates pass.
- `crates/backend-api/` — Leleka's versioned Rust backend contract.
- `crates/tokenizer/` — the Qwen35 byte-level BPE tokenizer extracted as a
backend-independent Rust crate.
backend-independent Rust crate, including a bounded GGUF v3 reader for its
tokenizer metadata.
- `desktop/`, `desktop-core/` — current desktop application and its Rust core.
- `control-plane/` — current Rust API, Responses handling, and worker supervisor.
- `engine/strata/` — pinned upstream Strata reference; retained during migration.
@@ -34,11 +35,13 @@ artifacts remain outside Git or under ignored paths.
Leleka currently has a versioned backend contract and a standalone Qwen35 BPE
tokenizer crate. The existing Rust control plane now consumes that shared
tokenizer crate instead of maintaining a second copy; its oracle-parity tests
remain in the workspace. Leleka still has no independent inference backend or
CUDA integration, so this does not yet serve a model independently. The
desktop app and the rest of the control plane remain available as migration
source in this repository.
tokenizer crate for both encoding and GGUF tokenizer metadata rather than
maintaining a second parser; its oracle-parity and malformed-header tests remain
in the workspace. The GGUF reader only supports the current Qwen35 GPT-2 BPE
metadata shape and does not inspect tensor payloads. Leleka still has no
independent inference backend or CUDA integration, so this does not yet serve a
model independently. The desktop app and the rest of the control plane remain
available as migration source in this repository.
## Development
+11 -1
View File
@@ -119,15 +119,25 @@ mod tests {
#[test]
fn sealed_payload_is_exact_immutable_and_removed_on_drop() {
use std::io::Write;
use std::os::unix::fs::MetadataExt;
let engine = materialize(b"immutable fixture bytes").unwrap();
let path = engine.executable.clone();
assert_eq!(std::fs::read(&path).unwrap(), b"immutable fixture bytes");
let metadata = std::fs::metadata(&path).unwrap();
let identity = (metadata.dev(), metadata.ino());
let mut other = std::fs::OpenOptions::new().write(true).open(&path).unwrap();
assert!(other.write_all(b"x").is_err());
assert!(other.set_len(0).is_err());
assert!(other.set_len(100).is_err());
drop(other);
drop(engine);
assert!(!path.exists());
// The path names a process fd, not a persistent file. Rust tests run
// concurrently, so another test can reuse that fd number immediately
// after drop; assert the original memfd identity disappeared instead.
match std::fs::metadata(&path) {
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
Ok(after) => assert_ne!((after.dev(), after.ino()), identity),
Err(error) => panic!("unexpected fd path metadata error: {error}"),
}
}
}
+3 -127
View File
@@ -41,16 +41,7 @@ pub struct TensorIndex {
pub tensors: Vec<TensorInfo>,
}
#[derive(Debug)]
pub struct TokenizerMetadata {
pub model: String,
pub pre: String,
pub tokens: Vec<String>,
pub merges: Vec<String>,
pub token_types: Option<Vec<u32>>,
pub special_ids: BTreeMap<String, u32>,
pub chat_template: String,
}
pub use leleka_tokenizer::GgufTokenizerMetadata as TokenizerMetadata;
/// Metadata admission for the specialised engine, before expensive preparation.
/// Mirrors artifact/gguf_reader.hpp::Qwen4ExpGuard; this does not inspect tensor values.
@@ -109,86 +100,10 @@ pub fn check_flash_next_profile(path: &Path) -> Result<()> {
Ok(())
}
/// Read only tokenizer fields after the complete GGUF header has passed inspection.
/// Read tokenizer fields after complete model-header inspection, using the shared Leleka parser.
pub fn tokenizer_metadata(path: &Path) -> Result<TokenizerMetadata> {
inspect(path)?;
let file = File::open(path)?;
let size = file.metadata()?.len();
let mut cursor = Cursor { file, size };
cursor.skip(16)?; // magic, version, tensor count
let count = cursor.u64()?;
let mut model = None;
let mut pre = None;
let mut tokens = None;
let mut merges = None;
let mut token_types = None;
let mut special_ids = BTreeMap::new();
let mut chat_template = None;
for _ in 0..count {
let key = cursor.string()?;
let kind = cursor.u32()?;
match key.as_str() {
"tokenizer.ggml.model" if kind == 8 => model = Some(cursor.string()?),
"tokenizer.ggml.pre" if kind == 8 => pre = Some(cursor.string()?),
"tokenizer.ggml.tokens" => tokens = Some(cursor.string_array(kind)?),
"tokenizer.ggml.merges" => merges = Some(cursor.string_array(kind)?),
"tokenizer.ggml.token_type" => token_types = Some(cursor.integer_array(kind)?),
"tokenizer.chat_template" if kind == 8 => chat_template = Some(cursor.string()?),
_ if key.starts_with("tokenizer.ggml.") && key.ends_with("_token_id") => {
special_ids.insert(key, cursor.integer(kind)?);
}
_ => cursor.skip_value(kind)?,
}
}
let model = model.ok_or("GGUF is missing tokenizer.ggml.model")?;
let tokens = tokens.ok_or("GGUF is missing tokenizer.ggml.tokens")?;
let merges = merges.ok_or("GGUF is missing tokenizer.ggml.merges")?;
let chat_template = chat_template.ok_or("GGUF is missing tokenizer.chat_template")?;
if model != "gpt2" || pre.as_deref().is_some_and(|value| value != "qwen35") {
return Err("only the qwen35 byte-level BPE tokenizer is supported".into());
}
if tokens.is_empty() || chat_template.is_empty() {
return Err("GGUF tokenizer has an empty vocabulary or chat template".into());
}
if token_types
.as_ref()
.is_some_and(|types| types.len() != tokens.len())
{
return Err("token_type length differs from vocabulary length".into());
}
let vocab: HashSet<&str> = tokens.iter().map(String::as_str).collect();
if vocab.len() != tokens.len() {
return Err("GGUF tokenizer has duplicate vocabulary entries".into());
}
let mut seen_merges = HashSet::new();
for merge in &merges {
let Some((left, right)) = merge.split_once(' ') else {
return Err("GGUF BPE merge is not a pair".into());
};
if left.is_empty()
|| right.is_empty()
|| right.contains(' ')
|| !vocab.contains(left)
|| !vocab.contains(right)
|| !seen_merges.insert(merge)
{
return Err("GGUF BPE merge is invalid or duplicated".into());
}
}
for &id in special_ids.values() {
if id as usize >= tokens.len() {
return Err("special token ID exceeds vocabulary".into());
}
}
Ok(TokenizerMetadata {
model,
pre: pre.unwrap_or_else(|| "qwen35".to_owned()),
tokens,
merges,
token_types,
special_ids,
chat_template,
})
Ok(leleka_tokenizer::read_gguf_tokenizer_metadata(path)?)
}
pub fn inspect(path: &Path) -> Result<Summary> {
@@ -495,45 +410,6 @@ impl Cursor {
Ok(String::from_utf8(self.take(size as usize)?)?)
}
fn string_array(&mut self, kind: u32) -> Result<Vec<String>> {
if kind != 9 || self.u32()? != 8 {
return Err("expected a GGUF string array".into());
}
let count = self.u64()?;
if count > 1_000_000 {
return Err("unreasonable GGUF tokenizer array count".into());
}
let mut total = 0u64;
let mut values = Vec::with_capacity(count as usize);
for _ in 0..count {
let value = self.string()?;
total = total
.checked_add(value.len() as u64)
.ok_or("GGUF tokenizer array size overflow")?;
if total > 512 * 1024 * 1024 {
return Err("GGUF tokenizer array exceeds 512 MiB".into());
}
values.push(value);
}
Ok(values)
}
fn integer_array(&mut self, kind: u32) -> Result<Vec<u32>> {
if kind != 9 {
return Err("expected a GGUF integer array".into());
}
let element = self.u32()?;
let count = self.u64()?;
if count > 1_000_000 {
return Err("unreasonable GGUF tokenizer array count".into());
}
let mut values = Vec::with_capacity(count as usize);
for _ in 0..count {
values.push(self.integer(element)?);
}
Ok(values)
}
fn integer(&mut self, kind: u32) -> Result<u32> {
match kind {
0 | 7 => Ok(u32::from(self.u8()?)),
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+380 -39
View File
@@ -92,47 +92,114 @@ async fn ensure_sharded_streamed_with_policy(
levels: u8,
ple_part_elements: Option<u64>,
) -> Result<PreviewOutcome, Box<dyn Error>> {
if !(1..=8).contains(&levels) {
return Err("streamed sharded preparation requires 1..=8 KAR levels".into());
StreamedEnsureRequest {
manifest,
source_dir,
archive,
levels,
ple_part_elements,
}
.run()
.await
}
struct StreamedEnsureRequest<'a> {
manifest: &'a model::Manifest,
source_dir: &'a Path,
archive: &'a Path,
levels: u8,
ple_part_elements: Option<u64>,
}
impl StreamedEnsureRequest<'_> {
async fn run(self) -> Result<PreviewOutcome, Box<dyn Error>> {
self.validate()?;
preflight_existing_shards(self.manifest, self.source_dir, self.archive, self.levels)?;
model::fetch(self.manifest, self.source_dir).await?;
model::verify(self.manifest, self.source_dir).await?;
self.resolve_archive()
}
fn validate(&self) -> Result<(), Box<dyn Error>> {
if !(1..=8).contains(&self.levels) {
return Err("streamed sharded preparation requires 1..=8 KAR levels".into());
}
if let Some(limit) = self.ple_part_elements {
stream_parts::validate_ple_limit(limit)?;
}
Ok(())
}
fn resolve_archive(self) -> Result<PreviewOutcome, Box<dyn Error>> {
match fs::symlink_metadata(self.archive) {
Ok(metadata) => self.reuse_existing(metadata),
Err(error) if error.kind() == io::ErrorKind::NotFound => self.create_archive(),
Err(error) => Err(error.into()),
}
}
fn reuse_existing(&self, metadata: fs::Metadata) -> Result<PreviewOutcome, Box<dyn Error>> {
if metadata.file_type().is_symlink() || !metadata.is_file() {
return Err("existing KAR path must be a regular file".into());
}
let summary = if prepare_preview::has_pending_streamed_publication(self.archive)? {
prepare_preview::recover_sharded_streamed_provenance(
self.manifest,
self.source_dir,
self.archive,
self.levels,
self.ple_part_elements,
)?
.ok_or("KAR recovery intent disappeared before verification")?
} else {
self.verify_archive()?
};
Ok(PreviewOutcome::Reused(summary))
}
fn create_archive(&self) -> Result<PreviewOutcome, Box<dyn Error>> {
let created = if let Some(limit) = self.ple_part_elements {
prepare_preview::prepare_sharded_streamed_ple(
self.manifest,
self.source_dir,
self.archive,
self.levels,
limit,
)?
} else {
prepare_preview::prepare_sharded_streamed(
self.manifest,
self.source_dir,
self.archive,
self.levels,
)?
};
self.verify_archive()?;
Ok(PreviewOutcome::Created(created))
}
fn verify_archive(&self) -> Result<kar::Summary, String> {
verify_streamed_archive(
self.manifest,
self.source_dir,
self.archive,
self.levels,
self.ple_part_elements,
)
}
}
fn verify_streamed_archive(
manifest: &model::Manifest,
source_dir: &Path,
archive: &Path,
levels: u8,
ple_part_elements: Option<u64>,
) -> Result<kar::Summary, String> {
if let Some(limit) = ple_part_elements {
stream_parts::validate_ple_limit(limit)?;
}
preflight_existing_shards(manifest, source_dir, archive, levels)?;
model::fetch(manifest, source_dir).await?;
model::verify(manifest, source_dir).await?;
match fs::symlink_metadata(archive) {
Ok(metadata) => {
if !metadata.is_file() || metadata.file_type().is_symlink() {
return Err("existing KAR path must be a regular file".into());
}
let summary = if let Some(limit) = ple_part_elements {
prepare_preview::verify_sharded_streamed_ple(
manifest, source_dir, archive, levels, limit,
)?
} else {
prepare_preview::verify_sharded_streamed(manifest, source_dir, archive, levels)?
};
Ok(PreviewOutcome::Reused(summary))
}
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
let created = if let Some(limit) = ple_part_elements {
prepare_preview::prepare_sharded_streamed_ple(
manifest, source_dir, archive, levels, limit,
)?
} else {
prepare_preview::prepare_sharded_streamed(manifest, source_dir, archive, levels)?
};
if let Some(limit) = ple_part_elements {
prepare_preview::verify_sharded_streamed_ple(
manifest, source_dir, archive, levels, limit,
)?;
} else {
prepare_preview::verify_sharded_streamed(manifest, source_dir, archive, levels)?;
}
Ok(PreviewOutcome::Created(created))
}
Err(error) => Err(error.into()),
prepare_preview::verify_sharded_streamed_ple(manifest, source_dir, archive, levels, limit)
} else {
prepare_preview::verify_sharded_streamed(manifest, source_dir, archive, levels)
}
}
@@ -199,8 +266,93 @@ fn preflight_existing_shards(
#[cfg(test)]
mod tests {
use super::*;
use sha2::{Digest, Sha256};
use std::time::{SystemTime, UNIX_EPOCH};
fn gguf_string(bytes: &mut Vec<u8>, value: &str) {
bytes.extend_from_slice(&(value.len() as u64).to_le_bytes());
bytes.extend_from_slice(value.as_bytes());
}
fn f32_shard(name: &str, values: &[f32]) -> Vec<u8> {
let mut bytes = b"GGUF".to_vec();
bytes.extend_from_slice(&3u32.to_le_bytes());
bytes.extend_from_slice(&1u64.to_le_bytes());
bytes.extend_from_slice(&1u64.to_le_bytes());
gguf_string(&mut bytes, "general.architecture");
bytes.extend_from_slice(&8u32.to_le_bytes());
gguf_string(&mut bytes, "qwen35");
gguf_string(&mut bytes, name);
bytes.extend_from_slice(&1u32.to_le_bytes());
bytes.extend_from_slice(&(values.len() as u64).to_le_bytes());
bytes.extend_from_slice(&0u32.to_le_bytes());
bytes.extend_from_slice(&0u64.to_le_bytes());
bytes.resize(bytes.len().div_ceil(32) * 32, 0);
bytes.extend(values.iter().flat_map(|value| value.to_le_bytes()));
bytes
}
fn iq3_shard() -> Vec<u8> {
let mut payload = vec![0u8; crate::iq3_s::BLOCK_BYTES];
payload[..2].copy_from_slice(&0x3c00u16.to_le_bytes());
let mut bytes = b"GGUF".to_vec();
bytes.extend_from_slice(&3u32.to_le_bytes());
bytes.extend_from_slice(&1u64.to_le_bytes());
bytes.extend_from_slice(&0u64.to_le_bytes());
gguf_string(&mut bytes, "expert");
bytes.extend_from_slice(&1u32.to_le_bytes());
bytes.extend_from_slice(&256u64.to_le_bytes());
bytes.extend_from_slice(&21u32.to_le_bytes());
bytes.extend_from_slice(&0u64.to_le_bytes());
bytes.resize(bytes.len().div_ceil(32) * 32, 0);
bytes.extend(payload);
bytes
}
fn temporary_directory(label: &str) -> std::path::PathBuf {
let stamp = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_nanos();
std::env::temp_dir().join(format!("strata-{label}-{}-{stamp}", std::process::id()))
}
fn local_manifest(directory: &Path) -> model::Manifest {
let payload = (0..64)
.map(|number| [-1.0, -0.25, 0.25, 1.0][number % 4])
.collect::<Vec<_>>();
let shard = f32_shard("dense", &payload);
fs::write(directory.join("tiny.gguf"), &shard).unwrap();
let iq3 = iq3_shard();
fs::write(directory.join("expert.gguf"), &iq3).unwrap();
model::Manifest {
schema_version: 1,
files: [("tiny.gguf", shard), ("expert.gguf", iq3)]
.into_iter()
.map(|(name, bytes)| model::ModelFile {
name: name.into(),
url: format!("https://example.invalid/{name}"),
size: bytes.len() as u64,
sha256: hex::encode(Sha256::digest(bytes)),
})
.collect(),
}
}
fn ple_manifest(directory: &Path) -> model::Manifest {
let mut manifest = local_manifest(directory);
let values = (0..512).map(|value| value as f32).collect::<Vec<_>>();
let bytes = f32_shard(stream_parts::PLE_TENSOR_NAME, &values);
fs::write(directory.join("ple.gguf"), &bytes).unwrap();
manifest.files.push(model::ModelFile {
name: "ple.gguf".into(),
url: "https://example.invalid/ple.gguf".into(),
size: bytes.len() as u64,
sha256: hex::encode(Sha256::digest(bytes)),
});
manifest
}
#[tokio::test]
async fn full_model_is_rejected_before_creating_a_download_directory() {
let manifest = model::Manifest::from_spec("qwen-iq3-s").await.unwrap();
@@ -222,4 +374,193 @@ mod tests {
assert!(error.contains("at most 64 MiB"));
assert!(!source_dir.exists());
}
#[test]
fn streamed_create_and_reuse_verify_local_archive() {
let directory = temporary_directory("pipeline");
fs::create_dir(&directory).unwrap();
let manifest = local_manifest(&directory);
let archive = directory.join("tiny.kar");
let request = StreamedEnsureRequest {
manifest: &manifest,
source_dir: &directory,
archive: &archive,
levels: 2,
ple_part_elements: None,
};
let created = request.create_archive().unwrap();
assert!(matches!(created, PreviewOutcome::Created(_)));
let metadata = fs::metadata(&archive).unwrap();
let reused = request.reuse_existing(metadata).unwrap();
assert!(matches!(reused, PreviewOutcome::Reused(_)));
verify_streamed_archive(&manifest, &directory, &archive, 2, None).unwrap();
fs::remove_dir_all(directory).unwrap();
}
#[test]
fn streamed_ple_create_verify_and_reuse_keep_the_partition_policy() {
let directory = temporary_directory("pipeline-ple");
fs::create_dir(&directory).unwrap();
let manifest = ple_manifest(&directory);
let archive = directory.join("ple.kar");
let request = StreamedEnsureRequest {
manifest: &manifest,
source_dir: &directory,
archive: &archive,
levels: 2,
ple_part_elements: Some(128),
};
let created = request.create_archive().unwrap();
assert!(matches!(created, PreviewOutcome::Created(_)));
assert!(verify_streamed_archive(&manifest, &directory, &archive, 2, Some(128)).is_ok());
assert!(matches!(
request.reuse_existing(fs::metadata(&archive).unwrap()),
Ok(PreviewOutcome::Reused(_))
));
fs::remove_dir_all(directory).unwrap();
}
#[test]
fn preflight_defers_existing_missing_and_resumable_shards() {
let directory = temporary_directory("preflight-incomplete");
fs::create_dir(&directory).unwrap();
let manifest = local_manifest(&directory);
let archive = directory.join("model.kar");
assert!(preflight_existing_shards(&manifest, &directory, &archive, 2).is_ok());
fs::write(&archive, b"existing").unwrap();
assert!(preflight_existing_shards(&manifest, &directory, &archive, 2).is_ok());
fs::remove_file(&archive).unwrap();
fs::remove_file(directory.join("tiny.gguf")).unwrap();
assert!(preflight_existing_shards(&manifest, &directory, &archive, 2).is_ok());
fs::write(directory.join("tiny.gguf"), b"short").unwrap();
assert!(preflight_existing_shards(&manifest, &directory, &archive, 2).is_ok());
fs::remove_dir_all(directory).unwrap();
}
#[test]
fn preflight_rejects_unsafe_names_and_non_regular_shards() {
let directory = temporary_directory("preflight-invalid");
fs::create_dir(&directory).unwrap();
let mut manifest = local_manifest(&directory);
manifest.files.truncate(1);
manifest.files[0].name = "../escape.gguf".into();
assert!(preflight_existing_shards(&manifest, &directory, Path::new("out"), 2).is_err());
manifest.files[0].name = "directory.gguf".into();
fs::create_dir(directory.join("directory.gguf")).unwrap();
assert!(preflight_existing_shards(&manifest, &directory, Path::new("out"), 2).is_err());
fs::remove_dir_all(directory).unwrap();
}
#[test]
fn streamed_request_validation_and_archive_path_fail_closed() {
let manifest = model::Manifest {
schema_version: 1,
files: Vec::new(),
};
let source_dir = Path::new(".");
let archive = Path::new("bad\0archive.kar");
let invalid = StreamedEnsureRequest {
manifest: &manifest,
source_dir,
archive,
levels: 0,
ple_part_elements: None,
};
assert!(invalid.validate().is_err());
let invalid_limit = StreamedEnsureRequest {
levels: 2,
ple_part_elements: Some(31),
..invalid
};
assert!(invalid_limit.validate().is_err());
assert!(invalid_limit.resolve_archive().is_err());
}
#[test]
fn existing_non_regular_archive_is_rejected() {
let dir = temporary_directory("non-regular");
fs::create_dir(&dir).unwrap();
let manifest = model::Manifest {
schema_version: 1,
files: Vec::new(),
};
let request = StreamedEnsureRequest {
manifest: &manifest,
source_dir: &dir,
archive: &dir,
levels: 2,
ple_part_elements: None,
};
assert!(request.reuse_existing(fs::metadata(&dir).unwrap()).is_err());
assert!(
StreamedEnsureRequest {
manifest: &manifest,
source_dir: &dir,
archive: &dir,
levels: 2,
ple_part_elements: None,
}
.resolve_archive()
.is_err()
);
fs::remove_dir_all(dir).unwrap();
}
#[cfg(unix)]
#[test]
fn streamed_archive_resolution_handles_missing_and_symlink_paths() {
let dir = temporary_directory("archive-resolution");
fs::create_dir(&dir).unwrap();
let manifest = model::Manifest {
schema_version: 1,
files: Vec::new(),
};
let archive = dir.join("missing.kar");
assert_missing_archive_rejected(&manifest, &dir, &archive);
let target = dir.join("target");
fs::write(&target, b"regular target").unwrap();
let link = dir.join("link.kar");
std::os::unix::fs::symlink(&target, &link).unwrap();
assert_symlink_archive_rejected(&manifest, &dir, &link);
fs::remove_dir_all(dir).unwrap();
}
#[cfg(unix)]
fn assert_missing_archive_rejected(
manifest: &model::Manifest,
source_dir: &Path,
archive: &Path,
) {
let request = ensure_request(manifest, source_dir, archive);
assert!(request.resolve_archive().is_err());
}
#[cfg(unix)]
fn assert_symlink_archive_rejected(
manifest: &model::Manifest,
source_dir: &Path,
archive: &Path,
) {
let request = ensure_request(manifest, source_dir, archive);
assert!(
request
.reuse_existing(fs::symlink_metadata(archive).unwrap())
.is_err()
);
}
#[cfg(unix)]
fn ensure_request<'a>(
manifest: &'a model::Manifest,
source_dir: &'a Path,
archive: &'a Path,
) -> StreamedEnsureRequest<'a> {
StreamedEnsureRequest {
manifest,
source_dir,
archive,
levels: 2,
ple_part_elements: None,
}
}
}
File diff suppressed because it is too large Load Diff
+685 -95
View File
@@ -171,7 +171,14 @@ pub(crate) fn plan_shards_with_limit(
source_dir: &Path,
max_part_elements: u64,
) -> Result<Vec<Vec<PartIdentity>>, String> {
plan_shards_with_limits(identity, source_dir, max_part_elements, None)
plan_shards_with_limits(
identity,
source_dir,
PlanLimits {
max_part_elements,
ple_part_elements: None,
},
)
}
pub fn plan_shards_with_ple_limit(
@@ -183,122 +190,705 @@ pub fn plan_shards_with_ple_limit(
plan_shards_with_limits(
identity,
source_dir,
MAX_PART_ELEMENTS,
Some(ple_part_elements),
PlanLimits {
max_part_elements: MAX_PART_ELEMENTS,
ple_part_elements: Some(ple_part_elements),
},
)
}
fn plan_shards_with_limits(
identity: &derived_mixed::ShardedIdentity,
source_dir: &Path,
limits: PlanLimits,
) -> Result<Vec<Vec<PartIdentity>>, String> {
ShardPlanner::new(identity, source_dir, limits).plan()
}
#[derive(Clone, Copy)]
struct PlanLimits {
max_part_elements: u64,
ple_part_elements: Option<u64>,
) -> Result<Vec<Vec<PartIdentity>>, String> {
let mut result = Vec::with_capacity(identity.tensors.len());
let mut names = HashSet::new();
let mut number = 0usize;
let mut saw_ple = false;
for shard in &identity.shards {
let path = source_dir.join(&shard.name);
}
struct ShardPlanner<'a> {
identity: &'a derived_mixed::ShardedIdentity,
source_dir: &'a Path,
limits: PlanLimits,
result: Vec<Vec<PartIdentity>>,
names: HashSet<String>,
number: usize,
saw_ple: bool,
}
struct ParentHashes {
source: Sha256,
f32: Sha256,
}
struct LayoutHashAccumulator<'a> {
part: ParentHashes,
parent: &'a mut ParentHashes,
}
struct PartBuildContext<'a> {
index: &'a gguf::TensorIndex,
tensor: &'a gguf::TensorInfo,
original: &'a derived_mixed::TensorIdentity,
split: bool,
}
impl<'a> ShardPlanner<'a> {
fn new(
identity: &'a derived_mixed::ShardedIdentity,
source_dir: &'a Path,
limits: PlanLimits,
) -> Self {
Self {
identity,
source_dir,
limits,
result: Vec::with_capacity(identity.tensors.len()),
names: HashSet::new(),
number: 0,
saw_ple: false,
}
}
fn plan(mut self) -> Result<Vec<Vec<PartIdentity>>, String> {
for shard in &self.identity.shards {
self.plan_shard(shard)?;
}
if self.number != self.identity.tensors.len() {
return Err("GGUF tensor count differs from virtual source".into());
}
if self.limits.ple_part_elements.is_some() && !self.saw_ple {
return Err("PLE partition policy requires per_layer_token_embd.weight".into());
}
Ok(self.result)
}
fn plan_shard(&mut self, shard: &derived_mixed::ShardIdentity) -> Result<(), String> {
self.plan_shard_with_open(shard, |path| File::open(path))
}
fn plan_shard_with_open(
&mut self,
shard: &derived_mixed::ShardIdentity,
open: fn(&Path) -> std::io::Result<File>,
) -> Result<(), String> {
let path = self.source_dir.join(&shard.name);
let index = gguf::tensor_index(&path).map_err(|error| error.to_string())?;
if index.tensors.len() != shard.tensor_count {
return Err("GGUF shard changed during KAR part planning".into());
}
let mut source = File::open(&path).map_err(|error| error.to_string())?;
let mut source = open(&path).map_err(|error| error.to_string())?;
for tensor in &index.tensors {
let original = identity
.tensors
.get(number)
.ok_or("GGUF tensor count differs from virtual source")?;
if original.name != tensor.name || original.source_kind != tensor.kind {
return Err("GGUF tensor differs from virtual source".into());
}
let part_limit = if tensor.name == PLE_TENSOR_NAME {
saw_ple = true;
ple_part_elements.unwrap_or(max_part_elements)
} else {
max_part_elements
};
let layouts = layout_with_limit(tensor, original.derived_offset, part_limit)?;
if tensor.name == PLE_TENSOR_NAME && ple_part_elements.is_some() && layouts.len() < 2 {
return Err("PLE part limit must split the PLE tensor".into());
}
let split = layouts.len() > 1;
let mut parent_source = Sha256::new();
let mut parent_f32 = Sha256::new();
let mut parts = Vec::with_capacity(layouts.len());
for part in layouts {
if !names.insert(part.name.clone()) {
return Err(format!("duplicate KAR part name: {}", part.name));
}
let (source_sha256, f32_sha256) = if split {
let absolute = index
.summary
.data_start
.checked_add(tensor.offset)
.and_then(|n| n.checked_add(part.source_byte_offset))
.ok_or("GGUF part offset overflow")?;
let mut source_hash = Sha256::new();
let mut f32_hash = Sha256::new();
let count = gguf_f32_stream::visit(
&mut source,
absolute,
tensor.kind,
part.source_bytes,
|raw, f32_bytes| {
source_hash.update(raw);
f32_hash.update(f32_bytes);
parent_source.update(raw);
parent_f32.update(f32_bytes);
Ok(())
},
)?;
if count != part.derived_bytes {
return Err("GGUF part derived byte count mismatch".into());
}
(source_hash.finalize().into(), f32_hash.finalize().into())
} else {
(original.source_sha256, original.f32_sha256)
};
parts.push(PartIdentity {
name: part.name,
parent_name: tensor.name.clone(),
parent_dimensions: tensor.dimensions.clone(),
dimensions: part.dimensions,
source_kind: tensor.kind,
source_byte_offset: part.source_byte_offset,
source_bytes: part.source_bytes,
source_sha256,
derived_offset: part.derived_offset,
derived_bytes: part.derived_bytes,
f32_sha256,
});
}
if split
&& (parent_source.finalize().as_slice() != original.source_sha256
|| parent_f32.finalize().as_slice() != original.f32_sha256)
{
return Err(format!(
"{}: KAR part hashes differ from source",
tensor.name
));
}
result.push(parts);
number += 1;
self.plan_tensor(&index, &mut source, tensor)?;
}
Ok(())
}
fn plan_tensor(
&mut self,
index: &gguf::TensorIndex,
source: &mut File,
tensor: &gguf::TensorInfo,
) -> Result<(), String> {
self.validate_original_tensor(tensor)?;
let derived_offset = self.identity.tensors[self.number].derived_offset;
let part_limit = self.part_limit(tensor);
let layouts = layout_with_limit(tensor, derived_offset, part_limit)?;
self.require_ple_split(tensor, &layouts)?;
let original = &self.identity.tensors[self.number];
let context = PartBuildContext {
index,
tensor,
original,
split: layouts.len() > 1,
};
let parts = self.build_parts(source, layouts, context)?;
self.register_parts(parts)
}
fn validate_original_tensor(&self, tensor: &gguf::TensorInfo) -> Result<(), String> {
let original = self
.identity
.tensors
.get(self.number)
.ok_or("GGUF tensor count differs from virtual source")?;
if original.name != tensor.name || original.source_kind != tensor.kind {
return Err("GGUF tensor differs from virtual source".into());
}
Ok(())
}
fn part_limit(&mut self, tensor: &gguf::TensorInfo) -> u64 {
if tensor.name == PLE_TENSOR_NAME {
self.saw_ple = true;
self.limits
.ple_part_elements
.unwrap_or(self.limits.max_part_elements)
} else {
self.limits.max_part_elements
}
}
if number != identity.tensors.len() {
return Err("GGUF tensor count differs from virtual source".into());
fn require_ple_split(
&self,
tensor: &gguf::TensorInfo,
layouts: &[Layout],
) -> Result<(), String> {
if tensor.name == PLE_TENSOR_NAME
&& self.limits.ple_part_elements.is_some()
&& layouts.len() < 2
{
return Err("PLE part limit must split the PLE tensor".into());
}
Ok(())
}
if ple_part_elements.is_some() && !saw_ple {
return Err("PLE partition policy requires per_layer_token_embd.weight".into());
fn build_parts(
&self,
source: &mut File,
layouts: Vec<Layout>,
context: PartBuildContext<'_>,
) -> Result<Vec<PartIdentity>, String> {
let mut hashes = ParentHashes {
source: Sha256::new(),
f32: Sha256::new(),
};
let mut parts = Vec::with_capacity(layouts.len());
for layout in layouts {
parts.push(self.build_part(source, &layout, &context, &mut hashes)?);
}
self.verify_parent_hashes(context.tensor, context.original, context.split, hashes)?;
Ok(parts)
}
fn build_part(
&self,
source: &mut File,
layout: &Layout,
context: &PartBuildContext<'_>,
hashes: &mut ParentHashes,
) -> Result<PartIdentity, String> {
let tensor = context.tensor;
let hashes = part_hashes(source, layout, context, hashes)?;
Ok(part_identity(tensor, layout, hashes))
}
fn verify_parent_hashes(
&self,
tensor: &gguf::TensorInfo,
original: &derived_mixed::TensorIdentity,
split: bool,
hashes: ParentHashes,
) -> Result<(), String> {
if split
&& (hashes.source.finalize().as_slice() != original.source_sha256
|| hashes.f32.finalize().as_slice() != original.f32_sha256)
{
return Err(format!(
"{}: KAR part hashes differ from source",
tensor.name
));
}
Ok(())
}
fn register_parts(&mut self, parts: Vec<PartIdentity>) -> Result<(), String> {
for part in &parts {
if !self.names.insert(part.name.clone()) {
return Err(format!("duplicate KAR part name: {}", part.name));
}
}
self.result.push(parts);
self.number += 1;
Ok(())
}
}
fn part_hashes(
source: &mut File,
layout: &Layout,
context: &PartBuildContext<'_>,
parent: &mut ParentHashes,
) -> Result<([u8; 32], [u8; 32]), String> {
if context.split {
hash_layout(
source,
context.index.summary.data_start,
context.tensor,
layout,
parent,
)
} else {
Ok((context.original.source_sha256, context.original.f32_sha256))
}
}
fn part_identity(
tensor: &gguf::TensorInfo,
layout: &Layout,
hashes: ([u8; 32], [u8; 32]),
) -> PartIdentity {
PartIdentity {
name: layout.name.clone(),
parent_name: tensor.name.clone(),
parent_dimensions: tensor.dimensions.clone(),
dimensions: layout.dimensions.clone(),
source_kind: tensor.kind,
source_byte_offset: layout.source_byte_offset,
source_bytes: layout.source_bytes,
source_sha256: hashes.0,
derived_offset: layout.derived_offset,
derived_bytes: layout.derived_bytes,
f32_sha256: hashes.1,
}
}
fn hash_layout(
source: &mut File,
data_start: u64,
tensor: &gguf::TensorInfo,
layout: &Layout,
parent: &mut ParentHashes,
) -> Result<([u8; 32], [u8; 32]), String> {
let absolute = layout_absolute(data_start, tensor.offset, layout.source_byte_offset)?;
let mut hashes = LayoutHashAccumulator::new(parent);
let count = gguf_f32_stream::visit(
source,
absolute,
tensor.kind,
layout.source_bytes,
|raw, f32_bytes| hashes.update(raw, f32_bytes),
)?;
if count != layout.derived_bytes {
return Err("GGUF part derived byte count mismatch".into());
}
Ok(hashes.finish())
}
fn layout_absolute(data_start: u64, tensor_offset: u64, part_offset: u64) -> Result<u64, String> {
data_start
.checked_add(tensor_offset)
.and_then(|offset| offset.checked_add(part_offset))
.ok_or_else(|| "GGUF part offset overflow".into())
}
impl LayoutHashAccumulator<'_> {
fn new(parent: &mut ParentHashes) -> LayoutHashAccumulator<'_> {
LayoutHashAccumulator {
part: ParentHashes {
source: Sha256::new(),
f32: Sha256::new(),
},
parent,
}
}
fn update(&mut self, source: &[u8], f32: &[u8]) -> Result<(), String> {
self.part.source.update(source);
self.part.f32.update(f32);
self.parent.source.update(source);
self.parent.f32.update(f32);
Ok(())
}
fn finish(self) -> ([u8; 32], [u8; 32]) {
(
self.part.source.finalize().into(),
self.part.f32.finalize().into(),
)
}
Ok(result)
}
#[cfg(test)]
mod tests {
use super::*;
use std::path::PathBuf;
use std::time::{SystemTime, UNIX_EPOCH};
fn gguf_f32(name: &str) -> Vec<u8> {
let mut bytes = b"GGUF".to_vec();
bytes.extend_from_slice(&3u32.to_le_bytes());
bytes.extend_from_slice(&1u64.to_le_bytes());
bytes.extend_from_slice(&0u64.to_le_bytes());
bytes.extend_from_slice(&(name.len() as u64).to_le_bytes());
bytes.extend_from_slice(name.as_bytes());
bytes.extend_from_slice(&1u32.to_le_bytes());
bytes.extend_from_slice(&32u64.to_le_bytes());
bytes.extend_from_slice(&0u32.to_le_bytes());
bytes.extend_from_slice(&0u64.to_le_bytes());
bytes.resize(bytes.len().div_ceil(32) * 32, 0);
bytes.extend((0..32u32).flat_map(|value| (value as f32).to_le_bytes()));
bytes
}
fn identity_fixture(
directory: &Path,
names: &[(&str, &str)],
) -> derived_mixed::ShardedIdentity {
let entries = names
.iter()
.enumerate()
.map(|(index, (file, tensor))| identity_fixture_entry(directory, index, file, tensor))
.collect::<Vec<_>>();
let (shards, tensors): (Vec<_>, Vec<_>) = entries.into_iter().unzip();
derived_mixed::ShardedIdentity {
derived_sha256: [0; 32],
derived_bytes: tensors.len() as u64 * 128,
shards,
tensors,
}
}
fn identity_fixture_entry(
directory: &Path,
index: usize,
file_name: &str,
tensor_name: &str,
) -> (derived_mixed::ShardIdentity, derived_mixed::TensorIdentity) {
let bytes = gguf_f32(tensor_name);
std::fs::write(directory.join(file_name), &bytes).unwrap();
let digest = Sha256::digest(&bytes).into();
let f32_bytes = (0..32u32)
.flat_map(|value| (value as f32).to_le_bytes())
.collect::<Vec<_>>();
let f32_digest = Sha256::digest(f32_bytes).into();
let shard = derived_mixed::ShardIdentity {
name: file_name.into(),
gguf_sha256: digest,
gguf_bytes: bytes.len() as u64,
tensor_count: 1,
};
let tensor = derived_mixed::TensorIdentity {
name: tensor_name.into(),
source_kind: 0,
source_sha256: f32_digest,
derived_offset: index as u64 * 128,
derived_bytes: 128,
f32_sha256: f32_digest,
};
(shard, tensor)
}
fn plan_test_dir(label: &str) -> PathBuf {
let path = std::env::temp_dir().join(format!(
"strata-{label}-{}-{}",
std::process::id(),
SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_nanos()
));
std::fs::create_dir(&path).unwrap();
path
}
fn layout_hash_test_file() -> PathBuf {
let path = std::env::temp_dir().join(format!(
"strata-layout-hash-{}-{}.gguf",
std::process::id(),
SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_nanos()
));
std::fs::write(&path, 1.0f32.to_le_bytes()).unwrap();
path
}
fn layout_hash_fixture(
derived_bytes: u64,
) -> (PathBuf, File, gguf::TensorInfo, Layout, ParentHashes) {
let path = layout_hash_test_file();
let source = File::open(&path).unwrap();
let tensor = gguf::TensorInfo {
name: "tensor".into(),
dimensions: vec![1],
kind: 0,
offset: 0,
bytes: 4,
};
let layout = Layout {
name: "tensor".into(),
dimensions: vec![1],
source_byte_offset: 0,
source_bytes: 4,
derived_offset: 0,
derived_bytes,
};
let parent = ParentHashes {
source: Sha256::new(),
f32: Sha256::new(),
};
(path, source, tensor, layout, parent)
}
#[test]
fn layout_absolute_checks_both_offset_additions() {
assert_eq!(layout_absolute(10, 20, 30), Ok(60));
assert_eq!(
layout_absolute(u64::MAX, 1, 0),
Err("GGUF part offset overflow".into())
);
assert_eq!(
layout_absolute(0, u64::MAX, 1),
Err("GGUF part offset overflow".into())
);
}
#[test]
fn shard_planner_preserves_manifest_tensor_order_and_rejects_missing_source() {
let directory = std::env::temp_dir().join(format!(
"strata-plan-parts-{}-{}",
std::process::id(),
SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_nanos()
));
std::fs::create_dir(&directory).unwrap();
let identity = identity_fixture(&directory, &[("a.gguf", "weight")]);
let parts = plan_shards_with_limit(&identity, &directory, 32).unwrap();
assert_eq!(parts[0][0].name, "weight");
std::fs::remove_file(directory.join("a.gguf")).unwrap();
assert!(plan_shards_with_limit(&identity, &directory, 32).is_err());
std::fs::remove_dir_all(directory).unwrap();
}
#[test]
fn shard_planner_rejects_missing_ple_and_duplicate_part_names() {
let directory = plan_test_dir("plan-invalid");
assert_missing_ple_is_rejected(&directory);
assert_duplicate_names_are_rejected(&directory);
assert_unsplit_ple_is_rejected(&directory);
std::fs::remove_dir_all(directory).unwrap();
}
fn assert_missing_ple_is_rejected(directory: &Path) {
let identity = identity_fixture(directory, &[("a.gguf", "weight")]);
let limits = PlanLimits {
max_part_elements: 32,
ple_part_elements: Some(32),
};
assert!(matches!(
plan_shards_with_limits(&identity, directory, limits),
Err(error) if error.contains("requires per_layer_token_embd.weight")
));
}
fn assert_duplicate_names_are_rejected(directory: &Path) {
let identity = identity_fixture(directory, &[("b.gguf", "weight"), ("c.gguf", "weight")]);
let error = plan_shards_with_limit(&identity, directory, 32).unwrap_err();
assert!(error.contains("duplicate KAR part name"));
}
fn assert_unsplit_ple_is_rejected(directory: &Path) {
let identity = identity_fixture(directory, &[("ple.gguf", PLE_TENSOR_NAME)]);
let limits = PlanLimits {
max_part_elements: 32,
ple_part_elements: Some(32),
};
let error = plan_shards_with_limits(&identity, directory, limits).unwrap_err();
assert!(error.contains("must split the PLE tensor"));
}
#[test]
fn shard_planner_checks_virtual_tensor_count_and_identity() {
let directory = plan_test_dir("plan-count");
let mut identity = identity_fixture(&directory, &[("a.gguf", "weight")]);
identity.shards.clear();
let error = plan_shards_with_limit(&identity, &directory, 32).unwrap_err();
assert!(error.contains("tensor count differs"));
assert_virtual_source_mismatch_rejected(&directory);
std::fs::remove_dir_all(directory).unwrap();
}
fn assert_virtual_source_mismatch_rejected(directory: &Path) {
let bytes = gguf_f32("other");
let identity = derived_mixed::ShardedIdentity {
derived_sha256: [0; 32],
derived_bytes: 128,
shards: vec![derived_mixed::ShardIdentity {
name: "a.gguf".into(),
gguf_sha256: Sha256::digest(&bytes).into(),
gguf_bytes: bytes.len() as u64,
tensor_count: 1,
}],
tensors: identity_fixture(directory, &[("a.gguf", "weight")]).tensors,
};
std::fs::write(directory.join("a.gguf"), &bytes).unwrap();
let error = plan_shards_with_limit(&identity, directory, 32).unwrap_err();
assert!(error.contains("differs from virtual source"));
}
#[test]
fn shard_planner_rejects_changed_tensor_count_and_kind() {
let directory = std::env::temp_dir().join(format!(
"strata-plan-changed-tensor-{}-{}",
std::process::id(),
SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_nanos()
));
std::fs::create_dir(&directory).unwrap();
let mut identity = identity_fixture(&directory, &[("a.gguf", "weight")]);
identity.shards[0].tensor_count += 1;
assert!(plan_shards_with_limit(&identity, &directory, 32).is_err());
identity.shards[0].tensor_count -= 1;
identity.tensors[0].source_kind = 1;
assert!(plan_shards_with_limit(&identity, &directory, 32).is_err());
std::fs::remove_dir_all(directory).unwrap();
}
#[test]
fn shard_open_failure_is_returned_after_index_validation() {
let directory = std::env::temp_dir().join(format!(
"strata-plan-open-failure-{}-{}",
std::process::id(),
SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_nanos()
));
std::fs::create_dir(&directory).unwrap();
let identity = identity_fixture(&directory, &[("a.gguf", "weight")]);
let mut planner = ShardPlanner::new(
&identity,
&directory,
PlanLimits {
max_part_elements: 32,
ple_part_elements: None,
},
);
let error = planner.plan_shard_with_open(&identity.shards[0], |_| {
Err(std::io::Error::from(std::io::ErrorKind::PermissionDenied))
});
assert_eq!(
error.unwrap_err(),
std::io::Error::from(std::io::ErrorKind::PermissionDenied).to_string()
);
std::fs::remove_dir_all(directory).unwrap();
}
#[test]
fn split_parent_hashes_must_match_both_source_digests() {
let directory = std::env::temp_dir();
let identity = identity_fixture(&directory, &[]);
let planner = ShardPlanner::new(
&identity,
&directory,
PlanLimits {
max_part_elements: 32,
ple_part_elements: None,
},
);
let tensor = parent_hash_test_tensor();
let original = parent_hash_test_identity();
assert!(
planner
.verify_parent_hashes(&tensor, &original, true, matching_parent_hashes())
.is_ok()
);
assert_source_hash_mismatch_rejected(&planner, &tensor);
assert_f32_hash_mismatch_rejected(&planner, &tensor);
}
fn parent_hash_test_tensor() -> gguf::TensorInfo {
gguf::TensorInfo {
name: "weight".into(),
dimensions: vec![1],
kind: 0,
offset: 0,
bytes: 4,
}
}
fn parent_hash_test_identity() -> derived_mixed::TensorIdentity {
derived_mixed::TensorIdentity {
name: "weight".into(),
source_kind: 0,
source_sha256: Sha256::digest(b"source").into(),
derived_offset: 0,
derived_bytes: 4,
f32_sha256: Sha256::digest(b"derived").into(),
}
}
fn matching_parent_hashes() -> ParentHashes {
let mut hashes = ParentHashes {
source: Sha256::new(),
f32: Sha256::new(),
};
hashes.source.update(b"source");
hashes.f32.update(b"derived");
hashes
}
fn assert_source_hash_mismatch_rejected(planner: &ShardPlanner<'_>, tensor: &gguf::TensorInfo) {
let mut changed = parent_hash_test_identity();
changed.source_sha256[0] ^= 1;
assert!(
planner
.verify_parent_hashes(tensor, &changed, true, matching_parent_hashes())
.is_err()
);
}
fn assert_f32_hash_mismatch_rejected(planner: &ShardPlanner<'_>, tensor: &gguf::TensorInfo) {
let mut changed = parent_hash_test_identity();
changed.f32_sha256[0] ^= 1;
assert!(
planner
.verify_parent_hashes(tensor, &changed, true, matching_parent_hashes())
.is_err()
);
}
#[test]
fn hash_layout_streams_matching_source_and_derived_bytes() {
let (path, mut source, tensor, layout, mut parent) = layout_hash_fixture(4);
assert_matching_layout_hash(&mut source, &tensor, &layout, &mut parent);
drop(source);
std::fs::remove_file(path).unwrap();
}
fn assert_matching_layout_hash(
source: &mut File,
tensor: &gguf::TensorInfo,
layout: &Layout,
parent: &mut ParentHashes,
) {
let expected: [u8; 32] = Sha256::digest(1.0f32.to_le_bytes()).into();
assert_eq!(
hash_layout(source, 0, tensor, layout, parent).unwrap().0,
expected
);
}
#[test]
fn hash_layout_rejects_derived_byte_count_mismatch() {
let (path, mut source, tensor, layout, mut parent) = layout_hash_fixture(8);
assert_eq!(
hash_layout(&mut source, 0, &tensor, &layout, &mut parent).unwrap_err(),
"GGUF part derived byte count mismatch"
);
drop(source);
std::fs::remove_file(path).unwrap();
}
#[test]
fn hash_layout_propagates_truncated_source_reads() {
let (path, mut source, tensor, layout, mut parent) = layout_hash_fixture(8);
std::fs::write(&path, []).unwrap();
assert!(hash_layout(&mut source, 0, &tensor, &layout, &mut parent).is_err());
drop(source);
std::fs::remove_file(path).unwrap();
}
#[test]
fn giant_per_layer_tensor_becomes_two_contiguous_kar_parts() {
+769 -2
View File
@@ -2,9 +2,10 @@
use std::{
cmp::Reverse,
collections::{BinaryHeap, HashMap},
collections::{BTreeMap, BinaryHeap, HashMap, HashSet},
error::Error,
fs,
fs::{self, File},
io::{Read, Seek, SeekFrom},
path::Path,
};
@@ -303,6 +304,493 @@ impl Tokenizer {
}
}
/// The Qwen35 tokenizer fields read from a GGUF v3 metadata header.
#[derive(Debug, PartialEq, Eq)]
pub struct GgufTokenizerMetadata {
pub model: String,
pub pre: String,
pub tokens: Vec<String>,
pub merges: Vec<String>,
pub token_types: Option<Vec<u32>>,
pub special_ids: BTreeMap<String, u32>,
pub chat_template: String,
}
/// A bounded GGUF tokenizer metadata parsing error.
#[derive(Debug)]
pub struct GgufTokenizerError(String);
impl std::fmt::Display for GgufTokenizerError {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
formatter.write_str(&self.0)
}
}
impl Error for GgufTokenizerError {}
type GgufResult<T> = std::result::Result<T, GgufTokenizerError>;
const MAX_GGUF_HEADER_BYTES: u64 = 1024 * 1024 * 1024;
const MAX_GGUF_METADATA_ENTRIES: u64 = 1_000_000;
const MAX_GGUF_STRING_BYTES: u64 = 1024 * 1024;
const MAX_TOKENIZER_ARRAY_ITEMS: u64 = 1_000_000;
const MAX_TOKENIZER_ARRAY_BYTES: u64 = 512 * 1024 * 1024;
const MAX_RELEVANT_TOKENIZER_FIELDS: usize = 128;
/// Read Qwen35 GPT-2 BPE tokenizer metadata from a GGUF v3 file.
///
/// This reads at most the first 1 GiB of the file as a metadata header, caps
/// each header string at 1 MiB, and caps tokenizer string arrays at 1,000,000
/// elements and 512 MiB of aggregate string bytes. It never reads tensor
/// payloads. Callers that also require model/tensor validation must perform
/// that separately before using these tokenizer assets.
pub fn read_gguf_tokenizer_metadata(path: &Path) -> GgufResult<GgufTokenizerMetadata> {
let mut cursor = GgufCursor::open(path)?;
cursor.validate_file()?;
let count = cursor.metadata_entry_count()?;
TokenizerFields::read(&mut cursor, count)?.finish()
}
#[derive(Default)]
struct TokenizerFields {
model: Option<String>,
pre: Option<String>,
tokens: Option<Vec<String>>,
merges: Option<Vec<String>>,
token_types: Option<Vec<u32>>,
special_ids: BTreeMap<String, u32>,
chat_template: Option<String>,
seen_fields: HashSet<String>,
}
impl TokenizerFields {
fn read(cursor: &mut GgufCursor, count: u64) -> GgufResult<Self> {
let mut fields = Self::default();
for _ in 0..count {
fields.read_entry(cursor)?;
}
Ok(fields)
}
fn read_entry(&mut self, cursor: &mut GgufCursor) -> GgufResult<()> {
let key = cursor.string()?;
let kind = cursor.u32()?;
self.ensure_unique(&key)?;
self.read_value(key, kind, cursor)
}
fn ensure_unique(&mut self, key: &str) -> GgufResult<()> {
if !is_relevant_tokenizer_field(key) {
return Ok(());
}
if self.seen_fields.len() >= MAX_RELEVANT_TOKENIZER_FIELDS {
return Err(gguf_error("too many tokenizer metadata fields"));
}
if !self.seen_fields.insert(key.to_owned()) {
return Err(gguf_error("duplicate tokenizer metadata field"));
}
Ok(())
}
fn read_value(&mut self, key: String, kind: u32, cursor: &mut GgufCursor) -> GgufResult<()> {
match key.as_str() {
"tokenizer.ggml.model" if kind == 8 => self.model = Some(cursor.string()?),
"tokenizer.ggml.pre" => self.pre = Some(read_pre_value(cursor, kind)?),
"tokenizer.ggml.tokens" => self.tokens = Some(cursor.string_array(kind)?),
"tokenizer.ggml.merges" => self.merges = Some(cursor.string_array(kind)?),
"tokenizer.ggml.token_type" => self.token_types = Some(cursor.integer_array(kind)?),
"tokenizer.chat_template" if kind == 8 => self.chat_template = Some(cursor.string()?),
_ if is_special_token_id(&key) => {
self.special_ids.insert(key, cursor.integer(kind)?);
}
_ => cursor.skip_value(kind)?,
}
Ok(())
}
fn finish(self) -> GgufResult<GgufTokenizerMetadata> {
let (model, tokens, merges, chat_template) =
(self.model, self.tokens, self.merges, self.chat_template);
let model = model.ok_or_else(|| gguf_error("GGUF is missing tokenizer.ggml.model"))?;
let tokens = tokens.ok_or_else(|| gguf_error("GGUF is missing tokenizer.ggml.tokens"))?;
let merges = merges.ok_or_else(|| gguf_error("GGUF is missing tokenizer.ggml.merges"))?;
let chat_template =
chat_template.ok_or_else(|| gguf_error("GGUF is missing tokenizer.chat_template"))?;
validate_tokenizer_fields(
&model,
self.pre.as_deref(),
&tokens,
self.token_types.as_deref(),
&chat_template,
)?;
let vocab = validate_vocabulary(&tokens)?;
validate_merges(&merges, &vocab)?;
validate_special_ids(&self.special_ids, tokens.len())?;
Ok(GgufTokenizerMetadata {
model,
pre: self.pre.unwrap_or_else(|| "qwen35".to_owned()),
tokens,
merges,
token_types: self.token_types,
special_ids: self.special_ids,
chat_template,
})
}
}
fn is_relevant_tokenizer_field(key: &str) -> bool {
matches!(
key,
"tokenizer.ggml.model"
| "tokenizer.ggml.pre"
| "tokenizer.ggml.tokens"
| "tokenizer.ggml.merges"
| "tokenizer.ggml.token_type"
| "tokenizer.chat_template"
) || is_special_token_id(key)
}
fn is_special_token_id(key: &str) -> bool {
key.starts_with("tokenizer.ggml.") && key.ends_with("_token_id")
}
fn read_pre_value(cursor: &mut GgufCursor, kind: u32) -> GgufResult<String> {
if kind != 8 {
return Err(gguf_error("tokenizer.ggml.pre must be a string"));
}
cursor.string()
}
fn validate_tokenizer_fields(
model: &str,
pre: Option<&str>,
tokens: &[String],
token_types: Option<&[u32]>,
chat_template: &str,
) -> GgufResult<()> {
if model != "gpt2" || pre.is_some_and(|value| value != "qwen35") {
return Err(gguf_error(
"only the qwen35 byte-level BPE tokenizer is supported",
));
}
if tokens.is_empty() || chat_template.is_empty() {
return Err(gguf_error(
"GGUF tokenizer has an empty vocabulary or chat template",
));
}
if token_types.is_some_and(|types| types.len() != tokens.len()) {
return Err(gguf_error(
"token_type length differs from vocabulary length",
));
}
Ok(())
}
fn validate_vocabulary(tokens: &[String]) -> GgufResult<HashSet<&str>> {
let vocab: HashSet<&str> = tokens.iter().map(String::as_str).collect();
if vocab.len() != tokens.len() {
return Err(gguf_error(
"GGUF tokenizer has duplicate vocabulary entries",
));
}
Ok(vocab)
}
fn validate_merges(merges: &[String], vocab: &HashSet<&str>) -> GgufResult<()> {
let mut seen_merges = HashSet::new();
for merge in merges {
let Some((left, right)) = merge.split_once(' ') else {
return Err(gguf_error("GGUF BPE merge is not a pair"));
};
if !valid_merge(left, right, vocab) || !seen_merges.insert(merge) {
return Err(gguf_error("GGUF BPE merge is invalid or duplicated"));
}
}
Ok(())
}
fn valid_merge(left: &str, right: &str, vocab: &HashSet<&str>) -> bool {
!left.is_empty()
&& !right.is_empty()
&& !right.contains(' ')
&& vocab.contains(left)
&& vocab.contains(right)
}
fn validate_special_ids(ids: &BTreeMap<String, u32>, token_count: usize) -> GgufResult<()> {
if ids.values().any(|id| *id as usize >= token_count) {
return Err(gguf_error("special token ID exceeds vocabulary"));
}
Ok(())
}
fn gguf_error(message: impl Into<String>) -> GgufTokenizerError {
GgufTokenizerError(message.into())
}
struct GgufCursor {
file: File,
size: u64,
}
impl GgufCursor {
fn open(path: &Path) -> GgufResult<Self> {
let file = File::open(path).map_err(|error| gguf_error(error.to_string()))?;
let size = file
.metadata()
.map_err(|error| gguf_error(error.to_string()))?
.len()
.min(MAX_GGUF_HEADER_BYTES);
Ok(Self { file, size })
}
fn validate_file(&mut self) -> GgufResult<()> {
if self.take(4)? != b"GGUF" {
return Err(gguf_error("not a GGUF file"));
}
if self.u32()? != 3 {
return Err(gguf_error("only GGUF v3 is supported"));
}
self.skip(8)
}
fn metadata_entry_count(&mut self) -> GgufResult<u64> {
let count = self.u64()?;
if count > MAX_GGUF_METADATA_ENTRIES {
return Err(gguf_error("unreasonable GGUF metadata entry count"));
}
self.validate_entry_envelope(count)?;
Ok(count)
}
fn validate_entry_envelope(&mut self, count: u64) -> GgufResult<()> {
let minimum_bytes = count
.checked_mul(13)
.ok_or_else(|| gguf_error("GGUF metadata entry count overflow"))?;
if minimum_bytes > self.remaining()? {
return Err(gguf_error("GGUF metadata count exceeds bounded header"));
}
Ok(())
}
fn position(&mut self) -> GgufResult<u64> {
self.file
.stream_position()
.map_err(|error| gguf_error(error.to_string()))
}
fn remaining(&mut self) -> GgufResult<u64> {
Ok(self.size.saturating_sub(self.position()?))
}
fn skip(&mut self, bytes: u64) -> GgufResult<()> {
let end = self
.position()?
.checked_add(bytes)
.ok_or_else(|| gguf_error("GGUF offset overflow"))?;
if end > self.size {
return Err(gguf_error("truncated or oversized GGUF metadata header"));
}
self.file
.seek(SeekFrom::Start(end))
.map_err(|error| gguf_error(error.to_string()))?;
Ok(())
}
fn take(&mut self, size: usize) -> GgufResult<Vec<u8>> {
if self
.position()?
.checked_add(size as u64)
.is_none_or(|end| end > self.size)
{
return Err(gguf_error("truncated or oversized GGUF metadata header"));
}
let mut data = vec![0; size];
self.file
.read_exact(&mut data)
.map_err(|error| gguf_error(error.to_string()))?;
Ok(data)
}
fn u8(&mut self) -> GgufResult<u8> {
Ok(self.take(1)?[0])
}
fn u16(&mut self) -> GgufResult<u16> {
let bytes = self.take(2)?;
Ok(u16::from_le_bytes([bytes[0], bytes[1]]))
}
fn u32(&mut self) -> GgufResult<u32> {
let bytes = self.take(4)?;
Ok(u32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]))
}
fn u64(&mut self) -> GgufResult<u64> {
let bytes = self.take(8)?;
Ok(u64::from_le_bytes([
bytes[0], bytes[1], bytes[2], bytes[3], bytes[4], bytes[5], bytes[6], bytes[7],
]))
}
fn string(&mut self) -> GgufResult<String> {
let size = self.u64()?;
if size > MAX_GGUF_STRING_BYTES {
return Err(gguf_error("GGUF header string is too large"));
}
String::from_utf8(self.take(size as usize)?)
.map_err(|error| gguf_error(format!("GGUF header string is not UTF-8: {error}")))
}
fn string_array(&mut self, kind: u32) -> GgufResult<Vec<String>> {
if kind != 9 || self.u32()? != 8 {
return Err(gguf_error("expected a GGUF string array"));
}
let count = self.u64()?;
self.check_tokenizer_array(count, 8)?;
let capacity = usize::try_from(count)
.map_err(|_| gguf_error("GGUF tokenizer array count exceeds platform limits"))?;
let mut total = 0u64;
let mut values = Vec::with_capacity(capacity);
for _ in 0..count {
let value = self.string()?;
total = total
.checked_add(value.len() as u64)
.ok_or_else(|| gguf_error("GGUF tokenizer array size overflow"))?;
if total > MAX_TOKENIZER_ARRAY_BYTES {
return Err(gguf_error("GGUF tokenizer array exceeds 512 MiB"));
}
values.push(value);
}
Ok(values)
}
fn integer_array(&mut self, kind: u32) -> GgufResult<Vec<u32>> {
if kind != 9 {
return Err(gguf_error("expected a GGUF integer array"));
}
let element = self.u32()?;
let count = self.u64()?;
let width = value_width(element)?;
self.check_tokenizer_array(count, width)?;
let capacity = usize::try_from(count)
.map_err(|_| gguf_error("GGUF tokenizer array count exceeds platform limits"))?;
let mut values = Vec::with_capacity(capacity);
for _ in 0..count {
values.push(self.integer(element)?);
}
Ok(values)
}
fn check_tokenizer_array(&mut self, count: u64, minimum_item_bytes: u64) -> GgufResult<()> {
if count > MAX_TOKENIZER_ARRAY_ITEMS {
return Err(gguf_error("unreasonable GGUF tokenizer array count"));
}
let minimum_bytes = count
.checked_mul(minimum_item_bytes)
.ok_or_else(|| gguf_error("GGUF tokenizer array size overflow"))?;
if minimum_bytes > self.remaining()? {
return Err(gguf_error("GGUF tokenizer array exceeds remaining header"));
}
Ok(())
}
fn integer(&mut self, kind: u32) -> GgufResult<u32> {
match kind {
0 | 7 => Ok(u32::from(self.u8()?)),
1 => u32::try_from(self.u8()? as i8)
.map_err(|_| gguf_error("negative GGUF integer is unsupported")),
2 => Ok(u32::from(self.u16()?)),
3 => u32::try_from(self.u16()? as i16)
.map_err(|_| gguf_error("negative GGUF integer is unsupported")),
4 => self.u32(),
5 => u32::try_from(self.u32()? as i32)
.map_err(|_| gguf_error("negative GGUF integer is unsupported")),
10 => u32::try_from(self.u64()?)
.map_err(|_| gguf_error("GGUF integer exceeds 32-bit range")),
11 => u32::try_from(self.u64()? as i64)
.map_err(|_| gguf_error("negative or oversized GGUF integer is unsupported")),
_ => Err(gguf_error(format!(
"GGUF metadata type {kind} is not an integer"
))),
}
}
fn skip_value(&mut self, kind: u32) -> GgufResult<()> {
match kind {
0 | 1 | 7 => self.skip(1),
2 | 3 => self.skip(2),
4..=6 => self.skip(4),
8 => {
let size = self.u64()?;
self.skip(size)
}
9 => self.skip_array_value(),
10..=12 => self.skip(8),
_ => Err(gguf_error(format!("unknown GGUF metadata type {kind}"))),
}
}
fn skip_array_value(&mut self) -> GgufResult<()> {
let element = self.u32()?;
let count = self.u64()?;
match element {
8 => self.skip_string_array(count),
9 => Err(gguf_error("nested GGUF arrays are unsupported")),
_ => self.skip_typed_array(element, count),
}
}
fn skip_string_array(&mut self, count: u64) -> GgufResult<()> {
if count > MAX_GGUF_METADATA_ENTRIES {
return Err(gguf_error("unreasonable GGUF string array count"));
}
self.validate_string_array_size(count)?;
for _ in 0..count {
self.skip_string_array_item()?;
}
Ok(())
}
fn validate_string_array_size(&mut self, count: u64) -> GgufResult<()> {
let bytes = count
.checked_mul(8)
.ok_or_else(|| gguf_error("GGUF string array size overflow"))?;
if bytes > self.remaining()? {
return Err(gguf_error("GGUF string array exceeds remaining header"));
}
Ok(())
}
fn skip_string_array_item(&mut self) -> GgufResult<()> {
let size = self.u64()?;
if size > MAX_GGUF_HEADER_BYTES {
return Err(gguf_error("GGUF string array element is too large"));
}
self.skip(size)
}
fn skip_typed_array(&mut self, element: u32, count: u64) -> GgufResult<()> {
let width = value_width(element)?;
let bytes = count
.checked_mul(width)
.ok_or_else(|| gguf_error("GGUF array size overflow"))?;
self.skip(bytes)
}
}
fn value_width(kind: u32) -> GgufResult<u64> {
match kind {
0 | 1 | 7 => Ok(1),
2 | 3 => Ok(2),
4..=6 => Ok(4),
10..=12 => Ok(8),
_ => Err(gguf_error(format!(
"invalid GGUF array element type {kind}"
))),
}
}
type HeapEntry = (usize, usize, usize, u64, u64);
struct Node {
@@ -494,3 +982,282 @@ mod tests {
fs::remove_dir_all(root).unwrap();
}
}
#[cfg(test)]
mod gguf_metadata_tests {
use super::*;
use std::path::PathBuf;
use std::sync::atomic::{AtomicU64, Ordering};
static NEXT_FIXTURE: AtomicU64 = AtomicU64::new(0);
fn fixture_path() -> PathBuf {
std::env::temp_dir().join(format!(
"leleka-tokenizer-gguf-{}-{}",
std::process::id(),
NEXT_FIXTURE.fetch_add(1, Ordering::Relaxed)
))
}
fn gguf_string(bytes: &mut Vec<u8>, value: &str) {
bytes.extend_from_slice(&(value.len() as u64).to_le_bytes());
bytes.extend_from_slice(value.as_bytes());
}
fn string_field(bytes: &mut Vec<u8>, key: &str, value: &str) {
gguf_string(bytes, key);
bytes.extend_from_slice(&8u32.to_le_bytes());
gguf_string(bytes, value);
}
fn string_array(bytes: &mut Vec<u8>, key: &str, values: &[&str]) {
gguf_string(bytes, key);
bytes.extend_from_slice(&9u32.to_le_bytes());
bytes.extend_from_slice(&8u32.to_le_bytes());
bytes.extend_from_slice(&(values.len() as u64).to_le_bytes());
for value in values {
gguf_string(bytes, value);
}
}
fn base() -> Vec<u8> {
let mut bytes = b"GGUF".to_vec();
bytes.extend_from_slice(&3u32.to_le_bytes());
bytes.extend_from_slice(&0u64.to_le_bytes());
bytes.extend_from_slice(&7u64.to_le_bytes());
string_field(&mut bytes, "tokenizer.ggml.model", "gpt2");
string_field(&mut bytes, "tokenizer.ggml.pre", "qwen35");
string_array(
&mut bytes,
"tokenizer.ggml.tokens",
&["a", "b", "ab", "<|eos|>"],
);
string_array(&mut bytes, "tokenizer.ggml.merges", &["a b"]);
gguf_string(&mut bytes, "tokenizer.ggml.token_type");
bytes.extend_from_slice(&9u32.to_le_bytes());
bytes.extend_from_slice(&4u32.to_le_bytes());
bytes.extend_from_slice(&4u64.to_le_bytes());
for value in [1u32, 1, 1, 3] {
bytes.extend_from_slice(&value.to_le_bytes());
}
gguf_string(&mut bytes, "tokenizer.ggml.eos_token_id");
bytes.extend_from_slice(&4u32.to_le_bytes());
bytes.extend_from_slice(&3u32.to_le_bytes());
string_field(&mut bytes, "tokenizer.chat_template", "{{ messages }}");
bytes
}
fn with_bytes(bytes: &[u8], check: impl FnOnce(&Path)) {
let path = fixture_path();
fs::write(&path, bytes).unwrap();
check(&path);
fs::remove_file(path).unwrap();
}
fn assert_metadata_rejected(bytes: &[u8]) {
with_bytes(bytes, |path| {
assert!(read_gguf_tokenizer_metadata(path).is_err());
});
}
fn token_array_count_offset(bytes: &[u8]) -> usize {
let marker = b"tokenizer.ggml.tokens";
let start = bytes
.windows(marker.len())
.position(|window| window == marker)
.unwrap();
start + 8 + marker.len() + 4 + 4
}
fn replace_pre_with_integer(bytes: &mut Vec<u8>) {
let marker = b"tokenizer.ggml.pre";
let start = bytes
.windows(marker.len())
.position(|window| window == marker)
.unwrap();
let kind = start + marker.len();
let value = kind + 4;
let end = value + 8 + b"qwen35".len();
bytes[kind..value].copy_from_slice(&4u32.to_le_bytes());
bytes.splice(value..end, 1u32.to_le_bytes());
}
#[test]
fn reads_qwen35_tokenizer_metadata_with_control_plane_parity() {
with_bytes(&base(), |path| {
let metadata = read_gguf_tokenizer_metadata(path).unwrap();
assert_eq!(metadata.model, "gpt2");
assert_eq!(metadata.pre, "qwen35");
assert_eq!(metadata.tokens, ["a", "b", "ab", "<|eos|>"]);
assert_eq!(metadata.merges, ["a b"]);
assert_eq!(metadata.token_types, Some(vec![1, 1, 1, 3]));
assert_eq!(metadata.special_ids["tokenizer.ggml.eos_token_id"], 3);
assert_eq!(metadata.chat_template, "{{ messages }}");
});
}
#[test]
fn rejects_wrong_magic() {
let mut bytes = base();
bytes[0] = b'X';
assert_metadata_rejected(&bytes);
}
#[test]
fn rejects_unsupported_version() {
let mut bytes = base();
bytes[4..8].copy_from_slice(&2u32.to_le_bytes());
assert_metadata_rejected(&bytes);
}
#[test]
fn rejects_truncated_metadata() {
let bytes = base();
assert_metadata_rejected(&bytes[..bytes.len() - 2]);
}
#[test]
fn rejects_excessive_metadata_count() {
let mut bytes = b"GGUF".to_vec();
bytes.extend_from_slice(&3u32.to_le_bytes());
bytes.extend_from_slice(&0u64.to_le_bytes());
bytes.extend_from_slice(&u64::MAX.to_le_bytes());
assert_metadata_rejected(&bytes);
}
#[test]
fn rejects_oversized_metadata_string() {
let mut bytes = b"GGUF".to_vec();
bytes.extend_from_slice(&3u32.to_le_bytes());
bytes.extend_from_slice(&0u64.to_le_bytes());
bytes.extend_from_slice(&1u64.to_le_bytes());
bytes.extend_from_slice(&(MAX_GGUF_STRING_BYTES + 1).to_le_bytes());
bytes.extend_from_slice(&[0; 5]);
assert_metadata_rejected(&bytes);
}
#[test]
fn rejects_excessive_token_array_count() {
let mut bytes = base();
let count_at = token_array_count_offset(&bytes);
bytes[count_at..count_at + 8]
.copy_from_slice(&(MAX_TOKENIZER_ARRAY_ITEMS + 1).to_le_bytes());
assert_metadata_rejected(&bytes);
}
#[test]
fn rejects_token_array_count_overflow() {
let mut bytes = base();
let count_at = token_array_count_offset(&bytes);
bytes[count_at..count_at + 8].copy_from_slice(&u64::MAX.to_le_bytes());
assert_metadata_rejected(&bytes);
}
#[test]
fn rejects_duplicate_tokenizer_metadata() {
let mut bytes = base();
string_field(&mut bytes, "tokenizer.ggml.model", "gpt2");
bytes[16..24].copy_from_slice(&8u64.to_le_bytes());
assert_metadata_rejected(&bytes);
}
#[test]
fn rejects_duplicate_vocabulary_tokens() {
let mut bytes = base();
let marker = b"tokenizer.ggml.tokens";
let at = bytes
.windows(marker.len())
.position(|w| w == marker)
.unwrap();
let third_token_len_at = at + 8 + marker.len() + 4 + 4 + 8 + 8 + 1 + 8 + 1;
bytes[third_token_len_at..third_token_len_at + 8].copy_from_slice(&1u64.to_le_bytes());
bytes.copy_within(third_token_len_at + 8 + 2.., third_token_len_at + 8 + 1);
bytes.truncate(bytes.len() - 1);
with_bytes(&bytes, |path| {
let result = read_gguf_tokenizer_metadata(path);
assert!(result.is_err(), "unexpected parse result: {result:?}");
});
}
#[test]
fn rejects_special_token_id_outside_vocabulary() {
let mut bytes = base();
let marker = b"tokenizer.ggml.eos_token_id";
let at = bytes
.windows(marker.len())
.position(|w| w == marker)
.unwrap();
let value_at = at + 8 + marker.len() + 4;
bytes[value_at..value_at + 4].copy_from_slice(&99u32.to_le_bytes());
assert_metadata_rejected(&bytes);
}
#[test]
fn rejects_invalid_merge() {
let mut bytes = base();
let marker = b"tokenizer.ggml.merges";
let at = bytes
.windows(marker.len())
.position(|w| w == marker)
.unwrap();
let value_at = at + 8 + marker.len() + 4 + 4 + 8 + 8;
bytes[value_at..value_at + 3].copy_from_slice(b"x y");
assert_metadata_rejected(&bytes);
}
#[test]
fn rejects_mismatched_token_types_length() {
let mut bytes = base();
let marker = b"tokenizer.ggml.token_type";
let at = bytes
.windows(marker.len())
.position(|w| w == marker)
.unwrap();
let count_at = at + 8 + marker.len() + 4 + 4;
bytes[count_at..count_at + 8].copy_from_slice(&3u64.to_le_bytes());
bytes.drain(count_at + 8 + 4 * 3..count_at + 8 + 4 * 4);
assert_metadata_rejected(&bytes);
}
#[test]
fn rejects_unknown_metadata_type() {
let mut bytes = base();
bytes.extend_from_slice(&("x".len() as u64).to_le_bytes());
bytes.extend_from_slice(b"x");
bytes.extend_from_slice(&99u32.to_le_bytes());
bytes.extend_from_slice(&8u64.to_le_bytes());
bytes[16..24].copy_from_slice(&8u64.to_le_bytes());
assert_metadata_rejected(&bytes);
}
#[test]
fn rejects_present_non_string_pre_tokenizer() {
let mut bytes = base();
replace_pre_with_integer(&mut bytes);
with_bytes(&bytes, |path| {
let error = read_gguf_tokenizer_metadata(path).unwrap_err();
assert!(
error
.to_string()
.contains("tokenizer.ggml.pre must be a string")
);
});
}
#[test]
fn missing_pre_tokenizer_uses_the_existing_qwen_default() {
let mut bytes = base();
let marker = b"tokenizer.ggml.pre";
let at = bytes
.windows(marker.len())
.position(|w| w == marker)
.unwrap();
let start = at - 8;
let end = at + marker.len() + 4 + 8 + b"qwen35".len();
bytes.drain(start..end);
bytes[16..24].copy_from_slice(&6u64.to_le_bytes());
with_bytes(&bytes, |path| {
assert_eq!(read_gguf_tokenizer_metadata(path).unwrap().pre, "qwen35");
});
}
}
+34
View File
@@ -0,0 +1,34 @@
FROM --platform=linux/amd64 ubuntu:24.04@sha256:f610ab94648195aa356059f5b41d6085c9d4d903c072430cdd1af7bdb646106b
ENV DEBIAN_FRONTEND=noninteractive
# The minimal pinned Ubuntu base has no CA store. Seed it from the trusted
# Linux CI runner so HTTPS verification works before apt installs ca-certificates.
COPY runner-ca-certificates.crt /etc/ssl/certs/ca-certificates.crt
# Freeze Ubuntu's package view as well as the base-image digest. CUDA itself is
# supplied separately by the checksum-pinned redistributable bundle.
RUN rm -f /etc/apt/sources.list.d/ubuntu.sources /etc/apt/sources.list && \
printf '%s\n' \
'deb [check-valid-until=no] https://snapshot.ubuntu.com/ubuntu/20260917T000000Z noble main universe' \
'deb [check-valid-until=no] https://snapshot.ubuntu.com/ubuntu/20260917T000000Z noble-updates main universe' \
'deb [check-valid-until=no] https://snapshot.ubuntu.com/ubuntu/20260917T000000Z noble-security main universe' \
> /etc/apt/sources.list && \
apt-get -o Acquire::Check-Valid-Until=false update && \
apt-get install -y --no-install-recommends \
ca-certificates cmake gcc-13 g++-13 git make ninja-build python3 python3-numpy && \
rm -rf /var/lib/apt/lists/* && \
test "$(gcc-13 -dumpfullversion | cut -d. -f1)" = 13 && \
mkdir -p /stage/source /stage/toolkit /build && chmod 1777 /build
ENV CUDACXX=/opt/cuda/bin/nvcc \
CUDAToolkit_ROOT=/opt/cuda \
CUDAHOSTCXX=/usr/bin/g++-13 \
CC=/usr/bin/gcc-13 \
CXX=/usr/bin/g++-13 \
CUDA_VISIBLE_DEVICES= \
NVIDIA_VISIBLE_DEVICES=void \
HOME=/tmp/home
WORKDIR /workspace
ENTRYPOINT ["/bin/bash"]
+4 -1
View File
@@ -7,8 +7,11 @@ RUN apt-get update \
RUN rustup target add "${RUST_TARGET}"
WORKDIR /src
COPY Cargo.toml Cargo.lock ./
COPY rust-toolchain.toml ./
COPY manifests/ ./manifests/
COPY crates/ ./crates/
COPY desktop-core/ ./desktop-core/
COPY control-plane/ ./control-plane/
COPY engine/strata/LICENSE ./engine/strata/LICENSE
RUN cargo build --manifest-path control-plane/Cargo.toml --locked --release \
@@ -16,5 +19,5 @@ RUN cargo build --manifest-path control-plane/Cargo.toml --locked --release \
FROM scratch
ARG RUST_TARGET=x86_64-unknown-linux-musl
COPY --from=build /src/control-plane/target/${RUST_TARGET}/release/strata-next /strata-next
COPY --from=build /src/target/${RUST_TARGET}/release/strata-next /strata-next
ENTRYPOINT ["/strata-next"]
+12
View File
@@ -0,0 +1,12 @@
FROM debian:bookworm-slim
ENV container=docker
RUN apt-get update \
&& DEBIAN_FRONTEND=noninteractive apt-get install --yes --no-install-recommends \
ca-certificates dbus-user-session python3 systemd systemd-sysv util-linux \
&& useradd --create-home --uid 1000 --shell /bin/sh leleka \
&& rm -rf /var/lib/apt/lists/*
STOPSIGNAL SIGRTMIN+3
CMD ["/sbin/init"]
+31 -20
View File
@@ -602,21 +602,27 @@ CMake's static CUDA runtime and cuBLAS targets and statically links the engine's
GNU C++ runtime. The default CUDA profile continues to use shared toolkit
libraries. HIP and non-Linux/GNU configurations reject this option.
On a Linux builder with the toolkit and CMake already installed:
On a Linux x86_64 host with Docker and the pinned CUDA toolkit bundle already
bootstrapped, use the repository wrapper to build inside a digest-pinned Ubuntu
24.04 amd64 image. The source checkout and toolkit are read-only mounts, output
paths must be fresh and outside the checkout, and no GPU device is passed into
the container:
```sh
export CUDACXX=/absolute/path/to/cuda/bin/nvcc
export CUDAToolkit_ROOT=/absolute/path/to/cuda
# Optional existing pinned llama.cpp checkout; otherwise CMake fetches its pinned source:
export STRATA_GGML_DIR=/absolute/path/to/llama.cpp
BUILD_JOBS=2 scripts/build-static-cuda.sh
python3 scripts/bootstrap-cuda-toolkit.py --output /tmp/strata-cuda-toolkit
python3 scripts/build-cuda-engine-in-docker.py \
--toolkit /tmp/strata-cuda-toolkit \
--build-dir /tmp/strata-cuda-build \
--output /tmp/strata-cuda-output/strata \
--metadata /tmp/strata-cuda-output/CUDA-BUILDER.json \
--image-tag local-1
```
The script builds only `strata`, using SM 120 and portable AVX2 GGML defaults;
`CUDA_ARCHITECTURES` and `STRATA_BUILD_DIR` can override the build target/path.
It audits ELF dependencies and runs only `--help` with no GPU visible. It does
not install anything, serve a model, change a service, or run a speed test.
CMake's imported targets provide the static dependency closure; see the
The wrapper compiles only `strata`, using SM 120 and portable AVX2 GGML defaults;
`CUDA_ARCHITECTURES` remains configurable in `scripts/build-static-cuda.sh`.
It audits ELF dependencies and runs only `--help` with NVIDIA device nodes hidden.
It does not install anything, serve a model, change a service, run a kernel, or
measure speed. CMake's imported targets provide the static dependency closure; see the
[FindCUDAToolkit reference](https://cmake.org/cmake/help/latest/module/FindCUDAToolkit.html).
The measured CUDA 13.2 build has only `libm.so.6`, `libc.so.6` and the host loader
@@ -638,10 +644,16 @@ the dynamic engine. See the [packaging report](../docs/experiments/2026-10-04-la
No quality, numerical parity, speedup or production-ready claim follows from
linking successfully. Keep the default profile until the model gates pass.
The optional `static_cuda_package` workflow-dispatch job performs the build and
ELF audit on the private CUDA runner without inference. It publishes no package
and cleans its private build directory. The runner must have the required
compiler/toolkit in its environment; hosted execution has not yet occurred.
The optional `hosted_cuda_package` workflow-dispatch job bootstraps the
checksum-pinned toolkit on the generic Linux runner, then builds the actual CUDA
engine in this GPU-hidden Docker image before assembling the executable and OCI
preview. It publishes a private prerelease asset with provenance and checksums.
This verifies compilation, ELF dependencies and GPU-hidden help only; the host
driver, kernel execution, real model, quality and performance still require
separate GPU qualification. This job publishes a private prerelease because
the Gitea instance does not support the GitHub-hosted `upload-artifact` action.
The independent `keyless_gpu` job remains opt-in and requires an actual GPU
runner for kernel-execution tests.
## Fetch pinned assets as part of native startup
@@ -997,11 +1009,10 @@ operator/CI-declared provenance, not a binary-to-source attestation, and this
pipeline does not promise bit-identical compiler output. Python is used only on
the build host; the resulting runtime does not require it.
The manual `static_cuda_package` workflow builds the engine then assembles and
uploads the combined preview to the **private repository**, with seven-day
artifact retention. It cleans owned build directories after the upload attempt; the final package
copy is removed only after a successful upload. A failed upload leaves that
private final package available for recovery.
The manual `hosted_cuda_package` workflow builds the engine inside a pinned,
GPU-hidden Docker builder on the generic Linux CPU runner, assembles the combined
preview, and publishes it as a private prerelease with provenance and checksums.
The workflow removes its local package copy only after successful publication.
The normal hosted job uses `--cpu-fixture` to exercise the same assembly path and
then tests exact serving output/restart against the external fixture. CPU
artifacts are explicitly marked and are not CUDA releases. No model weights,
+24 -9
View File
@@ -1,5 +1,12 @@
# Build validation
## 2026-10-06 — KAR overlay publication recovery
- Overlay preparation records a source/policy-bound pending intent before archive publication, verifies the archive before atomically publishing its separate sidecar, reads the sidecar back, and removes the intent last. Retry tests cover interruption before archive creation and after archive, sidecar, or intent publication; unrelated archive and sidecar bytes are preserved.
- `cargo fmt --manifest-path control-plane/Cargo.toml --check`, all-target Clippy with warnings denied, `cargo test --manifest-path control-plane/Cargo.toml --locked` (198 Rust tests), and `scripts/check-local.sh`'s Python/Rust/replay stages passed. The script stops at the host CPU build because CMake is unavailable on this macOS host.
- The CPU CMake/CTest stage passed separately inside GPU-hidden Docker using Ubuntu 24.04 arm64 digest `sha256:534baea6a22c03a63003dbc8dbe78fe34bc0d7e595d9a9dc9834884ff530eb55`, CMake 3.28.3, and GCC 13.3.0: five CTest tests passed. The container had no GPU device or NVIDIA runtime and was removed automatically.
- Required §702.1 changed-scope 100% line/function/branch coverage remains **unverified**. The permitted branch-capable coverage attempt was SIGKILLed before it produced a valid machine-readable report; no partial percentage is treated as a pass. This validation does not establish installed-driver inference, model quality, or rollback.
## 2026-10-03 — experimental PLE quality arm
The imported engine builds on Linux CUDA 13.2/sm_120 with the optional
@@ -139,6 +146,7 @@ The test toolchain was installed into ignored `artifacts/tool-venv/` for this ru
- Command: `strata-next model prepare-sharded-streamed qwen-iq3-s --source-dir /Users/para/.local/share/strata-next/qwen-iq3-s --output /Users/para/.local/share/strata-next/qwen-iq3-s-l2-v4.kar --levels 2`.
- The complete archive has **55,295,529,472 bytes** (51.49797487 GiB) across 1,225 KAR records; the two GGUF shards have 83,617,662,656 bytes. Archive/source ratio is 0.66129006, saving 28,322,133,184 bytes (33.87099%). Accounted rate is 2.500025 bits per derived F32 weight. Archive SHA-256 is `536d612ca60eab460cb978f51748fc6fa4e9d611d4601e777884e8b51385afa5`; derived F32 SHA-256 is `c89bfcea7b1c979ad2e9e64c59fcc3c03fc414b345c5f47f027ce0ba99015479`.
- The writer's full payload CRC verification passed before atomic publication, and a versioned provenance sidecar was written. The maximum tensor relative L2 error measured during encoding was 0.68008092. This is **not** a model-level quality result or permission to serve with KAR-2. No Linux GPU inference, GPU decode, or paired end-to-end throughput result exists yet.
- Archive publication keeps a source/policy-bound pending intent until the provenance sidecar is atomically linked. Deterministic fault tests cover destination hash failure, sidecar publication failure, provenance and pending-intent temporary cleanup failure, and archive temporary-link cleanup failure. Retry verifies source shards, KAR records and payload CRCs before recovering the matching sidecar; no existing archive or provenance file is replaced. This makes an interrupted publication recoverable, but does not change the archive's lossy quality status.
- A separate `model verify-sharded-streamed /Users/para/.local/share/strata-next/qwen-iq3-s-l2-v4.kar --manifest qwen-iq3-s --source-dir /Users/para/.local/share/strata-next/qwen-iq3-s --levels 2` run exited successfully. It recomputed the derived F32 source identity, checked both manifest shards, all 1,225 KAR source records and payload CRCs, the archive SHA-256, and the v4 provenance policy. The provenance sidecar SHA-256 is `3edceb512c386ea4552a3e5d3d49fbd841f7bd1b314aeba8b2a87ac811a8a6b5`. Temporary section files, old real-data slices, local header fixtures, and superseded local Docker images were removed; both verified GGUF shards, the final KAR, and its provenance remain outside Git.
## 2026-10-03 — outer block codec and selective precision probes
@@ -796,8 +804,9 @@ readiness remain separate acceptance gates. No image is pushed to a registry.
`workflow_dispatch` input `hosted_cuda_package=true` selects a private-repository
Ubuntu 24.04 CPU job. It never targets the private GPU runner. The existing
`static_cuda_package` and `keyless_gpu` inputs remain false unless explicitly
selected. This build does not load a model or install a driver.
`keyless_gpu` input remains false unless explicitly selected and requires a
dedicated GPU runner. The CUDA build route itself needs only the generic Linux
CPU runner. This build does not load a model or install a driver.
The build-only `scripts/bootstrap-cuda-toolkit.py` assembles seven components
from NVIDIA's [CUDA 13.0.1 redistrib manifest](https://developer.download.nvidia.com/compute/cuda/redist/redistrib_13.0.1.json),
@@ -807,9 +816,13 @@ prefix, bounded downloads/expansion, safe tar extraction, collision/link checks
and retained component licenses avoid a system CUDA installation. This is a
build dependency bootstrap, not an end-user runtime installer. NVIDIA documents
[component assembly and supported host compilers](https://docs.nvidia.com/cuda/archive/13.0.1/cuda-installation-guide-linux/index.html).
The job explicitly uses GCC 13, one engine compile job, two Rust build jobs and a
150-minute job limit; it refuses acquisition below 6 GiB RAM or 12 GiB free disk.
Actual host/compiler versions and initial resources are recorded. Toolkit bytes
The job builds the CUDA engine with `scripts/build-cuda-engine-in-docker.py` in a
digest-pinned Ubuntu 24.04 amd64 Docker builder, with the source and toolkit
mounted read-only and no GPU devices or NVIDIA container runtime. GCC 13 is
scoped to the engine builder; the job uses one engine compile job, two Rust build
jobs and a 150-minute limit. The toolkit bootstrap refuses acquisition below 6
GiB RAM or 12 GiB free disk. Container compiler/image identity and initial host
resources are recorded. Toolkit bytes
are pinned; hosted OS/compiler patch updates mean byte-identical rebuilds are
not asserted.
@@ -825,11 +838,13 @@ equality remain mandatory checks for this build-path change.
Existing static-engine, combined-package and OCI builders supply the actual
compile/link, dependency/ABI, embedded identity and GPU-hidden help gates.
The private `strata-next-hosted-cuda-preview` artifact retains package checksums,
The private prerelease `cuda-preview-<run>.<attempt>` retains package checksums,
source provenance, image archive/receipt, exact toolkit manifest/toolchain data
and component license archive. Retention is seven days. Successful upload is
required; an ephemeral hosted runner is not durable fallback storage if upload
fails. Owned build directories and image are cleaned. Tests use deliberately
and component license archive. Publishing uses the same Gitea-compatible `gh
release create` path as the CLI preview; the unsupported `actions/upload-artifact`
action is not used. A failed publication fails the job; an ephemeral hosted
runner is not durable fallback storage if publication fails. Owned build
directories and image are cleaned. Tests use deliberately
invalid archives/receipts and do not require CUDA; only a successful manual
actual-CUDA job qualifies compilation and packaging. GPU driver loading,
full-model/MTP inference, quality and clean-node rollback remain separate gates.
+26
View File
@@ -139,6 +139,30 @@ The CPU quality oracle can decode up to one million values from an arbitrary nes
`model ensure-sharded-streamed MANIFEST --source-dir DIR --output FILE.kar --levels N` adds the opt-in fetch → source verify → streamed prepare → archive verify sequence. On rerun it only reuses an archive after fresh shard, payload, and provenance checks; a damaged archive or changed level fails closed. The measured level-2 real-model archive is 55,295,529,472 bytes (51.50 GiB); its model quality remains unmeasured. Use an external model volume or the Linux GPU host for preparation.
Streamed publication is retry-safe across the archive/provenance boundary. Before
the no-replace archive link, preparation publishes a `.pending.json` intent that
binds the verified source identity and exact partition/level policy. If hashing
the published archive or publishing its provenance sidecar fails, the archive
and intent are retained. A later `ensure-sharded-streamed` may recover only
when that intent matches the current pinned shards and policy and a fresh
independent archive verification succeeds; it then writes the sidecar with a
no-replace link. An archive without a matching intent is never adopted, and an
existing sidecar or archive is never overwritten. Temporary-link cleanup after
a successful archive publication is retried once and cannot invalidate the
atomically linked destination; overlay preparation continues to provenance
publication after that final link. KAR writer temporary names are scoped to the
destination and one of eight fixed slots, created exclusively with mode `0600`,
and held under an advisory lock while being written and verified. This bounds
crash-left archive temp files per destination. A later write reaps only matching
temporary files when it can acquire the lock and confirm current-user ownership
and inode identity. Writers also verify that a newly locked slot still names
their opened inode before using it, closing the race with reaping. An unlinked
pre-publication crash partial is never confused with a final archive; a
published hard-link temporary is removed only when it is the same inode as
that destination. Recovery proves artifact integrity only, not lossy model
quality or serving readiness. Unknown or legacy temporary names are preserved
rather than guessed at or deleted.
`model ensure-sharded-streamed MANIFEST --source-dir DIR --output FILE.kar --levels 2 --ple-part-elements 100000000` selects an experimental v5 partition policy. Only `per_layer_token_embd.weight` gets the smaller limit; other tensors keep the v4 limit. The policy is encoded in the KAR builder string and provenance, and the matching verifier reconstructs every part from the pinned GGUF source. Reuse with another limit or the v4 command fails closed. For the target PLE dimensions, this limit plans 513 adjacent parts of at most 100 million elements, each aligned to complete GGUF rows and quantization blocks. This is a layout calculation, not a new measured archive size or GPU result. Overlay preparation and paired comparison now accept a single split PLE part in a v5 base; a synthetic fixture covers this path, while no full v5 model overlay has been produced. The existing v4 archive and its overlay remain the preserved comparison artifacts; producing a second full-model archive requires more free external storage than is currently available locally.
The streamed assembly now consumes private staged sections as it copies them into the archive, then independently verifies the finished archive before publication. This keeps peak preparation space close to the larger of staged sections or final archive, plus the source shards, rather than requiring both copies of the encoded payload at once. A later shard may omit `general.architecture`; all shards that declare it must agree, and at least one must supply it. The target model's second shard has this metadata shape.
@@ -155,6 +179,8 @@ For the target compressed runtime, copy the selected KAR data to VRAM in compres
The user-facing Linux command checks the installed NVIDIA driver and starts the native engine. It does not carry the driver. The single-file GPU packaging goal still needs a real Linux CUDA build and loader test.
Experimental `model prepare-kar-overlay` writes a matching `.pending.json` intent before publishing its archive. On retry it verifies the intent, KAR records/CRC and source identity before completing a missing provenance sidecar; the sidecar is no-replace and the intent is removed only after sidecar read-back verification. A complete archive and sidecar without an intent are reused only when both match the current inputs. Incomplete or unrelated outputs fail closed and are never overwritten. This is publication recovery, not approval of the lossy overlay for serving.
## Cache profiles
| Profile | Attention state | Status |
+9
View File
@@ -39,6 +39,15 @@ The acquisition stage downloads GGUF files; the native tokenizer stage extracts
`model inspect` reads the GGUF v3 header and tensor directory without mapping weight data. It checks metadata types, counts, alignment, duplicate keys/tensors, split numbering, and whether tensor start offsets fit the file. This is a structural check, not proof that all tensor bytes or quantization geometry are valid.
The public `leleka-tokenizer::read_gguf_tokenizer_metadata` API reads the
current Qwen35 GPT-2 BPE tokenizer fields directly from a GGUF v3 file. It
accepts a missing `tokenizer.ggml.pre` as `qwen35`, returns optional token
types and special-token IDs, and requires the vocabulary, merges, and chat
template. It bounds header reads to 1 GiB, individual strings to 1 MiB, and
tokenizer string arrays to 1,000,000 entries and 512 MiB of aggregate string
bytes. It reads no tensor payload; callers needing model structure or tensor
validation must separately use the GGUF inspector.
`model extract-tokenizer` validates the Qwen byte-level BPE metadata, then writes `tokenizer/` under the output directory through a staging directory. It requires a nonempty chat template and refuses to overwrite an existing tokenizer directory. The dense/expert pack is still pending.
The extracted directory is accepted by the native `model tokenize` and `model detokenize` commands. `model tokenize TOKENIZER_DIR --stdin --special` reads UTF-8 text from standard input and prints a JSON array of token IDs; `--special` enables control tokens such as `<|im_end|>`. User-defined tokens remain literal in both modes. `model detokenize TOKENIZER_DIR 1,2,3` prints a JSON string. The native BPE path matched the pinned upstream tokenizer on 20 cases from the real verified first shard. The dense/expert pack and model startup remain pending.
+88 -2
View File
@@ -5,7 +5,9 @@ No driver installation, model access, root privileges or inference. NVIDIA's
redistrib archives are assembly inputs, not a general-purpose CUDA installer.
"""
import argparse
import copy
import hashlib
import inspect
import json
import os
from pathlib import Path, PurePosixPath
@@ -53,22 +55,106 @@ def validate_lock(lock, manifest):
raise ValueError('component exceeds download budget')
def extract_members(source, destination, members, *, supports_filter=None):
"""Use tarfile's data policy on both new and older Python runtimes.
Python 3.11 runners may have neither ``extractall(filter=...)`` nor the
later ``tarfile.data_filter`` helper, so provide the same restricted data
policy locally. Never fall back to unfiltered extraction.
"""
if supports_filter is None:
supports_filter = 'filter' in inspect.signature(source.extractall).parameters
if supports_filter:
source.extractall(destination, members=members, filter='data')
return
safe_members = []
for member in members:
safe_member = safe_data_filter(member, destination)
if safe_member is not None:
safe_members.append(safe_member)
# tarfile 3.11's legacy chown path does not treat None ownership fields as
# "use current user". Pin filtered members to the extracting identity so
# archive ownership is ignored without relying on a Python 3.12 behavior.
for member in safe_members:
member.uid = os.geteuid()
member.gid = os.getegid()
member.uname = member.gname = ''
source.extractall(destination, members=safe_members, numeric_owner=True)
def safe_data_filter(member, destination):
"""Python 3.11-compatible equivalent of tarfile's restrictive data filter."""
name = member.name
if name.startswith('/') or os.path.isabs(name):
raise ValueError('absolute archive member path')
root = os.path.realpath(destination)
target = os.path.realpath(os.path.join(root, name))
if os.path.commonpath((target, root)) != root:
raise ValueError('archive member escapes extraction root')
filtered = copy.copy(member)
mode = member.mode
# Python 3.11's extractall() chmod path passes mode straight to os.chmod,
# so ``None`` (the data-filter convention for directories/symlinks) crashes.
# Give directories owner-only traversal/write permissions; this preserves
# the filter's security intent while remaining compatible with old tarfile.
if member.isdir():
mode = 0o700
elif member.isreg() or member.islnk():
mode = 0o600 if mode is None else mode & 0o755
if not mode & 0o100:
mode &= ~0o111
mode |= 0o600
elif member.issym():
mode = None
else:
raise ValueError('unsupported special archive member')
filtered.mode = mode
filtered.uid = filtered.gid = None
filtered.uname = filtered.gname = None
if member.issym() or member.islnk():
if os.path.isabs(member.linkname):
raise ValueError('absolute archive link target')
normalized = os.path.normpath(member.linkname)
filtered.linkname = normalized
if member.issym():
link_target = os.path.join(root, os.path.dirname(name), normalized)
else:
link_target = os.path.join(root, normalized)
resolved = os.path.realpath(link_target)
if os.path.commonpath((resolved, root)) != root:
raise ValueError('archive link escapes extraction root')
return filtered
def extract(archive, destination, root_name):
with tarfile.open(archive, 'r:xz') as source:
members=source.getmembers()
if len(members)>50000 or sum(x.size for x in members)>6*1024**3:
raise ValueError('archive expansion limit exceeded')
seen=set()
seen=set();links=set()
for item in members:
path=PurePosixPath(item.name)
if path.is_absolute() or '..' in path.parts or not path.parts or path.parts[0]!=root_name:
raise ValueError('archive path outside component root')
if item.name.rstrip('/') != str(path):
raise ValueError('non-canonical archive member path')
if item.name in seen:
raise ValueError('duplicate archive member')
seen.add(item.name)
if not (item.isdir() or item.isfile() or item.issym() or item.islnk()):
raise ValueError('unsupported archive member')
source.extractall(destination, members=members, filter='data')
if item.issym() or item.islnk():
links.add(str(path))
# Prevent a later member from traversing through an archive-created
# symlink/hardlink parent, even when each link target is individually
# confined to the destination.
for item in members:
path=PurePosixPath(item.name)
if any(str(parent) in links for parent in path.parents):
raise ValueError('archive member descends through a link')
extract_members(source, destination, members)
return destination/root_name
+310
View File
@@ -0,0 +1,310 @@
#!/usr/bin/env python3
"""Build and audit the CUDA engine in a pinned CPU-only Linux Docker container."""
import argparse
import hashlib
from io import BytesIO
import json
import os
from pathlib import Path
from pathlib import PurePosixPath
import re
import shutil
import ssl
import subprocess
import tarfile
import tempfile
import uuid
REPO = Path(__file__).resolve().parents[1].resolve()
DOCKERFILE = REPO / 'deploy/Dockerfile.cuda-builder'
BASE = 'ubuntu:24.04@sha256:f610ab94648195aa356059f5b41d6085c9d4d903c072430cdd1af7bdb646106b'
PLATFORM = 'linux/amd64'
CONTAINER_BUILD = r'''set -euo pipefail
test -x /opt/cuda/bin/nvcc
test -f /opt/cuda/lib/libcudart_static.a
shopt -s nullglob
devices=(/dev/nvidia*)
if (( ${#devices[@]} != 0 )); then
echo "CUDA builder unexpectedly sees NVIDIA device nodes: ${devices[*]}" >&2
exit 91
fi
test "${CUDA_VISIBLE_DEVICES+x}" = x && test -z "$CUDA_VISIBLE_DEVICES"
test "${NVIDIA_VISIBLE_DEVICES}" = void
mkdir -p /tmp/home /build/engine /build/output
python3 - <<'PY'
import json, os, subprocess
def capture(*args):
return subprocess.check_output(args, text=True, stderr=subprocess.STDOUT).strip()
data = {
'builder_base': os.environ['LELEKA_BUILDER_BASE'],
'builder_platform': 'linux/amd64',
'apt_snapshot': '20260917T000000Z',
'nvidia_device_nodes_visible': False,
'cuda_visible_devices': os.environ['CUDA_VISIBLE_DEVICES'],
'nvidia_visible_devices': os.environ['NVIDIA_VISIBLE_DEVICES'],
'nvcc': capture('/opt/cuda/bin/nvcc', '--version'),
'gcc': capture('gcc-13', '--version'),
'gxx': capture('g++-13', '--version'),
'cmake': capture('cmake', '--version'),
'ninja': capture('ninja', '--version'),
'make': capture('make', '--version'),
'packages': capture('dpkg-query', '-W', '-f=${Package}=${Version}\\n',
'ca-certificates', 'cmake', 'gcc-13', 'g++-13', 'git', 'make', 'ninja-build', 'python3', 'python3-numpy'),
}
with open(os.environ['LELEKA_TOOLCHAIN_METADATA'], 'w', encoding='utf-8') as stream:
json.dump(data, stream, indent=2)
stream.write(chr(10))
PY
scripts/build-static-cuda.sh
install -m 0755 /build/engine/strata "$LELEKA_ENGINE_OUTPUT"
'''
def digest(path):
h = hashlib.sha256()
with path.open('rb') as stream:
for block in iter(lambda: stream.read(1024 * 1024), b''):
h.update(block)
return h.hexdigest()
def extract_git_archive(archive, destination):
"""Extract only regular files/directories from git archive on old and new Python."""
root = destination.resolve()
with tarfile.open(fileobj=BytesIO(archive), mode='r:') as source:
members = source.getmembers()
seen = set()
checked = []
for member in members:
name = member.name
normalized_name = name.rstrip('/') if member.isdir() else name
path = PurePosixPath(normalized_name)
if (not normalized_name or path.is_absolute() or
any(part in ('', '.', '..') for part in normalized_name.split('/'))):
raise ValueError(f'unsafe path in committed source archive: {name!r}')
if not (member.isdir() or member.isfile()):
raise ValueError(f'unsupported entry in committed source archive: {name!r}')
target = root.joinpath(*path.parts)
if target == root or root not in target.parents:
raise ValueError(f'archive path escapes staging directory: {name!r}')
if path in seen:
raise ValueError(f'duplicate path in committed source archive: {name!r}')
seen.add(path)
checked.append((member, path, target))
directories = {root}
for member, path, target in checked:
if member.isdir():
directories.add(target)
continue
directories.update(parent for parent in target.parents if parent == root or root in parent.parents)
target.parent.mkdir(mode=0o755, parents=True, exist_ok=True)
payload = source.extractfile(member)
if payload is None:
raise ValueError(f'missing file payload in committed source archive: {member.name!r}')
flags = os.O_WRONLY | os.O_CREAT | os.O_EXCL | getattr(os, 'O_NOFOLLOW', 0)
fd = os.open(target, flags, member.mode & 0o777 & ~0o6000)
with os.fdopen(fd, 'wb') as output, payload:
shutil.copyfileobj(payload, output)
for directory in sorted(directories, key=lambda item: len(item.parts), reverse=True):
if directory.is_dir():
directory.chmod(0o755)
def stage_tracked_source(destination):
changed = subprocess.run(['git', '-C', str(REPO), 'diff', '--quiet', 'HEAD', '--'], check=False)
if changed.returncode == 1:
raise ValueError('refusing to build from a checkout with tracked changes; commit the source first')
if changed.returncode < 0:
raise ValueError('git diff was interrupted while checking the source checkout')
if changed.returncode != 0:
raise subprocess.CalledProcessError(changed.returncode, changed.args)
archive = subprocess.check_output(['git', '-C', str(REPO), 'archive', '--format=tar', 'HEAD'])
try:
extract_git_archive(archive, destination)
except (OSError, tarfile.TarError, ValueError) as error:
raise ValueError(f'could not safely stage the committed source tree: {error}') from error
return subprocess.check_output(['git', '-C', str(REPO), 'rev-parse', 'HEAD'], text=True).strip(), hashlib.sha256(archive).hexdigest()
def outside_repo(path, label):
resolved = path.resolve()
repo = REPO.resolve()
if resolved == repo or repo in resolved.parents:
raise ValueError(f'{label} must stay outside the source checkout')
if any(char in str(resolved) for char in ',:\n'):
raise ValueError(f'{label} contains a character unsupported in Docker mount paths')
return resolved
def run(command):
subprocess.run([str(arg) for arg in command], check=True)
def capture(command):
return subprocess.check_output([str(arg) for arg in command], text=True).strip()
def runner_ca_bundle():
"""Return the runner's CA bundle for bootstrapping HTTPS in the base image."""
cafile = ssl.get_default_verify_paths().cafile
if not cafile:
raise ValueError('Linux runner has no default CA bundle path')
try:
path = Path(cafile).resolve(strict=True)
except OSError as error:
raise ValueError('Linux runner CA bundle is missing or unreadable') from error
if not path.is_file():
raise ValueError('Linux runner CA bundle is not a regular file')
contents = path.read_bytes()
if not contents or b'-----BEGIN CERTIFICATE-----' not in contents:
raise ValueError('Linux runner CA bundle is empty or invalid')
return contents
def build(args):
docker = shutil.which(args.docker) if '/' not in args.docker else args.docker
if not docker:
raise ValueError('Docker CLI is not available')
toolkit = args.toolkit.resolve(strict=True)
if not (toolkit / 'bin/nvcc').is_file() or not (toolkit / 'lib/libcudart_static.a').is_file():
raise ValueError('toolkit is missing nvcc or static CUDA runtime')
build_dir = outside_repo(args.build_dir, 'build directory')
engine_output = outside_repo(args.output, 'engine output')
metadata_output = outside_repo(args.metadata, 'metadata output')
for path in (toolkit, build_dir, engine_output.parent, metadata_output.parent):
if any(char in str(path) for char in ',:\n'):
raise ValueError('a Docker mount path contains an unsupported character')
output_roots = (engine_output.parent, metadata_output.parent)
if any(build_dir == output or build_dir in output.parents or output in build_dir.parents
for output in output_roots):
raise ValueError('build and output directories must not overlap')
if engine_output.exists() or metadata_output.exists():
raise ValueError('refusing to overwrite an existing build output')
if build_dir.exists() and any(build_dir.iterdir()):
raise ValueError('build directory must be fresh and empty')
build_dir.mkdir(mode=0o700, parents=True, exist_ok=True)
engine_output.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
metadata_output.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
dockerfile = DOCKERFILE.read_text(encoding='utf-8')
match = re.search(r'^FROM --platform=linux/amd64 (\S+)$', dockerfile, re.M)
if not match or match.group(1) != BASE:
raise ValueError('CUDA builder Dockerfile must use the reviewed immutable amd64 base')
if not re.fullmatch(r'[A-Za-z0-9_.-]{1,46}', args.image_tag):
raise ValueError('invalid image tag')
nonce = uuid.uuid4().hex[:12]
tag = f'leleka-cuda-builder:{args.image_tag}-{nonce}'
image_built = False
container_id = None
staging_container_id = None
volume_names = {kind: f'leleka-cuda-{kind}-{args.image_tag}-{nonce}' for kind in ('source', 'toolkit', 'build')}
owned_volumes = []
source = build_dir / 'source'
try:
source.mkdir(mode=0o700)
source_commit, source_archive_sha256 = stage_tracked_source(source)
ca_bundle = runner_ca_bundle()
ca_bundle_sha256 = hashlib.sha256(ca_bundle).hexdigest()
with tempfile.TemporaryDirectory(prefix='leleka-cuda-docker-context-') as context_name:
context = Path(context_name)
image_context = context / 'image'
image_context.mkdir()
shutil.copyfile(DOCKERFILE, image_context / 'Dockerfile')
(image_context / 'runner-ca-certificates.crt').write_bytes(ca_bundle)
run([docker, 'build', '--platform', PLATFORM, '--pull', '--file', image_context / 'Dockerfile',
'--label', f'leleka.cuda-builder.run={args.image_tag}', '--tag', tag, image_context])
image_built = True
image_id = subprocess.check_output([docker, 'image', 'inspect', '--format', '{{.Id}}', tag], text=True).strip()
if not re.fullmatch(r'sha256:[0-9a-f]{64}', image_id):
raise ValueError('Docker returned an invalid builder image ID')
for kind, volume in volume_names.items():
created = capture([docker, 'volume', 'create', '--label', f'leleka.cuda-builder.run={args.image_tag}', volume])
if created != volume:
raise ValueError(f'Docker returned an unexpected {kind} volume name')
owned_volumes.append(volume)
staging_container_id = capture([
docker, 'create', '--platform', PLATFORM, '--network', 'none',
'--label', f'leleka.cuda-builder.run={args.image_tag}',
'--mount', f'type=volume,source={volume_names["source"]},target=/stage/source',
'--mount', f'type=volume,source={volume_names["toolkit"]},target=/stage/toolkit',
'--entrypoint', '/bin/true', tag
])
if not re.fullmatch(r'[A-Fa-f0-9]{12,64}', staging_container_id):
raise ValueError('Docker returned an invalid staging container ID')
run([docker, 'cp', f'{source}/.', f'{staging_container_id}:/stage/source'])
run([docker, 'cp', f'{toolkit}/.', f'{staging_container_id}:/stage/toolkit'])
run([docker, 'rm', staging_container_id])
staging_container_id = None
uid, gid = os.getuid(), os.getgid()
container_id = capture([docker, 'create', '--platform', PLATFORM, '--network', 'bridge', '--read-only',
'--label', f'leleka.cuda-builder.run={args.image_tag}',
'--cap-drop', 'ALL', '--security-opt', 'no-new-privileges', '--pids-limit', '512',
'--tmpfs', f'/tmp:rw,nosuid,nodev,size=1g,uid={uid},gid={gid}', '--user', f'{uid}:{gid}',
'--mount', f'type=volume,source={volume_names["source"]},target=/workspace,readonly',
'--mount', f'type=volume,source={volume_names["toolkit"]},target=/opt/cuda,readonly',
'--mount', f'type=volume,source={volume_names["build"]},target=/build',
'--workdir', '/workspace',
'--env', 'PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin',
'--env', 'HOME=/tmp/home', '--env', 'CUDA_VISIBLE_DEVICES=', '--env', 'NVIDIA_VISIBLE_DEVICES=void',
'--env', f'LELEKA_BUILDER_BASE={BASE}', '--env', 'LELEKA_ENGINE_OUTPUT=/build/output/strata',
'--env', 'LELEKA_TOOLCHAIN_METADATA=/build/output/CUDA-BUILDER.json',
'--env', 'CUDACXX=/opt/cuda/bin/nvcc', '--env', 'CUDAToolkit_ROOT=/opt/cuda',
'--env', 'CUDAHOSTCXX=/usr/bin/g++-13', '--env', 'CC=/usr/bin/gcc-13', '--env', 'CXX=/usr/bin/g++-13',
'--env', 'STRATA_BUILD_DIR=/build/engine', '--env', 'BUILD_JOBS=1', '--env', 'CUDA_ARCHITECTURES=120',
tag, '-lc', CONTAINER_BUILD])
if not re.fullmatch(r'[A-Fa-f0-9]{12,64}', container_id):
raise ValueError('Docker returned an invalid build container ID')
run([docker, 'start', '--attach', container_id])
run([docker, 'cp', f'{container_id}:/build/output/strata', engine_output])
run([docker, 'cp', f'{container_id}:/build/output/CUDA-BUILDER.json', metadata_output])
if not engine_output.is_file() or engine_output.is_symlink():
raise ValueError('Docker build did not produce a regular engine file')
engine_output.chmod(0o755)
container_metadata = json.loads(metadata_output.read_text(encoding='utf-8'))
expected = {'builder_base': BASE, 'builder_platform': PLATFORM,
'nvidia_device_nodes_visible': False, 'cuda_visible_devices': '', 'nvidia_visible_devices': 'void'}
if any(container_metadata.get(key) != value for key, value in expected.items()):
raise ValueError('container toolchain metadata violates CPU-only builder policy')
metadata = {'schema_version': 1, **container_metadata, 'source_commit': source_commit,
'source_archive_sha256': source_archive_sha256,
'runner_ca_bundle_sha256': ca_bundle_sha256, 'builder_image_id': image_id,
'engine_sha256': digest(engine_output), 'engine_bytes': engine_output.stat().st_size,
'gpu_tested': False, 'model_tested': False,
'qualification': 'CUDA compilation, ELF dependency audit and GPU-hidden --help only.'}
metadata_output.write_text(json.dumps(metadata, indent=2) + '\n', encoding='utf-8')
return metadata
finally:
if source.exists():
shutil.rmtree(source)
for owned_container in (container_id, staging_container_id):
if owned_container:
subprocess.run([docker, 'rm', '--force', owned_container], check=False,
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
for volume in owned_volumes:
subprocess.run([docker, 'volume', 'rm', '--force', volume], check=False,
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
if image_built:
subprocess.run([docker, 'image', 'rm', tag], check=False, stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL)
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--toolkit', type=Path, required=True, help='checksum-verified toolkit from bootstrap-cuda-toolkit.py')
parser.add_argument('--build-dir', type=Path, required=True, help='fresh private directory outside the checkout')
parser.add_argument('--output', type=Path, required=True, help='new engine file path outside the checkout')
parser.add_argument('--metadata', type=Path, required=True, help='new provenance JSON path outside the checkout')
parser.add_argument('--image-tag', required=True, help='unique CI run/attempt suffix for the temporary builder image')
parser.add_argument('--docker', default='docker', help='Docker CLI (used by tests)')
args = parser.parse_args()
try:
result = build(args)
print(json.dumps(result, sort_keys=True))
except (OSError, ValueError, subprocess.SubprocessError, json.JSONDecodeError) as error:
parser.exit(1, f'Docker CUDA build failed: {error}\n')
if __name__ == '__main__':
main()
+20 -4
View File
@@ -68,6 +68,15 @@ def static_outer(binary):
return {'program_headers': headers, 'dynamic_section': dynamic}
def probe_engine_help(binary, stage, env, *, defer_to_runtime_image):
if defer_to_runtime_image:
return 'deferred-to-runtime-image'
probe = stage / 'probe.json'
probe.write_text(json.dumps({'engine': {'executable': '@embedded'}, 'engine_probe': True}))
run([binary, 'provision', '--config', probe], env=env, timeout=30)
return 'passed-on-package-builder-host'
@contextlib.contextmanager
def lock(path):
# Caller-controlled build/output paths are private; keep the inode for reuse.
@@ -95,6 +104,9 @@ def publish(source, output):
def assemble(args):
if platform.system() != 'Linux' or platform.machine() != 'x86_64':
raise ValueError('package assembly requires Linux x86_64')
defer_help = getattr(args, 'defer_engine_help_probe_to_runtime_image', False)
if defer_help and args.cpu_fixture:
raise ValueError('only CUDA package builds may defer the loader probe to the runtime image')
source_check(REPO, args.revision)
output = args.output.absolute()
output.parent.mkdir(parents=True, exist_ok=True)
@@ -137,17 +149,19 @@ def assemble(args):
info['declared_source_revision'] == args.revision and info['bytes'] == size and
info['target_os'] == 'linux' and info['target_arch'] == 'x86_64'):
raise ValueError('combined engine identity does not match pinned input')
probe = stage / 'probe.json'
probe.write_text(json.dumps({'engine': {'executable': '@embedded'}, 'engine_probe': True}))
run([binary, 'provision', '--config', probe], env=probe_env, timeout=30)
help_probe = probe_engine_help(binary, stage, probe_env,
defer_to_runtime_image=defer_help)
source_check(REPO, args.revision)
provenance = {'schema_version': 1, 'kind': 'cpu-fixture' if args.cpu_fixture else 'static-cuda-preview',
'source_revision': args.revision, 'target': TARGET, 'engine': info,
'engine_help_probe': help_probe,
'engine_elf_audit': audit, 'outer_elf_audit': outer,
'cargo_lock_sha256': sha256(REPO / 'control-plane/Cargo.lock'),
'rustc': run(['rustc', '--version']), 'cargo': run(['cargo', '--version']),
'gpu_tested': False, 'model_tested': False, 'clean_node_tested': False,
'qualification': 'Exact payload identity, outer ELF and GPU-hidden loader help only; no inference.',
'qualification': ('Exact payload identity and outer ELF; loader help is verified in the compatible runtime image; no inference.'
if help_probe == 'deferred-to-runtime-image' else
'Exact payload identity, outer ELF and GPU-hidden loader help on package builder host; no inference.'),
'source_provenance': 'Operator/CI-declared engine revision, not binary-to-source attestation.'}
(published / 'PROVENANCE.json').write_text(json.dumps(provenance, indent=2) + '\n')
(published / 'SHA256SUMS').write_text(''.join(f'{sha256(p)} {p.name}\n' for p in [binary, published / 'PROVENANCE.json']))
@@ -165,6 +179,8 @@ def main():
parser.add_argument('--output', type=Path, required=True)
parser.add_argument('--cargo-target-dir', type=Path, required=True, help='dedicated build directory; do not run other Cargo commands here concurrently')
parser.add_argument('--cpu-fixture', action='store_true', help='explicit non-CUDA test artifact; never a GPU release')
parser.add_argument('--defer-engine-help-probe-to-runtime-image', action='store_true',
help='run the embedded engine loader probe only in the final runtime image, for CUDA engines with a newer glibc floor than the build host')
args = parser.parse_args()
try:
print(json.dumps(assemble(args)))
+4 -1
View File
@@ -70,6 +70,8 @@ def freeze(package, stage, receipt_sha, cpu_fixture):
not re.fullmatch(r'[0-9a-f]{64}', engine.get('sha256', ''))):
raise ValueError('invalid embedded engine identity')
if not cpu_fixture:
if p.get('engine_help_probe') != 'deferred-to-runtime-image':
raise ValueError('CUDA package must defer loader help until the compatible runtime image')
audit = p.get('engine_elf_audit', {})
if audit.get('toolkit_shared_libraries') is not False or audit.get('host_glibc_required') is not True:
raise ValueError('missing static CUDA ELF audit')
@@ -138,7 +140,8 @@ def assemble(args):
isolated_run(image, ['engine-help'])
result = {'schema_version': 1, 'image': image, 'base': args.base, 'base_glibc': glibc,
'package_receipt_sha256': args.receipt_sha256, 'source_revision': p['source_revision'],
'kind': p['kind'], 'gpu_tested': False, 'model_tested': False,
'kind': p['kind'], 'engine_help_probe': 'passed-in-runtime-image',
'gpu_tested': False, 'model_tested': False,
'qualification': 'Non-root GPU-hidden embedded identity and loader help only.'}
success = True
return result
+690
View File
@@ -0,0 +1,690 @@
#!/usr/bin/env python3
"""Run the pinned Linux unit suite and enforce changed-production Rust coverage."""
from __future__ import annotations
import argparse
import hashlib
import json
import os
import re
import subprocess
import sys
from pathlib import Path
BASELINE = "d3e63a7"
NIGHTLY = "nightly-2026-10-05"
RUSTC_VERSION = "rustc 1.101.0-nightly (282215592 2026-10-04)"
LLVM_VERSION = "LLVM version 23.1.3-rust-1.101.0-nightly"
RUST_FILES = (
"control-plane/src/kar_overlay.rs",
"control-plane/src/kar_stream_encode.rs",
"control-plane/src/kar_writer.rs",
"control-plane/src/model_pipeline.rs",
"control-plane/src/prepare_preview.rs",
"control-plane/src/stream_parts.rs",
)
DOCUMENT_FILES = ("docs/build-validation.md", "docs/compressed-runtime.md")
SCOPE_FILES = (*RUST_FILES, *DOCUMENT_FILES)
SCOPE_DEFINITION = (
"Full bodies of production functions with added lines or corresponding deleted baseline lines; "
"cfg(test) item/block lines are excluded; generated production closures remain included."
)
def _blank(chars: list[str], start: int, end: int) -> None:
for index in range(start, end):
if chars[index] != "\n":
chars[index] = " "
def _block_end(source: str, start: int) -> int:
depth, index = 1, start + 2
while index < len(source) and depth:
if source.startswith("/*", index):
depth, index = depth + 1, index + 2
elif source.startswith("*/", index):
depth, index = depth - 1, index + 2
else:
index += 1
if depth:
raise ValueError(f"unclosed Rust block comment at byte {start}")
return index
def _raw_string_end(source: str, start: int) -> int | None:
match = re.match(r"(?:br|r)(#{0,})\"", source[start:])
if not match:
return None
marker = '"' + match.group(1)
end = source.find(marker, start + match.end())
return len(source) if end < 0 else end + len(marker)
def _quoted_end(source: str, start: int) -> int:
index = start + 1
while index < len(source):
if source[index] == "\\":
index += 2
elif source[index] == '"':
return index + 1
else:
index += 1
raise ValueError(f"unclosed Rust string at byte {start}")
def _char_end(source: str, start: int) -> int | None:
if start + 2 >= len(source):
return None
index = start + 1
if source[index] == "\\":
index += 2
if source[start + 1 : start + 3] == "\\u":
close = source.find("}", start + 3)
if close < 0:
return None
index = close + 1
else:
index += 1
return index + 1 if index < len(source) and source[index] == "'" else None
def mask_rust(source: str) -> str:
chars, index = list(source), 0
while index < len(source):
raw_end = _raw_string_end(source, index)
if raw_end is not None:
_blank(chars, index, raw_end)
index = raw_end
elif source.startswith("//", index):
end = source.find("\n", index)
end = len(source) if end < 0 else end
_blank(chars, index, end)
index = end
elif source.startswith("/*", index):
end = _block_end(source, index)
_blank(chars, index, end)
index = end
elif source[index] == '"':
end = _quoted_end(source, index)
_blank(chars, index, end)
index = end
elif source[index] == "'" and (end := _char_end(source, index)):
_blank(chars, index, end)
index = end
else:
index += 1
return "".join(chars)
def matching(mask: str, start: int, left: str, right: str) -> int:
depth = 0
for index in range(start, len(mask)):
depth += mask[index] == left
depth -= mask[index] == right
if depth == 0:
return index
raise ValueError(f"unclosed Rust delimiter {left!r} at byte {start}")
def _body_depths(depths: list[int], char: str, previous: str) -> None:
if char == "(": depths[0] += 1
elif char == ")": depths[0] -= 1
elif char == "[": depths[1] += 1
elif char == "]": depths[1] -= 1
elif char == "<": depths[2] += 1
elif char == ">" and previous != "-" and depths[2]: depths[2] -= 1
def _body_open(mask: str, start: int) -> int:
depths = [0, 0, 0]
for index in range(start, len(mask)):
char = mask[index]
_body_depths(depths, char, mask[index - 1] if index else "")
if char in "{;" and not any(depths):
return index
return len(mask)
def _skip_space(mask: str, index: int) -> int:
while index < len(mask) and mask[index].isspace():
index += 1
return index
def _skip_attributes(mask: str, index: int) -> int:
while True:
index = _skip_space(mask, index)
if not mask.startswith("#[", index):
return index
index = matching(mask, index + 1, "[", "]") + 1
def _skip_visibility(mask: str, index: int) -> int:
if not re.match(r"pub\b", mask[index:]):
return index
index = _skip_space(mask, index + 3)
if index < len(mask) and mask[index] == "(":
index = matching(mask, index, "(", ")") + 1
return _skip_space(mask, index)
def _statement_depths(depths: list[int], char: str) -> bool:
if char == "(": depths[0] += 1
elif char == ")": depths[0] -= 1
elif char == "[": depths[1] += 1
elif char == "]": depths[1] -= 1
elif char == "{": depths[2] += 1
elif char == "}": depths[2] -= 1
return char == "}" and not any(depths)
def _statement_end(mask: str, start: int) -> int:
depths = [0, 0, 0]
for index, char in enumerate(mask[start:], start):
if _statement_depths(depths, char):
return index + 1
if char == ";" and not any(depths):
return index + 1
raise ValueError(f"cannot find end of Rust statement at byte {start}")
def _item_end(mask: str, start: int) -> int:
macro = re.match(r"(?:macro_rules!\s*[A-Za-z_][A-Za-z0-9_]*|[A-Za-z_:][A-Za-z0-9_:]*!)\s*", mask[start:])
if macro:
group = _skip_space(mask, start + macro.end())
if group >= len(mask) or mask[group] not in "{([":
raise ValueError(f"unsupported cfg(test) macro at byte {start}")
close = {"{": "}", "(": ")", "[": "]"}[mask[group]]
return matching(mask, group, mask[group], close) + 1
item = re.match(r"(fn|mod|impl|struct|enum|trait|use|const|static|type|extern)\b", mask[start:])
if not item:
return _statement_end(mask, start)
kind, cursor = item.group(1), start + item.end()
if kind == "fn":
paren = mask.find("(", cursor)
close = matching(mask, paren, "(", ")")
cursor = _body_open(mask, close + 1)
if kind in {"use", "const", "static", "type"}:
return _statement_end(mask, cursor)
opening = _body_open(mask, cursor)
if opening < len(mask) and mask[opening] == "{":
return matching(mask, opening, "{", "}") + 1
return _statement_end(mask, cursor)
def cfg_test_spans(source: str, mask: str) -> list[tuple[int, int]]:
spans = []
pattern = re.compile(r"#\s*\[\s*cfg\s*\(\s*test\s*\)\s*\]")
for attr in pattern.finditer(mask):
if attr.start() and mask[attr.start() - 1] == "!":
spans.append((0, len(source)))
continue
start = _skip_visibility(mask, _skip_attributes(mask, attr.end()))
end = _item_end(mask, start)
spans.append((attr.start(), end))
return _merge_spans(spans)
def _merge_spans(spans: list[tuple[int, int]]) -> list[tuple[int, int]]:
merged = []
for start, end in sorted(spans):
if merged and start <= merged[-1][1]:
merged[-1] = (merged[-1][0], max(merged[-1][1], end))
else:
merged.append((start, end))
return merged
def _span_lines(source: str, spans: list[tuple[int, int]]) -> set[int]:
lines = set()
for start, end in spans:
first = source.count("\n", 0, start) + 1
last = source.count("\n", 0, end) + 1
lines.update(range(first, last + 1))
return lines
def rust_functions(source: str) -> tuple[list[dict], set[int]]:
mask, found = mask_rust(source), []
test_spans = cfg_test_spans(source, mask)
test_lines = _span_lines(source, test_spans)
for match in re.finditer(r"\bfn\s+([A-Za-z_][A-Za-z0-9_]*)\b", mask):
if any(start <= match.start() < end for start, end in test_spans):
continue
paren = mask.find("(", match.end())
close = matching(mask, paren, "(", ")")
opening = _body_open(mask, close + 1)
if opening >= len(mask) or mask[opening] != "{":
continue
end = matching(mask, opening, "{", "}") + 1
found.append({"name": match.group(1), "start": source.count("\n", 0, match.start()) + 1,
"end": source.count("\n", 0, end) + 1})
return found, test_lines
def parse_diff_hunks(diff: str) -> tuple[set[int], set[int]]:
added, deleted, new_line, old_line = set(), set(), 0, 0
for line in diff.splitlines():
if line.startswith("@@"):
match = re.match(r"@@ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@", line)
if not match:
raise ValueError(f"invalid unified diff hunk: {line}")
old_line, new_line = int(match.group(1)), int(match.group(2))
elif line.startswith("+++") or line.startswith("---") or line.startswith("\\"):
continue
elif line.startswith("+"):
added.add(new_line)
new_line += 1
elif line.startswith("-"):
deleted.add(old_line)
old_line += 1
elif line.startswith(" "):
old_line += 1
new_line += 1
return added, deleted
def select_production_functions(source: str, baseline_source: str, diff: str) -> tuple[list[dict], set[int]]:
additions, deletions = parse_diff_hunks(diff)
current, test_lines = rust_functions(source)
old, old_test_lines = rust_functions(baseline_source)
additions.difference_update(test_lines)
deletions.difference_update(old_test_lines)
deleted_names = {item["name"] for item in old if any(item["start"] <= line <= item["end"] for line in deletions)}
selected = [item for item in current if item["name"] in deleted_names or
any(item["start"] <= line <= item["end"] for line in additions)]
if not selected:
raise ValueError("baseline diff selects no current production functions")
return selected, test_lines
def parse_lcov(text: str) -> list[dict]:
records, record = [], None
for line in text.splitlines():
if line.startswith("SF:"):
if record is not None:
raise ValueError("LCOV source record lacks end_of_record")
record = {"sf": line[3:], "da": [], "fn": [], "fnda": [], "brda": []}
elif line == "end_of_record":
if record is None:
raise ValueError("LCOV end_of_record without SF")
records.append(record)
record = None
elif record is not None:
_parse_lcov_row(record, line)
if record is not None:
raise ValueError("LCOV source record lacks end_of_record")
return records
def _parse_lcov_row(record: dict, line: str) -> None:
try:
if line.startswith("DA:"):
parts = line[3:].split(",")
record["da"].append((int(parts[0]), int(parts[1])))
elif line.startswith("FN:"):
number, name = line[3:].split(",", 1)
record["fn"].append((int(number), name))
elif line.startswith("FNDA:"):
count, name = line[5:].split(",", 1)
record["fnda"].append((int(count), name))
elif line.startswith("BRDA:"):
number, block, branch, taken = line[5:].split(",", 3)
record["brda"].append((int(number), block, branch, taken))
except (IndexError, ValueError) as error:
raise ValueError(f"invalid LCOV row: {line}") from error
def _record_path(record: dict) -> str:
path = record["sf"].replace("\\", "/")
return next((name for name in RUST_FILES if path == name or path.endswith("/" + name)), "")
def _inside(line: int, functions: list[dict], test_lines: set[int]) -> bool:
return line not in test_lines and any(item["start"] <= line <= item["end"] for item in functions)
def _merge_lcov(records: list[dict]) -> dict:
by_path = {}
for record in records:
path = _record_path(record)
if path:
by_path.setdefault(path, []).append(record)
return by_path
def _file_metrics(records: list[dict], functions: list[dict], test_lines: set[int]) -> dict:
da, fn, fnda, branch = _merge_record_metrics(records)
lines = {line: count for line, count in da.items() if _inside(line, functions, test_lines)}
funcs = {key: fnda.get(key[1], 0) for key in fn if _inside(key[0], functions, test_lines)}
branches = {key: value for key, value in branch.items() if _inside(key[0], functions, test_lines)}
return _metrics(lines, funcs, branches)
def _merge_record_metrics(records: list[dict]) -> tuple[dict, dict, dict, dict]:
da, fn, fnda, branch = {}, {}, {}, {}
for record in records:
_merge_record(record, da, fn, fnda, branch)
return da, fn, fnda, branch
def _merge_record(record: dict, da: dict, fn: dict, fnda: dict, branch: dict) -> None:
for line, count in record["da"]:
da[line] = da.get(line, 0) + count
for line, name in record["fn"]:
fn[(line, name)] = fn.get((line, name), 0)
for count, name in record["fnda"]:
fnda[name] = fnda.get(name, 0) + count
for line, block, number, taken in record["brda"]:
key = (line, block, number)
branch[key] = _branch_total(branch.get(key), taken)
def _branch_total(previous: str | None, taken: str) -> str:
if previous is None or taken == "-" or previous == "-":
return taken
return str(int(previous) + int(taken))
def _metrics(lines: dict, functions: dict, branches: dict) -> dict:
line_misses = sorted(line for line, hits in lines.items() if hits == 0)
fn_misses = [{"line": line, "name": name} for (line, name), hits in functions.items() if hits == 0]
branch_misses = [{"line": line, "block": block, "branch": branch, "taken": taken}
for (line, block, branch), taken in branches.items() if taken in {"0", "-"}]
return {"lines": _metric(len(lines) - len(line_misses), len(lines), line_misses),
"functions": _metric(len(functions) - len(fn_misses), len(functions), fn_misses),
"branches": _metric(len(branches) - len(branch_misses), len(branches), branch_misses)}
def _metric(hit: int, total: int, misses: list) -> dict:
return {"hit": hit, "total": total, "percent": (100.0 * hit / total) if total else 0.0,
"misses": misses}
def coverage_report(records: list[dict], scopes: dict[str, tuple[list[dict], set[int]]]) -> dict:
by_path, files = _merge_lcov(records), {}
totals = {kind: {"hit": 0, "total": 0, "misses": []} for kind in ("lines", "functions", "branches")}
for path in RUST_FILES:
if path not in by_path:
raise ValueError(f"LCOV is missing required Rust source record: {path}")
functions, test_lines = scopes[path]
metrics = _file_metrics(by_path[path], functions, test_lines)
files[path] = {"functions": functions, "metrics": metrics}
for kind, values in metrics.items():
totals[kind]["hit"] += values["hit"]
totals[kind]["total"] += values["total"]
totals[kind]["misses"].extend({**miss, "file": path} if isinstance(miss, dict)
else {"line": miss, "file": path} for miss in values["misses"])
for kind, values in totals.items():
values["percent"] = 100.0 * values["hit"] / values["total"] if values["total"] else 0.0
return {"baseline": BASELINE, "files": files, "totals": totals}
def raw_function_diagnostics(records: list[dict], scopes: dict[str, tuple[list[dict], set[int]]]) -> str:
"""Render raw LCOV function rows for selected zero-hit entries without changing metrics."""
by_path = _merge_lcov(records)
rows = ["Raw LCOV FN/FNDA diagnostics for selected zero-hit functions:"]
for path in RUST_FILES:
functions, test_lines = scopes[path]
source_records = by_path.get(path, [])
metrics = _file_metrics(source_records, functions, test_lines)
misses = {(item["line"], item["name"])
for item in metrics["functions"]["misses"]}
if not misses:
continue
raw_fn = sorted({(line, name) for record in source_records for line, name in record["fn"]
if _inside(line, functions, test_lines)})
raw_fnda = {}
for record in source_records:
for count, name in record["fnda"]:
raw_fnda.setdefault(name, []).append(count)
rows.append(f"{path}:")
for line, name in sorted(misses):
rows.append(f" zero-hit FN:{line},{name}")
enclosing = [item for item in functions if item["start"] <= line <= item["end"]]
related = [(fn_line, fn_name) for fn_line, fn_name in raw_fn
if any(item["start"] <= fn_line <= item["end"] for item in enclosing)]
for fn_line, fn_name in related:
counts = raw_fnda.get(fn_name, [])
raw_counts = ",".join(str(value) for value in counts) if counts else "<no exact FNDA>"
rows.append(f" raw FN:{fn_line},{fn_name}")
rows.append(f" exact raw FNDA:{raw_counts},{fn_name}")
if len(rows) == 1:
return ""
return "\n".join(rows) + "\n"
def _run(command: list[str], root: Path, env: dict | None = None) -> subprocess.CompletedProcess:
return subprocess.run(command, cwd=root, env=env, text=True, capture_output=True, check=False)
def _rust_tools(root: Path) -> tuple[Path, Path, dict]:
rustc = _run(["rustc", f"+{NIGHTLY}", "-vV"], root)
if rustc.returncode:
raise RuntimeError(f"pinned rustc is unavailable: {rustc.stderr.strip()}")
versions = rustc.stdout.strip()
if RUSTC_VERSION not in versions:
raise RuntimeError(f"unexpected pinned rustc version: {versions.splitlines()[0]}")
details = dict(line.split(": ", 1) for line in versions.splitlines() if ": " in line)
sysroot = _run(["rustc", f"+{NIGHTLY}", "--print", "sysroot"], root)
if sysroot.returncode or "host" not in details:
raise RuntimeError("cannot resolve pinned LLVM tool directory")
bindir = Path(sysroot.stdout.strip()) / "lib" / "rustlib" / details["host"] / "bin"
tools = (bindir / "llvm-cov", bindir / "llvm-profdata")
for tool in tools:
version = _run([str(tool), "--version"], root)
if version.returncode or LLVM_VERSION not in version.stdout:
raise RuntimeError(f"unexpected {tool.name} version: {version.stdout.strip()}")
return tools[0], tools[1], {"rustc": versions.splitlines()[0], "llvm": LLVM_VERSION, "host": details["host"]}
def _package_id(root: Path) -> str:
result = _run(["cargo", "metadata", "--manifest-path", "control-plane/Cargo.toml",
"--locked", "--format-version=1", "--no-deps"], root)
if result.returncode:
raise RuntimeError(f"cargo metadata failed: {result.stderr.strip()}")
packages = [item["id"] for item in json.loads(result.stdout)["packages"]
if item["name"] == "strata-control"]
if len(packages) != 1:
raise RuntimeError(f"expected one strata-control package, found {len(packages)}")
return packages[0]
def _cargo_harness(json_path: Path, package_id: str) -> Path:
found = []
for line in json_path.read_text().splitlines():
try: item = json.loads(line)
except json.JSONDecodeError: continue
if _is_test_lib_artifact(item, package_id):
found.append(Path(item["executable"]))
if len(found) != 1 or not found[0].is_file():
raise RuntimeError(f"expected one built strata-control lib test binary, found {len(found)}")
return found[0]
def _is_test_lib_artifact(item: dict, package_id: str) -> bool:
target = item.get("target", {})
return (item.get("reason") == "compiler-artifact" and item.get("package_id") == package_id
and target.get("name") == "strata_control" and target.get("kind") == ["lib"]
and target.get("test") and item.get("executable"))
def _changed_scopes(root: Path) -> tuple[dict, dict]:
if _run(["git", "cat-file", "-e", f"{BASELINE}^{{commit}}"], root).returncode:
raise RuntimeError(f"baseline commit {BASELINE} is unavailable")
if _run(["git", "merge-base", "--is-ancestor", BASELINE, "HEAD"], root).returncode:
raise RuntimeError(f"baseline {BASELINE} is not an ancestor of HEAD")
scopes, functions_by_file = {}, {}
for path in RUST_FILES:
source = (root / path).read_text()
old = _run(["git", "show", f"{BASELINE}:{path}"], root)
diff = _run(["git", "diff", "--no-ext-diff", "--unified=0", BASELINE, "--", path], root)
if old.returncode or diff.returncode:
raise RuntimeError(f"cannot read baseline/diff for {path}")
funcs, test_lines = select_production_functions(source, old.stdout, diff.stdout)
scopes[path] = (funcs, test_lines)
functions_by_file[path] = funcs
return scopes, functions_by_file
def _diff_hash(root: Path, paths: tuple[str, ...]) -> str:
result = _run(["git", "diff", "--binary", BASELINE, "--", *paths], root)
if result.returncode:
raise RuntimeError(f"cannot hash changed paths: {', '.join(paths)}")
return hashlib.sha256(result.stdout.encode()).hexdigest()
def _commit(root: Path, revision: str) -> str:
result = _run(["git", "rev-parse", revision], root)
if result.returncode:
raise RuntimeError(f"cannot resolve commit {revision}")
return result.stdout.strip()
def _coverage_env(out: Path) -> dict:
env = os.environ.copy()
flags = "-C instrument-coverage -Zcoverage-options=branch --cfg=coverage "
flags += "--cfg=coverage_nightly -C link-arg=-Wl,--no-keep-memory"
env.update({"RUSTFLAGS": flags,
"CARGO_BUILD_JOBS": "1", "CARGO_INCREMENTAL": "0", "RUST_TEST_THREADS": "1",
"CARGO_PROFILE_DEV_DEBUG": "0", "CARGO_PROFILE_TEST_DEBUG": "0",
"LLVM_PROFILE_FILE": str(out / "profraw" / "%m-%p.profraw")})
(out / "profraw").mkdir(parents=True, exist_ok=True)
return env
def _write_summary(out: Path, report: dict) -> None:
(out / "summary.json").write_text(json.dumps(report, indent=2, sort_keys=True) + "\n")
rows = summary_lines(report)
(out / "summary.txt").write_text("\n".join(rows) + "\n")
def summary_lines(report: dict) -> list[str]:
rows = [f"Changed-production coverage vs {report['baseline']}"]
totals = report.get("totals", {})
for kind in ("lines", "functions", "branches"):
value = totals.get(kind, {})
rows.append(f"{kind}: {value['hit']}/{value['total']} ({value.get('percent', 0.0):.2f}%)")
rows.append(f"Gate: {'PASS' if report.get('passed') else 'FAIL'}")
rows.append(f"Reason: {report.get('failure', 'all required gates passed')}")
if not report.get("passed"):
rows.extend(_miss_inventory(totals))
return rows
def _miss_inventory(totals: dict) -> list[str]:
rows = ["Miss inventory (file:line; deterministic order):"]
for kind in ("lines", "functions", "branches"):
misses = totals.get(kind, {}).get("misses", [])
rows.append(f"{kind} misses: {len(misses)}")
for miss in sorted(misses, key=_miss_sort_key):
rows.append(f" {_format_miss(kind, miss)}")
return rows
def _miss_sort_key(miss: dict) -> tuple:
return (miss.get("file", ""), miss.get("line", 0), miss.get("block", ""),
miss.get("branch", ""), miss.get("name", ""), miss.get("taken", ""))
def _format_miss(kind: str, miss: dict) -> str:
location = f"{miss.get('file', '<unknown>')}:{miss.get('line', 0)}"
if kind == "functions":
return f"{location} {miss.get('name', '<unknown>')}"
if kind == "branches":
return (f"{location} block={miss.get('block', '<unknown>')} "
f"branch={miss.get('branch', '<unknown>')} taken={miss.get('taken', '<unknown>')}")
return location
def _run_instrumented_tests(root: Path, out: Path, env: dict) -> tuple[int, Path, int]:
cargo_json, cargo_stderr = out / "cargo.jsonl", out / "cargo.stderr"
command = ["cargo", f"+{NIGHTLY}", "test", "--manifest-path", "control-plane/Cargo.toml",
"--locked", "-p", "strata-control", "--lib", "--message-format=json-render-diagnostics"]
with cargo_json.open("w") as stdout, cargo_stderr.open("w") as stderr:
test = subprocess.run(command, cwd=root, env=env, stdout=stdout, stderr=stderr, check=False)
binary = _cargo_harness(cargo_json, _package_id(root))
profiles = sorted((out / "profraw").glob("*.profraw"))
if not profiles:
raise RuntimeError("instrumented tests produced no profraw files")
return test.returncode, binary, len(profiles)
def _export_lcov(root: Path, out: Path, llvm_cov: Path, llvm_profdata: Path,
binary: Path) -> str:
profiles = sorted((out / "profraw").glob("*.profraw"))
profile = out / "merged.profdata"
merge = _run([str(llvm_profdata), "merge", "-sparse", "-o", str(profile), *map(str, profiles)], root)
if merge.returncode:
(out / "llvm-profdata.stderr").write_text(merge.stderr)
raise RuntimeError("llvm-profdata merge failed")
export = _run([str(llvm_cov), "export", "--format=lcov", f"--instr-profile={profile}", str(binary)], root)
(out / "llvm-cov.stderr").write_text(export.stderr)
if export.returncode:
raise RuntimeError("llvm-cov export failed")
(out / "coverage.raw.lcov").write_text(export.stdout)
return export.stdout
def _coverage_passed(state: dict, test_exit: int) -> bool:
exact = all(values["total"] > 0 and values["hit"] == values["total"]
for values in state["totals"].values())
return test_exit == 0 and exact
def _stable_diff(root: Path, state: dict) -> None:
if state["rust_six_path_diff_sha256"] != _diff_hash(root, RUST_FILES):
raise RuntimeError("Rust source diff changed during coverage collection")
if state["full_eight_path_diff_sha256"] != _diff_hash(root, SCOPE_FILES):
raise RuntimeError("eight-path source/docs diff changed during coverage collection")
def _attach_scope_result(state: dict, test_exit: int) -> None:
state["scope_files"] = list(RUST_FILES)
state["scope_definition"] = SCOPE_DEFINITION
state["measurement"] = "unit line/function/branch coverage; literal 100 percent required"
state["source_diff_sha256"] = state["rust_six_path_diff_sha256"]
state["passed"] = _coverage_passed(state, test_exit)
state["failure"] = "" if state["passed"] else "unit tests failed or changed-scope coverage was not exactly 100%"
def run_coverage(root: Path, out: Path) -> int:
out.mkdir(parents=True, exist_ok=True)
state = {"baseline": BASELINE, "head": "unknown", "passed": False, "failure": "not started"}
try:
state["head"] = _commit(root, "HEAD")
state["baseline_commit"] = _commit(root, BASELINE)
scopes, _ = _changed_scopes(root)
state["rust_six_path_diff_sha256"] = _diff_hash(root, RUST_FILES)
state["full_eight_path_diff_sha256"] = _diff_hash(root, SCOPE_FILES)
llvm_cov, llvm_profdata, versions = _rust_tools(root)
state["toolchain"] = versions
test_exit, binary, profile_count = _run_instrumented_tests(root, out, _coverage_env(out))
state.update(cargo_exit_code=test_exit, selected_test_binary=str(binary), profraw_files=profile_count)
raw = _export_lcov(root, out, llvm_cov, llvm_profdata, binary)
report = coverage_report(parse_lcov(raw), scopes)
state.update(report)
_stable_diff(root, state)
_attach_scope_result(state, test_exit)
except Exception as error:
state["failure"] = f"{type(error).__name__}: {error}"
_write_summary(out, state)
print((out / "summary.txt").read_text(), end="")
if "totals" in state:
diagnostics = raw_function_diagnostics(parse_lcov((out / "coverage.raw.lcov").read_text()), scopes)
if diagnostics:
(out / "function-diagnostics.txt").write_text(diagnostics)
print(diagnostics, end="")
return 0 if state["passed"] else 1
def main() -> int:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--root", type=Path, default=Path.cwd())
parser.add_argument("--output-dir", type=Path, required=True)
args = parser.parse_args()
return run_coverage(args.root.resolve(), args.output_dir.resolve())
if __name__ == "__main__":
raise SystemExit(main())
+2 -1
View File
@@ -3,13 +3,14 @@ set -euo pipefail
repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
python3 -m py_compile "${repo_root}/scripts/prepare-keyless-routing.py" "${repo_root}/scripts/calibrate-keyless-routing.py" "${repo_root}/scripts/test-keyless-routing.py" "${repo_root}/scripts/bench-chat-paired.py" "${repo_root}/scripts/compare-chat-reports.py" "${repo_root}/scripts/bench-chat-sequential-server.py" "${repo_root}/scripts/check-kar-cuda-records.py" "${repo_root}/scripts/strata-agent-profile.py" "${repo_root}/scripts/strata-dual-256-experiment.py" "${repo_root}/scripts/strata-dual-request-proxy.py" "${repo_root}/scripts/kv-keyless-feasibility.py" "${repo_root}/scripts/kv-keyless-attention.py" "${repo_root}/scripts/bench-expert-reserve.py" "${repo_root}/scripts/ple-cache-reuse.py" "${repo_root}/scripts/split-ple-row-trace.py" "${repo_root}/scripts/bench-kar-ple-device.py" "${repo_root}/scripts/bench-kar-ple-serve.py"
python3 -m py_compile "${repo_root}/scripts/prepare-keyless-routing.py" "${repo_root}/scripts/calibrate-keyless-routing.py" "${repo_root}/scripts/test-keyless-routing.py" "${repo_root}/scripts/bench-chat-paired.py" "${repo_root}/scripts/compare-chat-reports.py" "${repo_root}/scripts/bench-chat-sequential-server.py" "${repo_root}/scripts/check-kar-cuda-records.py" "${repo_root}/scripts/strata-agent-profile.py" "${repo_root}/scripts/strata-dual-256-experiment.py" "${repo_root}/scripts/strata-dual-request-proxy.py" "${repo_root}/scripts/kv-keyless-feasibility.py" "${repo_root}/scripts/kv-keyless-attention.py" "${repo_root}/scripts/bench-expert-reserve.py" "${repo_root}/scripts/ple-cache-reuse.py" "${repo_root}/scripts/split-ple-row-trace.py" "${repo_root}/scripts/bench-kar-ple-device.py" "${repo_root}/scripts/bench-kar-ple-serve.py" "${repo_root}/scripts/build-cuda-engine-in-docker.py"
python3 "${repo_root}/scripts/test-benchmark-harness.py"
python3 "${repo_root}/scripts/test-native-service.py"
python3 "${repo_root}/scripts/test-native-api.py"
python3 "${repo_root}/scripts/test-native-menu.py"
python3 "${repo_root}/scripts/test-model-switch.py"
python3 "${repo_root}/scripts/test-cuda-bootstrap.py"
python3 "${repo_root}/scripts/test-cuda-docker-builder.py"
python3 "${repo_root}/scripts/test-static-cuda-elf.py"
python3 "${repo_root}/scripts/test-linux-package.py"
python3 "${repo_root}/scripts/test-runtime-image.py"
+61
View File
@@ -0,0 +1,61 @@
#!/usr/bin/env bash
set -euo pipefail
# Pin the installer independently of rust-toolchain.toml, which pins rustc/cargo.
readonly RUSTUP_VERSION="1.29.0"
readonly RUSTUP_TARGET="x86_64-unknown-linux-gnu"
readonly RUSTUP_INIT_SHA256="4acc9acc76d5079515b46346a485974457b5a79893cfb01112423c89aeb5aa10"
readonly RUSTUP_INIT_URL="https://static.rust-lang.org/rustup/archive/${RUSTUP_VERSION}/${RUSTUP_TARGET}/rustup-init"
# Give each Actions job an isolated installation so a host's rustup cannot
# silently override the version pinned here.
if [[ -n "${RUNNER_TEMP:-}" && -n "${GITHUB_RUN_ID:-}" ]]; then
rustup_home="${RUNNER_TEMP}/strata-rustup-${GITHUB_RUN_ID}-${GITHUB_JOB:-job}"
export CARGO_HOME="${rustup_home}/cargo"
export RUSTUP_HOME="${rustup_home}/rustup"
mkdir -p "$CARGO_HOME"
if [[ -n "${GITHUB_ENV:-}" ]]; then
printf 'CARGO_HOME=%s\nRUSTUP_HOME=%s\n' "$CARGO_HOME" "$RUSTUP_HOME" >> "$GITHUB_ENV"
fi
fi
tmp_dir="$(mktemp -d)"
trap 'rm -rf -- "$tmp_dir"' EXIT
python3 - "$RUSTUP_INIT_URL" "$tmp_dir/rustup-init" <<'PY'
import shutil
import sys
import urllib.request
request = urllib.request.Request(
sys.argv[1], headers={"User-Agent": "strata-next-pinned-rustup-bootstrap/1"}
)
with urllib.request.urlopen(request, timeout=120) as response:
with open(sys.argv[2], "wb") as output:
shutil.copyfileobj(response, output)
PY
printf '%s %s\n' "$RUSTUP_INIT_SHA256" "$tmp_dir/rustup-init" | sha256sum --check --status || {
echo "rustup-init ${RUSTUP_VERSION} checksum mismatch" >&2
exit 1
}
chmod 0755 "$tmp_dir/rustup-init"
"$tmp_dir/rustup-init" -y --no-modify-path \
--default-host "$RUSTUP_TARGET" --default-toolchain none --profile minimal
export PATH="${CARGO_HOME:-$HOME/.cargo}/bin:$PATH"
if [[ -n "${GITHUB_PATH:-}" ]]; then
printf '%s\n' "${CARGO_HOME:-$HOME/.cargo}/bin" >> "$GITHUB_PATH"
fi
rustup set auto-self-update disable
actual_version="$(rustup --version | awk 'NR == 1 { print $2 }')"
if [[ "$actual_version" != "$RUSTUP_VERSION" ]]; then
echo "expected rustup ${RUSTUP_VERSION}, got ${actual_version:-unknown}" >&2
exit 1
fi
if (( $# > 0 )); then
"$@"
fi
+219
View File
@@ -0,0 +1,219 @@
#!/usr/bin/env python3
"""Publish the privately built CUDA preview through Gitea's API v1."""
import argparse
import hashlib
import http.client
import json
import os
from pathlib import Path
import re
import ssl
import stat
import sys
from urllib.parse import urlencode, urlsplit
PACKAGE_BINARY = 'strata-next-linux-x86_64-musl'
PACKAGE_ASSETS = {PACKAGE_BINARY, 'PROVENANCE.json'}
IMAGE_ASSETS = {'runtime-image.tar', 'IMAGE-PROVENANCE.json', 'CUDA-TOOLCHAIN.json', 'CUDA-LICENSES.tar'}
ASSETS = PACKAGE_ASSETS | IMAGE_ASSETS | {'SHA256SUMS', 'IMAGE-SHA256SUMS'}
CHUNK_SIZE = 1024 * 1024
def file_sha256(path):
fd = os.open(path, os.O_RDONLY | os.O_NOFOLLOW)
with os.fdopen(fd, 'rb') as source:
if not stat.S_ISREG(os.fstat(source.fileno()).st_mode):
raise ValueError(f'not a regular artifact file: {path.name}')
return hashlib.file_digest(source, 'sha256').hexdigest()
def verify_manifest(directory, manifest, expected):
path = directory / manifest
lines = path.read_text(encoding='ascii').splitlines()
entries = {}
for line in lines:
match = re.fullmatch(r'([0-9a-f]{64}) ([A-Za-z0-9_.-]+)', line)
if not match or match[2] in entries:
raise ValueError(f'invalid {manifest} entry')
entries[match[2]] = match[1]
if set(entries) != expected:
raise ValueError(f'{manifest} does not cover the required artifact set')
for name, expected_sha in entries.items():
if file_sha256(directory / name) != expected_sha:
raise ValueError(f'{manifest} checksum mismatch: {name}')
def read_json(path):
try:
value = json.loads(path.read_text(encoding='utf-8'))
except (OSError, json.JSONDecodeError) as error:
raise ValueError(f'invalid artifact JSON: {path.name}') from error
if not isinstance(value, dict):
raise ValueError(f'artifact JSON must be an object: {path.name}')
return value
def verify_artifacts(directory, target):
if not directory.is_dir():
raise ValueError('artifact directory does not exist')
paths = list(directory.iterdir())
if {path.name for path in paths} != ASSETS:
raise ValueError('artifact directory must contain exactly the CUDA preview files')
for path in paths:
file_sha256(path)
verify_manifest(directory, 'SHA256SUMS', PACKAGE_ASSETS)
verify_manifest(directory, 'IMAGE-SHA256SUMS', IMAGE_ASSETS)
package = read_json(directory / 'PROVENANCE.json')
if (package.get('kind') != 'static-cuda-preview' or package.get('source_revision') != target or
package.get('engine_help_probe') != 'deferred-to-runtime-image' or
package.get('gpu_tested') is not False or package.get('model_tested') is not False):
raise ValueError('combined package provenance is not a CUDA-only preview for this commit')
image = read_json(directory / 'IMAGE-PROVENANCE.json')
if (image.get('kind') != 'static-cuda-preview' or image.get('source_revision') != target or
image.get('engine_help_probe') != 'passed-in-runtime-image' or
image.get('gpu_tested') is not False or image.get('model_tested') is not False or
image.get('package_receipt_sha256') != file_sha256(directory / 'SHA256SUMS')):
raise ValueError('runtime image provenance is not qualified for this package and commit')
toolchain = read_json(directory / 'CUDA-TOOLCHAIN.json')
docker_builder = toolchain.get('docker_builder')
if (toolchain.get('source') != target or toolchain.get('driver_tested') is not False or
toolchain.get('model_tested') is not False or not isinstance(docker_builder, dict) or
docker_builder.get('source_commit') != target or
docker_builder.get('engine_sha256') != package.get('engine', {}).get('sha256')):
raise ValueError('CUDA toolchain provenance is not bound to this commit and engine')
return {path.name: {'size': path.stat().st_size, 'sha256': file_sha256(path)} for path in paths}
def parse_api_url(api_url):
parts = urlsplit(api_url)
if (parts.scheme not in {'http', 'https'} or not parts.hostname or parts.username or parts.password or
parts.query or parts.fragment or not parts.path.rstrip('/').endswith('/api/v1')):
raise ValueError('API URL must be a Gitea /api/v1 base URL')
prefix = parts.path.rstrip('/')
return parts, prefix
def connection(parts):
cls = http.client.HTTPSConnection if parts.scheme == 'https' else http.client.HTTPConnection
return cls(parts.hostname, parts.port, timeout=300, **({'context': ssl.create_default_context()} if parts.scheme == 'https' else {}))
def request_json(parts, prefix, path, token, payload, method='POST', expected_status=201):
body = json.dumps(payload, separators=(',', ':')).encode('utf-8')
conn = connection(parts)
try:
conn.request(method, prefix + path, body=body,
headers={'Authorization': f'token {token}', 'Content-Type': 'application/json',
'Accept': 'application/json'})
response = conn.getresponse()
data = response.read(1024 * 1024 + 1)
if response.status != expected_status:
detail = data[:1024].decode('utf-8', 'replace').replace(token, '[redacted]')
raise RuntimeError(f'Gitea API returned HTTP {response.status}: {detail}')
return json.loads(data)
finally:
conn.close()
def upload_asset(parts, prefix, path, token, asset, expected):
name = asset.name
route = prefix + path + '/assets?' + urlencode({'name': name})
fd = os.open(asset, os.O_RDONLY | os.O_NOFOLLOW)
conn = None
try:
source_stat = os.fstat(fd)
if not stat.S_ISREG(source_stat.st_mode):
raise ValueError(f'not a regular artifact file: {name}')
size = source_stat.st_size
if size != expected['size']:
raise ValueError(f'artifact size changed after verification: {name}')
conn = connection(parts)
conn.putrequest('POST', route)
conn.putheader('Authorization', f'token {token}')
conn.putheader('Content-Type', 'application/octet-stream')
conn.putheader('Content-Length', str(size))
conn.putheader('Accept', 'application/json')
conn.endheaders()
digest = hashlib.sha256()
sent = 0
with os.fdopen(fd, 'rb') as source:
fd = -1
while sent < size:
block = source.read(min(CHUNK_SIZE, size - sent))
if not block:
raise ValueError(f'artifact was truncated during upload: {name}')
sent += len(block)
digest.update(block)
conn.send(block)
if digest.hexdigest() != expected['sha256']:
raise ValueError(f'artifact content changed after verification: {name}')
response = conn.getresponse()
data = response.read(1024 * 1024 + 1)
if response.status != 201:
detail = data[:1024].decode('utf-8', 'replace').replace(token, '[redacted]')
raise RuntimeError(f'Gitea asset upload returned HTTP {response.status}: {detail}')
metadata = json.loads(data)
if metadata.get('name') != name or metadata.get('size') != size:
raise ValueError(f'Gitea returned mismatched asset metadata: {name}')
return {'name': name, 'size': size}
finally:
if fd >= 0:
os.close(fd)
if conn is not None:
conn.close()
def publish(api_url, repository, token, tag, target, title, notes, directory):
if not token:
raise ValueError('GITEA_TOKEN is required')
repo_parts = repository.split('/')
if len(repo_parts) != 2 or any(part in {'.', '..'} or not re.fullmatch(r'[A-Za-z0-9_.-]+', part)
for part in repo_parts):
raise ValueError('repository must be owner/name')
if not re.fullmatch(r'cuda-preview-[0-9]+-[0-9]+', tag):
raise ValueError('preview tag must be run-scoped cuda-preview-RUN-ATTEMPT')
if not re.fullmatch(r'[0-9a-f]{40}', target):
raise ValueError('target must be a full lowercase Git SHA')
parts, prefix = parse_api_url(api_url)
hashes = verify_artifacts(directory, target)
owner, repo = repo_parts
release = request_json(parts, prefix, f'/repos/{owner}/{repo}/releases', token,
{'tag_name': tag, 'target_commitish': target, 'name': title,
'body': notes, 'draft': True, 'prerelease': True})
release_id = release.get('id')
if type(release_id) is not int or release_id <= 0:
raise ValueError('Gitea did not return a valid release ID')
asset_route = f'/repos/{owner}/{repo}/releases/{release_id}'
uploaded = []
for name in sorted(ASSETS):
uploaded.append(upload_asset(parts, prefix, asset_route, token, directory / name, hashes[name]))
finalized = request_json(parts, prefix, asset_route, token, {'draft': False},
method='PATCH', expected_status=200)
if finalized.get('id') != release_id or finalized.get('draft') is not False:
raise ValueError('Gitea did not confirm publication of the complete preview release')
return {'release_id': release_id, 'release_url': release.get('html_url'),
'tag': tag, 'target': target, 'assets': [dict(uploaded_asset, sha256=hashes[uploaded_asset['name']]['sha256'])
for uploaded_asset in uploaded]}
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--api-url', default=os.environ.get('GITHUB_API_URL'), required=os.environ.get('GITHUB_API_URL') is None)
parser.add_argument('--repository', default=os.environ.get('GITHUB_REPOSITORY'), required=os.environ.get('GITHUB_REPOSITORY') is None)
parser.add_argument('--tag', required=True)
parser.add_argument('--target', required=True)
parser.add_argument('--title', required=True)
parser.add_argument('--notes', required=True)
parser.add_argument('--directory', type=Path, required=True)
args = parser.parse_args()
try:
result = publish(args.api_url, args.repository, os.environ.get('GITEA_TOKEN', ''),
args.tag, args.target, args.title, args.notes, args.directory)
print(json.dumps(result, sort_keys=True))
except (ValueError, OSError, RuntimeError, http.client.HTTPException, json.JSONDecodeError) as error:
print(f'Gitea release publication failed: {error}', file=sys.stderr)
raise SystemExit(1)
if __name__ == '__main__':
main()
+44 -11
View File
@@ -2,6 +2,7 @@
"""Exercise the actual CLI-only scratch image; never starts an inference worker."""
import json
from pathlib import Path
import socket
import subprocess
import sys
import time
@@ -17,18 +18,27 @@ def docker(*args, check=True):
def main(image):
name = 'strata-cli-smoke-' + uuid.uuid4().hex
network = 'strata-cli-smoke-' + uuid.uuid4().hex
job_container = socket.gethostname()
common = ['--name', name, '--read-only', '--user', '65532:65532',
'--cap-drop', 'ALL', '--security-opt', 'no-new-privileges']
root = Path(__file__).resolve().parents[1]
opener = urllib.request.build_opener(urllib.request.ProxyHandler({}))
def get(port, route):
def get(address, route):
try:
with opener.open(f'http://127.0.0.1:{port}{route}', timeout=2) as response:
with opener.open(f'{address}{route}', timeout=2) as response:
return response.status, json.load(response)
except urllib.error.HTTPError as error:
return error.code, json.load(error)
inspected_job = docker('inspect', '--format', '{{.Id}}', job_container, check=False)
attached_to_runner_container = inspected_job.returncode == 0 and bool(inspected_job.stdout.strip())
if attached_to_runner_container:
job_container = inspected_job.stdout.strip()
network_created = False
network_connected = False
try:
version = docker('run', '--rm', *common, '--network', 'none', image, '--version').stdout
assert version.startswith('strata-next '), version
@@ -38,21 +48,40 @@ def main(image):
info = json.loads(docker('run', '--rm', *common, '--network', 'none', image,
'engine-info').stdout)
assert info['embedded'] is False and info['model_bundled'] is False, info
docker('run', '-d', *common, '-p', '127.0.0.1::8081',
'-e', 'STRATA_BIND=0.0.0.0:8081', image, 'serve')
binding = docker('port', name, '8081/tcp').stdout.strip()
assert binding.startswith('127.0.0.1:'), binding
port = int(binding.rsplit(':', 1)[1])
if attached_to_runner_container:
# In Gitea, the Actions job itself is a sibling container on gitea-net;
# its 127.0.0.1 is not the Docker host where -p publishes ports. Use a
# private per-test network and join only this job plus the smoke image.
docker('network', 'create', '--internal', network)
network_created = True
docker('network', 'connect', network, job_container)
network_connected = True
docker('run', '-d', *common, '--network', network,
'--network-alias', name, '-e', 'STRATA_BIND=0.0.0.0:8081', image, 'serve')
address = f'http://{name}:8081'
else:
# Native VM runners can reach host-loopback port publication.
docker('run', '-d', *common, '-p', '127.0.0.1::8081',
'-e', 'STRATA_BIND=0.0.0.0:8081', image, 'serve')
binding = docker('port', name, '8081/tcp').stdout.strip()
assert binding.startswith('127.0.0.1:'), binding
address = f'http://{binding}'
deadline = time.monotonic() + 15
while True:
try:
assert get(port, '/health') == (200, {'status': 'ok'})
status, health = get(address, '/health')
assert status == 200 and health == {'status': 'ok'}, (status, health)
break
except (OSError, AssertionError):
except (OSError, urllib.error.URLError, AssertionError) as error:
if time.monotonic() >= deadline:
raise
state = docker('inspect', '--format', '{{json .State}}', name,
check=False).stdout
logs = docker('logs', name, check=False).stdout
raise AssertionError(
f'CLI service did not become healthy; state={state}; logs={logs}'
) from error
time.sleep(0.1)
status, ready = get(port, '/ready')
status, ready = get(address, '/ready')
assert status == 503 and ready['ready'] is False, (status, ready)
docker('stop', '--time', '10', name)
state = json.loads(docker('inspect', '--format', '{{json .State}}', name).stdout)
@@ -61,6 +90,10 @@ def main(image):
'non-root read-only health200/ready503, graceful stop. No GPU inference qualified.')
finally:
docker('rm', '-f', name, check=False)
if network_connected:
docker('network', 'disconnect', network, job_container, check=False)
if network_created:
docker('network', 'rm', network, check=False)
if __name__ == '__main__':
+75 -25
View File
@@ -7,12 +7,53 @@ import subprocess
import sys
import tempfile
import time
import urllib.request
import uuid
PROBE_SCRIPT = r'''#!/bin/bash
set -euo pipefail
request() {
local method="$1" path="$2" body="${3-}" request status line response
if ! { exec 3<>/dev/tcp/127.0.0.1/8081; } 2>/dev/null; then return 1; fi
if [[ -n "$body" ]]; then
printf -v request '%s %s HTTP/1.0\r\nHost: localhost\r\nContent-Type: application/json\r\nContent-Length: %s\r\n\r\n%s' \
"$method" "$path" "${#body}" "$body"
else
printf -v request '%s %s HTTP/1.0\r\nHost: localhost\r\nConnection: close\r\n\r\n' "$method" "$path"
fi
printf '%s' "$request" >&3
IFS= read -r status <&3 || { exec 3<&-; exec 3>&-; return 1; }
status="${status%$'\r'}"
while IFS= read -r line <&3; do
line="${line%$'\r'}"
[[ -n "$line" ]] || break
done
response="$(cat <&3)"
exec 3<&-
exec 3>&-
[[ "${status:9:3}" == 200 ]] || { echo "HTTP request failed: $status $response" >&2; return 1; }
printf '%s' "$response"
}
deadline=$((SECONDS + 15))
until status="$(request GET /status)"; do
if (( SECONDS >= deadline )); then echo 'worker did not become ready within 15s' >&2; exit 1; fi
sleep 0.1
done
[[ "$status" == *'"ready":true'* ]] || { echo "unexpected /status response: $status" >&2; exit 1; }
result="$(request POST /v1/responses '{"model":"embedded-fixture","input":"Reply A","max_output_tokens":1,"reasoning":{"effort":"none"}}')"
[[ "$result" == *'"status":"completed"'* && "$result" == *'"text":"A"'* ]] || {
echo "unexpected Responses result: $result" >&2
exit 1
}
'''
def docker(*args, check=True):
return subprocess.run(['docker', *map(str, args)], check=check, capture_output=True, text=True, timeout=30)
try:
return subprocess.run(['docker', *map(str, args)], check=check,
capture_output=True, text=True, timeout=30)
except subprocess.CalledProcessError as error:
detail = (error.stderr or '').strip()[-2048:]
raise RuntimeError(f'docker command failed ({error.returncode}): {detail}') from None
def main(receipt):
@@ -24,40 +65,47 @@ def main(receipt):
spec = importlib.util.spec_from_file_location('helper', Path(__file__).with_name('smoke-worker-cancel.py'))
helper = importlib.util.module_from_spec(spec); spec.loader.exec_module(helper)
name = 'strata-runtime-smoke-' + uuid.uuid4().hex
opener = urllib.request.build_opener(urllib.request.ProxyHandler({}))
fixture_container = 'strata-runtime-fixture-' + uuid.uuid4().hex
fixture_volume = 'strata-runtime-fixture-' + uuid.uuid4().hex
base = proof['base']
with tempfile.TemporaryDirectory(prefix='strata-container-fixture-') as tmp:
root = Path(tmp); root.chmod(0o755)
helper.tokenizer(root)
(root/'config.json').write_text(json.dumps({'bind': '0.0.0.0:8081', 'model': 'embedded-fixture',
'engine_probe': True, 'engine': {'executable': '@embedded', 'args': ['/tmp/worker.pid'],
'tokenizer_dir': '/fixture', 'startup_timeout_s': 5, 'max_restarts': 1}}))
(root/'probe.sh').write_text(PROBE_SCRIPT)
for path in root.iterdir(): path.chmod(0o644)
(root/'probe.sh').chmod(0o755)
try:
# The Docker daemon may be outside the job container. A job-local
# /tmp bind source is therefore not guaranteed to exist on it.
# `docker cp` streams this synthetic fixture through the CLI into
# a named volume; the tested image then mounts that volume read-only.
docker('volume', 'create', fixture_volume)
docker('create', '--name', fixture_container, '--platform', 'linux/amd64',
'--mount', f'type=volume,src={fixture_volume},dst=/fixture',
'--entrypoint', '/bin/sleep', base, '30')
docker('cp', f'{root}/.', f'{fixture_container}:/fixture/')
docker('rm', fixture_container)
docker('run', '-d', '--name', name, '--platform', 'linux/amd64', '--read-only',
'--cap-drop', 'ALL', '--security-opt', 'no-new-privileges', '--user', '65532:65532',
'--tmpfs', '/tmp:rw,nosuid,nodev,size=64m', '-e', 'CUDA_VISIBLE_DEVICES=',
'-e', 'NVIDIA_VISIBLE_DEVICES=void', '-p', '127.0.0.1::8081',
'--mount', f'type=bind,src={root},dst=/fixture,readonly', image,
'-e', 'NVIDIA_VISIBLE_DEVICES=void',
'--mount', f'type=volume,src={fixture_volume},dst=/fixture,readonly', image,
'serve', '--config', '/fixture/config.json')
port = int(docker('port', name, '8081/tcp').stdout.strip().rsplit(':', 1)[1])
def request(route, body=None):
req = urllib.request.Request(f'http://127.0.0.1:{port}{route}',
data=json.dumps(body).encode() if body else None, headers={'Content-Type': 'application/json'})
with opener.open(req, timeout=5) as response: return json.load(response)
def ready():
deadline = time.monotonic()+15
while time.monotonic()<deadline:
try:
if request('/status')['ready']: return
except OSError: pass
time.sleep(.1)
raise AssertionError('container worker did not become ready')
def generate():
result = request('/v1/responses', {'model':'embedded-fixture','input':'Reply A',
'max_output_tokens':1,'reasoning':{'effort':'none'}})
assert result['status']=='completed'
assert result['output'][0]['content'][0]['text']=='A'
ready(); generate()
def probe():
# The Gitea job container and Docker daemon do not share the
# daemon host's loopback. A short-lived client joins the
# server's network namespace, so probes remain loopback-only
# and don't publish a runtime port from the CI host.
docker('run', '--rm', '--platform', 'linux/amd64', '--network', f'container:{name}',
'--read-only', '--cap-drop', 'ALL', '--security-opt', 'no-new-privileges',
'--user', '65532:65532', '-e', 'CUDA_VISIBLE_DEVICES=',
'-e', 'NVIDIA_VISIBLE_DEVICES=void',
'--mount', f'type=volume,src={fixture_volume},dst=/fixture,readonly',
'--entrypoint', '/bin/bash', base, '/fixture/probe.sh')
probe()
before = docker('exec', name, 'cat', '/tmp/worker.pid').stdout.strip()
assert before.isascii() and before.isdigit()
docker('exec', name, '/bin/sh', '-c', 'kill -KILL "$1"', 'strata-smoke', before)
@@ -65,13 +113,15 @@ def main(receipt):
while docker('exec', name, 'cat', '/tmp/worker.pid').stdout.strip()==before:
assert time.monotonic()<deadline
time.sleep(.1)
ready(); generate()
probe()
docker('stop', '--time', '10', name)
state = json.loads(docker('inspect','--format','{{json .State}}',name).stdout)
assert state['ExitCode']==0 and not state['OOMKilled']
print('Combined CPU OCI: Responses A exact, worker crash/restart A exact, nonroot/read-only, graceful stop. No GPU/model qualification.')
finally:
docker('rm','-f',name,check=False)
docker('rm','-f',fixture_container,check=False)
docker('volume','rm',fixture_volume,check=False)
if __name__=='__main__': main(sys.argv[1])
+1 -1
View File
@@ -164,7 +164,7 @@ exit {42 if fail_action else 0}
'--ready-timeout-s', '2', env=fault_env, check=False)
assert bad.returncode != 0, bad.stdout
actions = [line.split('|')[2] for line in commands.read_text().splitlines()]
assert actions.count('start') == 1 and all(a in ('start','show') for a in actions), actions
assert actions.count('start') == 1 and all(a in ('start','show') for a in actions), (actions, bad.stderr, bad.stdout)
finally:
changed_http.shutdown(); changed_http.server_close(); changed_thread.join(timeout=5)
fault_unit.write_bytes(retained)
+245
View File
@@ -0,0 +1,245 @@
#!/usr/bin/env python3
"""Deterministic parser and workflow-contract tests for the manual coverage gate."""
from __future__ import annotations
import importlib.util
import json
import subprocess
import tempfile
import unittest
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
# Reviewed snapshots from frozen infrastructure commit ba60abfa659da4d418e20e1d5363e468845607e2.
EXISTING_JOBS_SHA256 = "c61b2c03df92cb4027e6d1f666b9ff6f370e9a783ae44662674864db006b7b7f"
COVERAGE_JOB_SHA256 = "22081e16838b5b3d403db38d22753792bcf4d507ae363f7ae9e2c2a0e14f03c5"
PUSH_PULL_SHA256 = "cefb2858cd9b21076e171fa764dbf2df1472b911cc0743caa6fac7d09a216c89"
SPEC = importlib.util.spec_from_file_location("changed_scope", ROOT / "scripts/check-changed-scope-coverage.py")
COVERAGE = importlib.util.module_from_spec(SPEC)
SPEC.loader.exec_module(COVERAGE)
def _job_block(text: str, name: str) -> str:
lines = text.splitlines(keepends=True)
start = next(index for index, line in enumerate(lines) if line == f" {name}:\n")
end = next((index for index in range(start + 1, len(lines))
if lines[index].startswith(" ") and not lines[index].startswith(" ")
and lines[index].strip().endswith(":")), len(lines))
return "".join(lines[start:end])
def _lcov(path: str, branch: str = "1") -> str:
return (f"SF:{path}\nFN:1,live\nFNDA:1,live\nDA:1,1\nDA:2,1\n"
f"BRDA:2,0,0,{branch}\nend_of_record\n")
class ChangedScopeCoverageTests(unittest.TestCase):
def test_rust_mask_and_cfg_test_exclusion(self) -> None:
source = '''
// fn comment() {}
const TEXT: &str = r###"fn raw_fake() {}"###;
pub fn live(value: u8) -> u8 { if value > 0 { value } else { 0 } }
#[cfg(test)]
mod tests { #[test] fn hidden() {} }
pub fn with_test_only_block() {
#[cfg(test)] if true { unreachable!(); }
}
'''
functions, test_lines = COVERAGE.rust_functions(source)
self.assertEqual([item["name"] for item in functions], ["live", "with_test_only_block"])
self.assertTrue(test_lines)
self.assertNotIn("fn raw_fake", COVERAGE.mask_rust(source))
def test_diff_hunks_select_only_added_and_deleted_new_lines(self) -> None:
diff = "--- a/x\n+++ b/x\n@@ -2,2 +2,2 @@\n old\n+added\n-gone\n"
self.assertEqual(COVERAGE.parse_diff_hunks(diff), ({3}, {3}))
def test_changed_scope_selects_body_but_excludes_test_additions(self) -> None:
old = "fn stable() { 1 }\nfn live() { 2 }\n#[cfg(test)]\nmod tests { fn sample() {} }\n"
new = "fn stable() { 1 }\nfn live() { 3 }\n#[cfg(test)]\nmod tests { fn sample() { 4 } }\n"
diff = ("@@ -2 +2 @@\n-fn live() { 2 }\n+fn live() { 3 }\n"
"@@ -4 +4 @@\n-mod tests { fn sample() {} }\n+mod tests { fn sample() { 4 } }\n")
selected, _ = COVERAGE.select_production_functions(new, old, diff)
self.assertEqual([item["name"] for item in selected], ["live"])
def test_lcov_zero_and_unknown_branches_fail_closed(self) -> None:
record = COVERAGE.parse_lcov(_lcov("control-plane/src/kar_writer.rs", "-"))[0]
metrics = COVERAGE._file_metrics([record], [{"name": "live", "start": 1, "end": 3}], set())
self.assertEqual(metrics["branches"]["hit"], 0)
self.assertEqual(metrics["branches"]["misses"][0]["taken"], "-")
record = COVERAGE.parse_lcov(_lcov("control-plane/src/kar_writer.rs", "0"))[0]
metrics = COVERAGE._file_metrics([record], [{"name": "live", "start": 1, "end": 3}], set())
self.assertEqual(metrics["branches"]["hit"], 0)
def test_coverage_requires_every_production_file_and_exact_hits(self) -> None:
scopes = {path: ([{"name": "live", "start": 1, "end": 3}], set())
for path in COVERAGE.RUST_FILES}
records = [COVERAGE.parse_lcov(_lcov(path))[0] for path in COVERAGE.RUST_FILES]
report = COVERAGE.coverage_report(records, scopes)
self.assertTrue(all(item["hit"] == item["total"] for item in report["totals"].values()))
with self.assertRaisesRegex(ValueError, "missing required Rust source"):
COVERAGE.coverage_report(records[:-1], scopes)
records[0]["brda"][0] = (2, "0", "0", "0")
report = COVERAGE.coverage_report(records, scopes)
self.assertNotEqual(report["totals"]["branches"]["hit"], report["totals"]["branches"]["total"])
def test_failure_summary_prints_deterministic_complete_miss_inventory(self) -> None:
report = {"baseline": "d3e63a7", "passed": False, "failure": "coverage below 100%",
"totals": {"lines": {"hit": 0, "total": 1,
"misses": [{"file": "b.rs", "line": 9},
{"file": "a.rs", "line": 4}]},
"functions": {"hit": 0, "total": 1,
"misses": [{"file": "a.rs", "line": 7, "name": "f"}]},
"branches": {"hit": 0, "total": 1,
"misses": [{"file": "b.rs", "line": 9, "block": "1",
"branch": "0", "taken": "-"}]}}}
lines = COVERAGE.summary_lines(report)
self.assertEqual(lines[6:9], ["Miss inventory (file:line; deterministic order):",
"lines misses: 2", " a.rs:4"])
self.assertIn(" a.rs:7 f", lines)
self.assertIn(" b.rs:9 block=1 branch=0 taken=-", lines)
self.assertEqual(lines, COVERAGE.summary_lines(report))
self.assertFalse(any("a.rs:4" in line for line in COVERAGE.summary_lines(
{**report, "passed": True})))
def test_raw_function_diagnostics_show_fn_and_exact_fnda_without_changing_metrics(self) -> None:
path = "control-plane/src/kar_writer.rs"
lcov = (f"SF:{path}\nFN:10,crate::write_section\nFNDA:1,crate::write_section\n"
"FN:12,crate::write_section::{closure#0}\n"
"FNDA:0,crate::write_section::{closure#0}\nDA:10,1\nDA:12,0\n"
"BRDA:12,0,0,0\nend_of_record\n")
records = [COVERAGE.parse_lcov(lcov)[0]]
records.extend(COVERAGE.parse_lcov(_lcov(other))[0]
for other in COVERAGE.RUST_FILES if other != path)
scopes = {name: ([], set()) for name in COVERAGE.RUST_FILES}
scopes[path] = ([{"name": "write_section", "start": 10, "end": 14}], set())
before = COVERAGE.coverage_report(records, scopes)
diagnostics = COVERAGE.raw_function_diagnostics(records, scopes)
after = COVERAGE.coverage_report(records, scopes)
self.assertEqual(before, after)
self.assertIn("zero-hit FN:12,crate::write_section::{closure#0}", diagnostics)
self.assertIn("raw FN:12,crate::write_section::{closure#0}", diagnostics)
self.assertIn("exact raw FNDA:0,crate::write_section::{closure#0}", diagnostics)
self.assertNotIn("zero-hit FN:10,crate::write_section", diagnostics)
def test_raw_function_diagnostics_are_empty_when_all_selected_functions_hit(self) -> None:
path = "control-plane/src/kar_writer.rs"
records = COVERAGE.parse_lcov(_lcov(path))[0:]
scopes = {name: ([], set()) for name in COVERAGE.RUST_FILES}
scopes[path] = ([{"name": "live", "start": 1, "end": 3}], set())
self.assertEqual(COVERAGE.raw_function_diagnostics(records, scopes), "")
def test_cargo_json_selects_only_the_package_lib_test_executable(self) -> None:
with tempfile.TemporaryDirectory() as directory:
binary = Path(directory) / "strata_control-test"
binary.touch()
rows = [{"reason": "compiler-artifact", "package_id": "other 1.0.0",
"target": {"name": "strata_control", "kind": ["lib"], "test": True},
"executable": str(binary)},
{"reason": "compiler-artifact", "package_id": "strata-control 1.0.0",
"target": {"name": "strata_control", "kind": ["lib"], "test": True},
"executable": str(binary)}]
log = Path(directory) / "cargo.jsonl"
log.write_text("\n".join(json.dumps(row) for row in rows))
self.assertEqual(COVERAGE._cargo_harness(log, "strata-control 1.0.0"), binary)
def test_workflow_adds_opt_in_cpu_job_without_changing_existing_jobs(self) -> None:
current = (ROOT / ".github/workflows/linux.yml").read_text()
original = subprocess.run(["git", "show", "HEAD:.github/workflows/linux.yml"],
cwd=ROOT, capture_output=True, text=True, check=True).stdout
self._assert_workflow_contract(current, original)
def _assert_workflow_contract(self, current: str, original: str) -> None:
self._assert_checkout_contract(current)
job_names = ("verify", "keyless-cuda", "hosted-cuda-package", "linux-static-cli",
"linux-cli-container", "release-cli")
self.assertEqual(_digest("".join(_job_block(current, name) for name in job_names)),
EXISTING_JOBS_SHA256)
self.assertEqual(_digest(_push_pull_block(current)), PUSH_PULL_SHA256)
for name in job_names:
self.assertEqual(_job_block(current, name), _job_block(original, name), name)
self.assertIn("pull_request:\n workflow_dispatch:", current)
self.assertIn("changed_scope_coverage:\n description:", current)
self.assertIn("type: boolean\n default: false", current)
job = _job_block(current, "changed-scope-coverage")
self.assertEqual(_digest(job), COVERAGE_JOB_SHA256)
self.assertIn("needs: verify", job)
self.assertIn("runs-on: ubuntu-latest", job)
self.assertNotIn("self-hosted", job)
self.assertNotIn("strata-gpu", job)
self.assertIn("inputs.changed_scope_coverage", job)
self.assertIn("nightly-2026-10-05", job)
self.assertIn("scripts/check-changed-scope-coverage.py", job)
self.assertNotIn("actions/upload-artifact", job)
self.assertNotIn("download-artifact", job)
def _assert_checkout_contract(self, current: str) -> None:
expected = " - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262\n"
names = ("verify", "changed-scope-coverage", "keyless-cuda", "hosted-cuda-package",
"linux-static-cli", "linux-cli-container", "release-cli")
# This explicit allowlist is independent of both the subject and snapshot hashes.
self.assertEqual(current.count("actions/checkout@"), len(names))
for name in names:
block = _job_block(current, name)
self.assertEqual(block.count("actions/checkout@"), 1, name)
self.assertEqual(block.count(expected), 1, name)
def test_workflow_requires_seven_immutable_checkout_references(self) -> None:
current = (ROOT / ".github/workflows/linux.yml").read_text()
self._assert_checkout_contract(current)
def test_workflow_rejects_mutable_checkout_references_in_every_job(self) -> None:
"""[SEC][UC-104-CI01] Refuse mutable checkout tags/branches independently of hashes."""
current = (ROOT / ".github/workflows/linux.yml").read_text()
self._assert_checkout_contract(current)
pinned = "actions/checkout@11d5960a326750d5838078e36cf38b85af677262"
for name in ("verify", "changed-scope-coverage", "keyless-cuda", "hosted-cuda-package",
"linux-static-cli", "linux-cli-container", "release-cli"):
for mutable in ("v4", "v4.2.2", "main"):
with self.subTest(job=name, ref=mutable):
block = _job_block(current, name)
self.assertEqual(block.count(pinned), 1)
mutated = current.replace(block, block.replace(pinned,
f"actions/checkout@{mutable}", 1), 1)
# Exercise the semantic judge directly: no digest or HEAD mismatch
# is needed to reject any of the seven restored mutable callers.
with self.assertRaises(AssertionError):
self._assert_checkout_contract(mutated)
def test_workflow_rejects_restored_unchecked_installer_in_every_bootstrap_job(self) -> None:
current = (ROOT / ".github/workflows/linux.yml").read_text()
self._assert_workflow_contract(current, current)
unchecked_bootstrap = (
" curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs "
"| sh -s -- -y --profile minimal --default-toolchain none\n"
' echo "$HOME/.cargo/bin" >> "$GITHUB_PATH"\n'
' export PATH="$HOME/.cargo/bin:$PATH"\n'
" "
)
for name in ("verify", "changed-scope-coverage", "hosted-cuda-package",
"linux-static-cli", "release-cli"):
with self.subTest(job=name):
block = _job_block(current, name)
self.assertEqual(block.count(" scripts/install-pinned-rustup.sh "), 1)
restored = block.replace(" scripts/install-pinned-rustup.sh ",
unchecked_bootstrap, 1)
mutated = current.replace(block, restored, 1)
# Matching HEAD cannot rescue a committed insecure bootstrap: the fixed
# reviewed snapshots must refuse it independently of that comparison.
with self.assertRaises(AssertionError):
self._assert_workflow_contract(mutated, mutated)
def _digest(value: str) -> str:
import hashlib
return hashlib.sha256(value.encode()).hexdigest()
def _push_pull_block(text: str) -> str:
start = text.index("on:\n") + len("on:\n")
end = text.index(" workflow_dispatch:", start)
return text[start:end]
if __name__ == "__main__":
unittest.main(verbosity=2)
+46
View File
@@ -20,6 +20,52 @@ class Tests(unittest.TestCase):
item=tarfile.TarInfo('component/lib/b');item.type=tarfile.SYMTYPE;item.linkname='a';t.addfile(item)
out=m.extract(archive,root/'out','component')
self.assertEqual((out/'lib/b').read_bytes(),b'a')
def test_python311_style_data_filter_fallback(self):
# Python 3.11 has data_filter but extractall(filter=...) is unavailable.
with tempfile.TemporaryDirectory() as tmp:
root=Path(tmp);archive=root/'test.tar.xz';dest=root/'out'
with tarfile.open(archive,'w:xz') as t:
item=tarfile.TarInfo('component/lib/a');item.size=1;t.addfile(item,io.BytesIO(b'a'))
item=tarfile.TarInfo('component/lib/b');item.type=tarfile.SYMTYPE;item.linkname='a';t.addfile(item)
with tarfile.open(archive,'r:xz') as source:
m.extract_members(source,dest,source.getmembers(),supports_filter=False)
self.assertEqual((dest/'component/lib/b').read_bytes(),b'a')
def test_python311_fallback_accepts_members_without_mode(self):
# NVIDIA component archives can contain directory/file entries without
# a mode. The legacy tarfile chmod path must never receive None.
with tempfile.TemporaryDirectory() as tmp:
root=Path(tmp);archive=root/'test.tar.xz';dest=root/'out'
with tarfile.open(archive,'w:xz') as t:
directory=tarfile.TarInfo('component/include');directory.type=tarfile.DIRTYPE;t.addfile(directory)
item=tarfile.TarInfo('component/include/header.h');item.size=1;t.addfile(item,io.BytesIO(b'h'))
with tarfile.open(archive,'r:xz') as source:
members=source.getmembers()
for member in members:member.mode=None
# Emulate old extractall()'s fully-trusted default after the
# caller's explicit data-policy validation has run.
with patch.object(source,'extraction_filter',lambda member,path: member,create=True):
m.extract_members(source,dest,members,supports_filter=False)
self.assertEqual((dest/'component/include/header.h').read_bytes(),b'h')
self.assertEqual((dest/'component/include').stat().st_mode & 0o777,0o700)
self.assertEqual((dest/'component/include/header.h').stat().st_mode & 0o777,0o600)
def test_python311_style_fallback_rejects_escaping_link(self):
with tempfile.TemporaryDirectory() as tmp:
root=Path(tmp);archive=root/'test.tar.xz';dest=root/'out'
with tarfile.open(archive,'w:xz') as t:
item=tarfile.TarInfo('component/b');item.type=tarfile.SYMTYPE;item.linkname='../../escape';t.addfile(item)
with tarfile.open(archive,'r:xz') as source:
with self.assertRaises(ValueError):
m.extract_members(source,dest,source.getmembers(),supports_filter=False)
self.assertFalse((root/'escape').exists())
def test_rejects_member_nested_under_archive_symlink(self):
with tempfile.TemporaryDirectory() as tmp:
root=Path(tmp);archive=root/'test.tar.xz'
with tarfile.open(archive,'w:xz') as t:
item=tarfile.TarInfo('component/a');item.type=tarfile.SYMTYPE;item.linkname='..';t.addfile(item)
# Lexically this link is still inside the root, but after the
# parent symlink is followed it would escape the extraction tree.
item=tarfile.TarInfo('component/a/x');item.type=tarfile.SYMTYPE;item.linkname='../..';t.addfile(item)
with self.assertRaises(ValueError):m.extract(archive,root/'out','component')
def test_bad_archive_paths_and_links(self):
for name,link in [('../escape',None),('/escape',None),('other/file',None),('component/b','../../escape')]:
with self.subTest(name=name),tempfile.TemporaryDirectory() as tmp:
+250
View File
@@ -0,0 +1,250 @@
#!/usr/bin/env python3
"""CPU-only contract tests for the Docker CUDA builder wrapper."""
import importlib.util
import hashlib
from io import BytesIO
import json
from pathlib import Path
import shutil
import subprocess
from types import SimpleNamespace
import tempfile
import tarfile
import unittest
from unittest.mock import patch
MODULE = Path(__file__).with_name('build-cuda-engine-in-docker.py')
spec = importlib.util.spec_from_file_location('cuda_docker_builder', MODULE)
builder = importlib.util.module_from_spec(spec)
spec.loader.exec_module(builder)
class Tests(unittest.TestCase):
def setUp(self):
self.temp = tempfile.TemporaryDirectory(prefix='cuda-docker-contract-')
self.root = Path(self.temp.name)
self.source_repo = self.root / 'repo'
(self.source_repo / 'deploy').mkdir(parents=True)
(self.source_repo / 'scripts').mkdir()
shutil.copyfile(builder.DOCKERFILE, self.source_repo / 'deploy/Dockerfile.cuda-builder')
(self.source_repo / 'scripts/build-static-cuda.sh').write_text('#!/bin/sh\nexit 0\n', encoding='utf-8')
(self.source_repo / 'scripts/check-static-cuda-elf.py').write_text('# fixture\n', encoding='utf-8')
subprocess.run(['git', '-C', str(self.source_repo), 'init', '-q'], check=True)
subprocess.run(['git', '-C', str(self.source_repo), 'config', 'user.email', 'cuda-test@example.invalid'], check=True)
subprocess.run(['git', '-C', str(self.source_repo), 'config', 'user.name', 'CUDA test'], check=True)
subprocess.run(['git', '-C', str(self.source_repo), 'add', '-f', 'deploy/Dockerfile.cuda-builder',
'scripts/build-static-cuda.sh', 'scripts/check-static-cuda-elf.py'], check=True)
subprocess.run(['git', '-C', str(self.source_repo), 'commit', '-qm', 'fixture'], check=True)
(self.source_repo / '.env').write_text('must not be staged', encoding='utf-8')
self.original_runner_ca_bundle = builder.runner_ca_bundle
self.original_repo = builder.REPO
self.original_dockerfile = builder.DOCKERFILE
self.ca_bundle = b'-----BEGIN CERTIFICATE-----\nfixture\n-----END CERTIFICATE-----\n'
self.ca_patch = patch.object(builder, 'runner_ca_bundle', return_value=self.ca_bundle)
self.ca_patch.start()
builder.REPO = self.source_repo.resolve()
builder.DOCKERFILE = self.source_repo / 'deploy/Dockerfile.cuda-builder'
self.toolkit = self.root / 'toolkit'
(self.toolkit / 'bin').mkdir(parents=True)
(self.toolkit / 'lib').mkdir()
(self.toolkit / 'bin/nvcc').write_text('fixture', encoding='utf-8')
(self.toolkit / 'lib/libcudart_static.a').write_bytes(b'fixture')
self.fake_docker = self.root / 'docker'
self.log = self.root / 'calls.jsonl'
fake = r'''#!/usr/bin/env python3
import json, pathlib, sys
args=sys.argv[1:]
with open(__LOG_PATH__, 'a') as f: f.write(json.dumps(args)+'\n')
if args[0] == 'build':
dockerfile=pathlib.Path(args[args.index('--file')+1]).read_text()
context=pathlib.Path(args[-1])
assert 'ubuntu:24.04@sha256:f610ab94648195aa356059f5b41d6085c9d4d903c072430cdd1af7bdb646106b' in dockerfile
assert (context/'runner-ca-certificates.crt').is_file()
assert 'COPY runner-ca-certificates.crt /etc/ssl/certs/ca-certificates.crt' in dockerfile
assert 'ca-certificates cmake gcc-13 g++-13 git make ninja-build' in dockerfile
elif args[:2] == ['image','inspect']:
print('sha256:' + 'a'*64)
elif args[:2] == ['volume','create']:
print(args[-1])
elif args[0] == 'create':
if '--entrypoint' not in args:
assert '--read-only' in args and '--gpus' not in args and '--device' not in args and '--runtime' not in args
mounts=[args[i+1] for i,x in enumerate(args[:-1]) if x=='--mount']
assert len(mounts)==3 and all(item.startswith('type=volume,') for item in mounts)
assert any('target=/workspace,readonly' in item for item in mounts)
assert any('target=/opt/cuda,readonly' in item for item in mounts)
assert any('target=/build' in item and 'readonly' not in item for item in mounts)
envs=[args[i+1] for i,x in enumerate(args[:-1]) if x=='--env']
assert 'CUDA_VISIBLE_DEVICES=' in envs and 'NVIDIA_VISIBLE_DEVICES=void' in envs
print(('a' if '--entrypoint' in args else 'b')*64)
elif args[0] == 'cp':
if args[2].endswith(':/stage/source'):
source=pathlib.Path(args[1][:-2])
assert (source/'scripts/build-static-cuda.sh').is_file()
assert not (source/'.env').exists()
elif args[2].endswith(':/stage/toolkit'):
source=pathlib.Path(args[1][:-2])
assert (source/'bin/nvcc').is_file()
elif args[1].endswith(':/build/output/strata'):
pathlib.Path(args[2]).write_bytes(b'fake compiled CUDA engine')
elif args[1].endswith(':/build/output/CUDA-BUILDER.json'):
pathlib.Path(args[2]).write_text(json.dumps({
'builder_base':'ubuntu:24.04@sha256:f610ab94648195aa356059f5b41d6085c9d4d903c072430cdd1af7bdb646106b',
'builder_platform':'linux/amd64','apt_snapshot':'20260917T000000Z',
'nvidia_device_nodes_visible':False,'cuda_visible_devices':'','nvidia_visible_devices':'void',
'nvcc':'fixture','gcc':'fixture','gxx':'fixture','cmake':'fixture','ninja':'fixture','packages':'fixture'}))
elif args[0] == 'start':
if pathlib.Path(__FAIL_RUN__).exists(): sys.exit(42)
elif args[0] == 'rm' or args[:2] == ['volume','rm'] or args[:2] == ['image','rm']:
pass
else:
raise AssertionError(args)
'''.replace('__LOG_PATH__', json.dumps(str(self.log)))
self.fake_docker.write_text(fake.replace('__FAIL_RUN__', json.dumps(str(self.root / 'fail-run'))), encoding='utf-8')
self.fake_docker.chmod(0o755)
def tearDown(self):
self.ca_patch.stop()
builder.REPO = self.original_repo
builder.DOCKERFILE = self.original_dockerfile
self.temp.cleanup()
def arguments(self, **overrides):
from argparse import Namespace
values = dict(toolkit=self.toolkit,
build_dir=self.root / 'build',
output=self.root / 'out' / 'strata',
metadata=self.root / 'out' / 'CUDA-BUILDER.json',
image_tag='test-1', docker=str(self.fake_docker))
values.update(overrides)
return Namespace(**values)
def docker_calls(self):
return [json.loads(line) for line in self.log.read_text().splitlines()]
def test_runner_ca_bundle_resolves_a_default_symlink(self):
pem = self.root / 'runner-ca.pem'
pem.write_bytes(self.ca_bundle)
link = self.root / 'runner-ca-link.pem'
link.symlink_to(pem)
with patch.object(builder.ssl, 'get_default_verify_paths',
return_value=SimpleNamespace(cafile=str(link))):
self.assertEqual(self.original_runner_ca_bundle(), self.ca_bundle)
def test_runner_ca_bundle_rejects_missing_path(self):
missing = self.root / 'missing-ca.pem'
with patch.object(builder.ssl, 'get_default_verify_paths',
return_value=SimpleNamespace(cafile=str(missing))):
with self.assertRaisesRegex(ValueError, 'missing or unreadable'):
self.original_runner_ca_bundle()
def test_container_build_has_pinned_cpu_only_invocation(self):
self.assertIn('stream.write(chr(10))', builder.CONTAINER_BUILD)
result = builder.build(self.arguments())
self.assertEqual(result['builder_base'], builder.BASE)
self.assertFalse(result['gpu_tested'])
self.assertEqual(result['source_commit'], subprocess.check_output(
['git', '-C', str(self.source_repo), 'rev-parse', 'HEAD'], text=True).strip())
self.assertEqual(result['engine_sha256'], builder.digest(self.root / 'out/strata'))
calls = self.docker_calls()
build = next(args for args in calls if args[0] == 'build')
container = next(args for args in calls if args[0] == 'create' and '--entrypoint' not in args)
self.assertEqual(build[build.index('--platform')+1], 'linux/amd64')
self.assertEqual(container[container.index('--platform')+1], 'linux/amd64')
self.assertNotIn('--gpus', container)
self.assertIn(['rm', '--force', 'b'*64], calls)
self.assertTrue(any(call[:2] == ['volume', 'rm'] for call in calls))
self.assertEqual(calls[-1][:2], ['image','rm'])
self.assertEqual(result['runner_ca_bundle_sha256'], hashlib.sha256(self.ca_bundle).hexdigest())
subprocess.run(['bash','-n','-c',builder.CONTAINER_BUILD], check=True)
def test_owned_docker_resources_are_removed_when_build_fails(self):
(self.root / 'fail-run').touch()
with self.assertRaises(subprocess.CalledProcessError):
builder.build(self.arguments())
calls = self.docker_calls()
self.assertIn(['rm', '--force', 'b'*64], calls)
self.assertEqual(calls[-1][:2], ['image', 'rm'])
def test_refuses_output_inside_source_checkout_before_docker(self):
with self.assertRaisesRegex(ValueError, 'outside the source checkout'):
builder.build(self.arguments(output=self.source_repo / 'artifacts/strata'))
self.assertFalse(self.log.exists(), self.log.read_text() if self.log.exists() else '')
def test_refuses_existing_output(self):
output = self.root / 'existing'
output.mkdir()
(output / 'strata').write_bytes(b'keep')
with self.assertRaisesRegex(ValueError, 'refusing to overwrite'):
builder.build(self.arguments(output=output / 'strata'))
self.assertEqual((output / 'strata').read_bytes(), b'keep')
self.assertFalse(self.log.exists())
def test_refuses_overlapping_build_and_output_directories(self):
with self.assertRaisesRegex(ValueError, 'must not overlap'):
builder.build(self.arguments(build_dir=self.root / 'out'))
self.assertFalse(self.log.exists())
def test_rejects_changed_builder_base_before_docker(self):
with tempfile.TemporaryDirectory() as d:
bad = Path(d) / 'Dockerfile'
bad.write_text('FROM ubuntu:latest\n', encoding='utf-8')
old = builder.DOCKERFILE
builder.DOCKERFILE = bad
try:
with self.assertRaisesRegex(ValueError, 'immutable amd64 base'):
builder.build(self.arguments())
finally:
builder.DOCKERFILE = old
self.assertFalse(self.log.exists())
def test_refuses_tracked_source_changes_before_docker(self):
(self.source_repo / 'scripts/build-static-cuda.sh').write_text('#!/bin/sh\necho modified\n', encoding='utf-8')
diff = subprocess.run(['git', '-C', str(self.source_repo), 'diff', '--quiet', 'HEAD', '--'], check=False)
self.assertEqual(diff.returncode, 1)
with self.assertRaisesRegex(ValueError, 'tracked changes'):
builder.build(self.arguments())
self.assertFalse(self.log.exists(), self.log.read_text() if self.log.exists() else '')
def test_archive_extraction_rejects_parent_paths_and_symlinks(self):
for name, kind in (('../escape', tarfile.REGTYPE), ('link', tarfile.SYMTYPE)):
with self.subTest(name=name):
archive = BytesIO()
with tarfile.open(fileobj=archive, mode='w:') as output:
entry = tarfile.TarInfo(name)
entry.type = kind
entry.linkname = '../outside'
if kind == tarfile.REGTYPE:
entry.size = 1
output.addfile(entry, BytesIO(b'x'))
else:
output.addfile(entry)
destination = self.root / f"safe-stage-{name.replace('/', '_')}"
destination.mkdir()
with self.assertRaisesRegex(ValueError, 'unsafe path|unsupported entry'):
builder.extract_git_archive(archive.getvalue(), destination)
self.assertEqual(list(destination.iterdir()), [])
self.assertFalse((self.root / 'escape').exists())
def test_manual_cuda_job_uses_generic_linux_and_no_artifact_action(self):
workflow = (self.original_repo / '.github/workflows/linux.yml').read_text(encoding='utf-8')
job = workflow.split(' hosted-cuda-package:', 1)[1].split('\n linux-static-cli:', 1)[0]
self.assertIn('runs-on: ubuntu-latest', job)
self.assertIn('scripts/build-cuda-engine-in-docker.py', job)
self.assertRegex(job, r'apt-get install -y .*\btime\b')
self.assertIn('/usr/bin/time -v python3 scripts/build-linux-package.py', job)
self.assertIn('--defer-engine-help-probe-to-runtime-image', job)
self.assertIn('scripts/build-runtime-image.py --package', job)
self.assertIn('contents: read', job)
self.assertIn('releases: write', job)
self.assertIn('secrets.GITEA_TOKEN', job)
self.assertIn('github.api_url', job)
self.assertIn('scripts/publish-gitea-release.py', job)
self.assertNotIn('gh release create', job)
self.assertNotIn('strata-gpu', job)
self.assertNotIn('actions/upload-artifact', job)
self.assertNotIn('static_cuda_package', workflow)
if __name__ == '__main__':
unittest.main()
+194
View File
@@ -0,0 +1,194 @@
#!/usr/bin/env python3
"""Contract tests for private CUDA preview release publishing."""
import hashlib
import importlib.util
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
import json
from pathlib import Path
import tempfile
import threading
from types import SimpleNamespace
from urllib.parse import parse_qs, urlsplit
import unittest
spec = importlib.util.spec_from_file_location('publisher', Path(__file__).with_name('publish-gitea-release.py'))
publisher = importlib.util.module_from_spec(spec)
spec.loader.exec_module(publisher)
TOKEN = 'fixture-action-token'
REVISION = 'a' * 40
class FakeGitea(BaseHTTPRequestHandler):
def log_message(self, *_args):
pass
def send_json(self, status, payload):
body = json.dumps(payload).encode()
self.send_response(status)
self.send_header('Content-Type', 'application/json')
self.send_header('Content-Length', str(len(body)))
self.end_headers()
self.wfile.write(body)
def do_POST(self):
if self.headers.get('Authorization') != f'token {TOKEN}':
self.send_json(401, {'message': 'bad token'})
return
if self.path == '/api/v1/repos/owner/repo/releases':
body = self.rfile.read(int(self.headers['Content-Length']))
self.server.release_payload = json.loads(body)
if self.server.fail_create:
return self.send_json(403, {'message': TOKEN})
return self.send_json(201, {'id': 73, 'html_url': 'http://gitea.invalid/owner/repo/releases/tag/x'})
parsed = urlsplit(self.path)
if parsed.path == '/api/v1/repos/owner/repo/releases/73/assets':
size = int(self.headers['Content-Length'])
digest = hashlib.sha256()
remaining = size
while remaining:
block = self.rfile.read(min(128 * 1024, remaining))
if not block:
raise AssertionError('truncated streamed request body')
digest.update(block)
remaining -= len(block)
name = parse_qs(parsed.query)['name'][0]
self.server.assets.append({'name': name, 'size': size, 'sha256': digest.hexdigest()})
if self.server.fail_asset:
return self.send_json(500, {'message': TOKEN})
return self.send_json(201, {'name': name, 'size': size})
self.send_json(404, {'message': 'unexpected route'})
def do_PATCH(self):
if self.headers.get('Authorization') != f'token {TOKEN}':
return self.send_json(401, {'message': 'bad token'})
if self.path != '/api/v1/repos/owner/repo/releases/73':
return self.send_json(404, {'message': 'unexpected route'})
self.server.finalize_payload = json.loads(self.rfile.read(int(self.headers['Content-Length'])))
self.send_json(200, {'id': 73, 'draft': self.server.finalize_payload['draft']})
class PublisherTests(unittest.TestCase):
def setUp(self):
self.tmp = tempfile.TemporaryDirectory()
self.addCleanup(self.tmp.cleanup)
self.directory = Path(self.tmp.name)
self.server = ThreadingHTTPServer(('127.0.0.1', 0), FakeGitea)
self.server.release_payload = None
self.server.finalize_payload = None
self.server.assets = []
self.server.fail_create = False
self.server.fail_asset = False
self.thread = threading.Thread(target=self.server.serve_forever, daemon=True)
self.thread.start()
self.addCleanup(self.server.server_close)
self.addCleanup(self.thread.join)
self.addCleanup(self.server.shutdown)
self.api_url = f'http://127.0.0.1:{self.server.server_port}/api/v1'
self.write_artifacts()
def write_artifacts(self):
directory = self.directory
(directory / publisher.PACKAGE_BINARY).write_bytes(b'embedded-engine-fixture')
engine_sha = hashlib.sha256(b'cuda-engine-fixture').hexdigest()
package_provenance = {
'kind': 'static-cuda-preview', 'source_revision': REVISION,
'engine_help_probe': 'deferred-to-runtime-image', 'gpu_tested': False, 'model_tested': False,
'engine': {'sha256': engine_sha},
}
(directory / 'PROVENANCE.json').write_text(json.dumps(package_provenance))
package_files = [publisher.PACKAGE_BINARY, 'PROVENANCE.json']
(directory / 'SHA256SUMS').write_text(''.join(
f'{publisher.file_sha256(directory / name)} {name}\n' for name in package_files))
receipt = publisher.file_sha256(directory / 'SHA256SUMS')
(directory / 'runtime-image.tar').write_bytes(b'runtime-image-' * 180000)
image_provenance = {
'kind': 'static-cuda-preview', 'source_revision': REVISION,
'engine_help_probe': 'passed-in-runtime-image', 'gpu_tested': False, 'model_tested': False,
'package_receipt_sha256': receipt,
}
(directory / 'IMAGE-PROVENANCE.json').write_text(json.dumps(image_provenance))
(directory / 'CUDA-TOOLCHAIN.json').write_text(json.dumps({
'source': REVISION, 'driver_tested': False, 'model_tested': False,
'docker_builder': {'source_commit': REVISION, 'engine_sha256': engine_sha},
}))
(directory / 'CUDA-LICENSES.tar').write_bytes(b'license archive')
image_files = ['runtime-image.tar', 'IMAGE-PROVENANCE.json', 'CUDA-TOOLCHAIN.json', 'CUDA-LICENSES.tar']
(directory / 'IMAGE-SHA256SUMS').write_text(''.join(
f'{publisher.file_sha256(directory / name)} {name}\n' for name in image_files))
def test_uploads_exact_hashed_assets_via_api_v1_and_streams_large_asset(self):
result = publisher.publish(self.api_url, 'owner/repo', TOKEN, 'cuda-preview-42-1', REVISION,
'CUDA preview 42.1', 'Build-only preview.', self.directory)
self.assertEqual(result['release_id'], 73)
self.assertEqual(result['target'], REVISION)
self.assertEqual(len(result['assets']), len(publisher.ASSETS))
self.assertEqual(self.server.release_payload, {
'tag_name': 'cuda-preview-42-1', 'target_commitish': REVISION, 'name': 'CUDA preview 42.1',
'body': 'Build-only preview.', 'draft': True, 'prerelease': True,
})
self.assertEqual(self.server.finalize_payload, {'draft': False})
uploaded = {asset['name']: asset for asset in self.server.assets}
self.assertEqual(set(uploaded), publisher.ASSETS)
self.assertGreater(uploaded['runtime-image.tar']['size'], publisher.CHUNK_SIZE)
for name in publisher.ASSETS:
self.assertEqual(uploaded[name]['sha256'], publisher.file_sha256(self.directory / name))
def test_checksum_failure_precedes_api_call(self):
(self.directory / publisher.PACKAGE_BINARY).write_bytes(b'tampered')
with self.assertRaisesRegex(ValueError, 'SHA256SUMS checksum mismatch'):
publisher.publish(self.api_url, 'owner/repo', TOKEN, 'cuda-preview-42-1', REVISION,
'title', 'notes', self.directory)
self.assertIsNone(self.server.release_payload)
def test_wrong_source_provenance_is_rejected(self):
path = self.directory / 'IMAGE-PROVENANCE.json'
image = json.loads(path.read_text())
image['source_revision'] = 'c' * 40
path.write_text(json.dumps(image))
files = ['runtime-image.tar', 'IMAGE-PROVENANCE.json', 'CUDA-TOOLCHAIN.json', 'CUDA-LICENSES.tar']
(self.directory / 'IMAGE-SHA256SUMS').write_text(''.join(
f'{publisher.file_sha256(self.directory / name)} {name}\n' for name in files))
with self.assertRaisesRegex(ValueError, 'runtime image provenance'):
publisher.publish(self.api_url, 'owner/repo', TOKEN, 'cuda-preview-42-1', REVISION,
'title', 'notes', self.directory)
self.assertIsNone(self.server.release_payload)
def test_api_failures_redact_token_and_do_not_finalize_incomplete_release(self):
self.server.fail_create = True
with self.assertRaisesRegex(RuntimeError, r'HTTP 403: \{"message": "\[redacted\]"\}') as failure:
publisher.publish(self.api_url, 'owner/repo', TOKEN, 'cuda-preview-42-1', REVISION,
'title', 'notes', self.directory)
self.assertNotIn(TOKEN, str(failure.exception))
self.assertIsNone(self.server.finalize_payload)
self.server.fail_create = False
self.server.fail_asset = True
with self.assertRaisesRegex(RuntimeError, r'HTTP 500: \{"message": "\[redacted\]"\}'):
publisher.publish(self.api_url, 'owner/repo', TOKEN, 'cuda-preview-42-1', REVISION,
'title', 'notes', self.directory)
self.assertIsNone(self.server.finalize_payload)
def test_unexpected_extra_file_and_invalid_route_are_rejected(self):
(self.directory / 'private-key').write_text('never upload')
with self.assertRaisesRegex(ValueError, 'exactly the CUDA preview files'):
publisher.publish(self.api_url, 'owner/repo', TOKEN, 'cuda-preview-42-1', REVISION,
'title', 'notes', self.directory)
(self.directory / 'private-key').unlink()
with self.assertRaisesRegex(ValueError, 'API URL'):
publisher.publish(self.api_url.replace('/api/v1', '/api/v3'), 'owner/repo', TOKEN,
'cuda-preview-42-1', REVISION, 'title', 'notes', self.directory)
self.assertIsNone(self.server.release_payload)
def test_invalid_scope_and_target_rejected(self):
with self.assertRaisesRegex(ValueError, 'owner/name'):
publisher.publish(self.api_url, '../repo', TOKEN, 'cuda-preview-42-1', REVISION,
'title', 'notes', self.directory)
with self.assertRaisesRegex(ValueError, 'full lowercase Git SHA'):
publisher.publish(self.api_url, 'owner/repo', TOKEN, 'cuda-preview-42-1', 'ABC',
'title', 'notes', self.directory)
self.assertIsNone(self.server.release_payload)
if __name__ == '__main__':
unittest.main()
+26
View File
@@ -76,6 +76,20 @@ class PackageTests(unittest.TestCase):
with pkg.lock(alias):
self.fail('symlink lock accepted')
def test_cuda_loader_probe_can_be_deferred_only_as_declared(self):
probe_binary = self.root / 'strata-next'
stage = self.root / 'stage'
stage.mkdir()
with patch.object(pkg, 'run') as run:
self.assertEqual(pkg.probe_engine_help(probe_binary, stage, {}, defer_to_runtime_image=True),
'deferred-to-runtime-image')
run.assert_not_called()
with patch.object(pkg, 'run') as run:
self.assertEqual(pkg.probe_engine_help(probe_binary, stage, {}, defer_to_runtime_image=False),
'passed-on-package-builder-host')
run.assert_called_once()
self.assertTrue((stage / 'probe.json').is_file())
@unittest.skipUnless(sys.platform == 'linux', 'Linux atomic publication')
def test_atomic_publication_never_replaces_existing_directory(self):
staged, output = self.root / 'stage', self.root / 'out'
@@ -117,6 +131,18 @@ class PackageTests(unittest.TestCase):
build.assert_not_called()
self.assertEqual((output / 'old').read_text(), 'keep')
def test_cpu_fixture_cannot_defer_loader_probe(self):
from types import SimpleNamespace
args = SimpleNamespace(engine=self.root/'engine', sha256='0'*64, revision='a'*40,
output=self.root/'out', cargo_target_dir=self.root/'target',
cpu_fixture=True, defer_engine_help_probe_to_runtime_image=True)
with patch.object(pkg.platform, 'system', return_value='Linux'), \
patch.object(pkg.platform, 'machine', return_value='x86_64'), \
patch.object(pkg.subprocess, 'run') as build:
with self.assertRaisesRegex(ValueError, 'only CUDA package builds'):
pkg.assemble(args)
build.assert_not_called()
if __name__ == '__main__':
unittest.main()
+38
View File
@@ -3,6 +3,7 @@
import importlib.util
import json
from pathlib import Path
import subprocess
import tempfile
import unittest
from types import SimpleNamespace
@@ -11,6 +12,9 @@ from unittest.mock import patch
spec = importlib.util.spec_from_file_location('builder', Path(__file__).with_name('build-runtime-image.py'))
b = importlib.util.module_from_spec(spec)
spec.loader.exec_module(b)
smoke_spec = importlib.util.spec_from_file_location('smoke', Path(__file__).with_name('smoke-runtime-image.py'))
smoke = importlib.util.module_from_spec(smoke_spec)
smoke_spec.loader.exec_module(smoke)
class PackageTests(unittest.TestCase):
@@ -24,6 +28,7 @@ class PackageTests(unittest.TestCase):
'source_revision': 'a'*40, 'target': 'x86_64-unknown-linux-musl',
'engine': {'embedded': True, 'target_os': 'linux', 'target_arch': 'x86_64',
'declared_source_revision': 'a'*40, 'bytes': 3, 'sha256': 'b'*64},
'engine_help_probe': 'deferred-to-runtime-image',
'engine_elf_audit': {'toolkit_shared_libraries': False,
'host_glibc_required': True, 'minimum_glibc': '2.43'}}
(self.pkg/b.NAME).write_bytes(b'not executable; validator does not execute input')
@@ -106,6 +111,39 @@ class PackageTests(unittest.TestCase):
with self.assertRaisesRegex(ValueError, 'size limit'):
b.frozen_file(self.pkg/b.NAME, Path(stage)/'out', 1)
def test_cuda_package_requires_runtime_image_loader_probe(self):
self.provenance.pop('engine_help_probe')
self.write()
with self.assertRaisesRegex(ValueError, 'defer loader help'):
self.freeze()
def test_successful_image_probes_embedded_help_after_identity(self):
args = SimpleNamespace(base=b.BASE, package=self.pkg, receipt_sha256=self.sha, cpu_fixture=False)
image = 'sha256:' + 'd'*64
isolated = []
def docker(*argv, **kwargs):
if argv[0] == 'build':
Path(argv[argv.index('--iidfile')+1]).write_text(image)
return SimpleNamespace(stdout='')
def probe(probe_image, arguments, *, entrypoint=None):
isolated.append((probe_image, arguments, entrypoint))
if entrypoint == 'getconf':
return 'glibc 2.43\n'
if arguments == ['engine-info']:
return json.dumps(self.provenance['engine'])
if arguments == ['engine-help']:
return ''
raise AssertionError((arguments, entrypoint))
with patch.object(b, 'docker', side_effect=docker), patch.object(b, 'isolated_run', side_effect=probe):
result = b.assemble(args)
self.assertEqual(result['engine_help_probe'], 'passed-in-runtime-image')
self.assertEqual([call[1] for call in isolated], [['GNU_LIBC_VERSION'], ['engine-info'], ['engine-help']])
self.assertEqual([call[2] for call in isolated], ['getconf', None, None])
def test_runtime_probe_script_has_valid_bash_syntax(self):
subprocess.run(['bash', '-n'], input=smoke.PROBE_SCRIPT, text=True,
capture_output=True, check=True)
if __name__ == '__main__':
unittest.main()