Compare commits
32
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d3e63a789e | ||
|
|
a8fa7e013a | ||
|
|
59b30049e3 | ||
|
|
7446c70dfa | ||
|
|
70f99ba63e | ||
|
|
4125a0305f | ||
|
|
00f04de5a7 | ||
|
|
f4dbcfd53e | ||
|
|
f7d273e560 | ||
|
|
be8f66f961 | ||
|
|
f245abc532 | ||
|
|
27b02c8b11 | ||
|
|
2833a86482 | ||
|
|
65589dff44 | ||
|
|
f4aa6b8af2 | ||
|
|
cb075ef762 | ||
|
|
096d21dcec | ||
|
|
c767751d96 | ||
|
|
f463149d02 | ||
|
|
878b4df303 | ||
|
|
982f4ce326 | ||
|
|
679572a13e | ||
|
|
ca8b1fee67 | ||
|
|
b7d8388806 | ||
|
|
cde6063c9c | ||
|
|
65a8dbd469 | ||
|
|
e5d934a850 | ||
|
|
39a0fe00da | ||
|
|
f0d4814649 | ||
|
|
d07df86a12 | ||
|
|
684f4cb191 | ||
|
|
276f662d56 |
+179
-137
@@ -15,28 +15,31 @@ 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)
|
||||
type: boolean
|
||||
default: false
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
verify:
|
||||
runs-on: ubuntu-24.04
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
# 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: |
|
||||
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y --profile minimal --default-toolchain none
|
||||
echo "$HOME/.cargo/bin" >> "$GITHUB_PATH"
|
||||
export PATH="$HOME/.cargo/bin:$PATH"
|
||||
rustup toolchain install 1.99.0 --profile minimal --component rustfmt --component clippy
|
||||
- name: Local checks
|
||||
run: scripts/check-local.sh
|
||||
|
||||
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
|
||||
@@ -45,66 +48,14 @@ jobs:
|
||||
- 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'
|
||||
@@ -112,18 +63,16 @@ jobs:
|
||||
CUDA_ARCHITECTURES: '120'
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- name: Install compatible host tools (no drivers)
|
||||
- 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,19 +80,22 @@ 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: |
|
||||
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y --profile minimal --default-toolchain none
|
||||
echo "$HOME/.cargo/bin" >> "$GITHUB_PATH"
|
||||
export PATH="$HOME/.cargo/bin:$PATH"
|
||||
rustup toolchain install 1.99.0 --profile minimal
|
||||
rustup target add --toolchain 1.99.0 x86_64-unknown-linux-musl
|
||||
- name: Assemble actual combined executable and runtime image
|
||||
@@ -161,23 +113,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 +150,35 @@ 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
|
||||
- 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: |
|
||||
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y --profile minimal --default-toolchain none
|
||||
echo "$HOME/.cargo/bin" >> "$GITHUB_PATH"
|
||||
export PATH="$HOME/.cargo/bin:$PATH"
|
||||
rustup toolchain install 1.99.0 --profile minimal
|
||||
rustup target add --toolchain 1.99.0 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 +206,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 +328,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
|
||||
- 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 +346,55 @@ 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@v4
|
||||
- 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: |
|
||||
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y --profile minimal --default-toolchain none
|
||||
echo "$HOME/.cargo/bin" >> "$GITHUB_PATH"
|
||||
export PATH="$HOME/.cargo/bin:$PATH"
|
||||
rustup toolchain install 1.99.0 --profile minimal
|
||||
rustup target add --toolchain 1.99.0 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
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -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
@@ -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()?)),
|
||||
|
||||
+659
-2
@@ -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,391 @@ 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)?;
|
||||
if cursor.take(4)? != b"GGUF" {
|
||||
return Err(gguf_error("not a GGUF file"));
|
||||
}
|
||||
if cursor.u32()? != 3 {
|
||||
return Err(gguf_error("only GGUF v3 is supported"));
|
||||
}
|
||||
cursor.skip(8)?; // tensor count; tensor inspection belongs to the model loader.
|
||||
let count = cursor.u64()?;
|
||||
if count > MAX_GGUF_METADATA_ENTRIES {
|
||||
return Err(gguf_error("unreasonable GGUF metadata entry count"));
|
||||
}
|
||||
let minimum_bytes = count
|
||||
.checked_mul(13)
|
||||
.ok_or_else(|| gguf_error("GGUF metadata entry count overflow"))?;
|
||||
if minimum_bytes > cursor.remaining()? {
|
||||
return Err(gguf_error("GGUF metadata count exceeds bounded header"));
|
||||
}
|
||||
|
||||
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;
|
||||
let mut seen_fields = HashSet::new();
|
||||
for _ in 0..count {
|
||||
let key = cursor.string()?;
|
||||
let kind = cursor.u32()?;
|
||||
let relevant = matches!(
|
||||
key.as_str(),
|
||||
"tokenizer.ggml.model"
|
||||
| "tokenizer.ggml.pre"
|
||||
| "tokenizer.ggml.tokens"
|
||||
| "tokenizer.ggml.merges"
|
||||
| "tokenizer.ggml.token_type"
|
||||
| "tokenizer.chat_template"
|
||||
) || (key.starts_with("tokenizer.ggml.") && key.ends_with("_token_id"));
|
||||
if relevant {
|
||||
if seen_fields.len() >= MAX_RELEVANT_TOKENIZER_FIELDS {
|
||||
return Err(gguf_error("too many tokenizer metadata fields"));
|
||||
}
|
||||
if !seen_fields.insert(key.clone()) {
|
||||
return Err(gguf_error("duplicate tokenizer metadata field"));
|
||||
}
|
||||
}
|
||||
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_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"))?;
|
||||
if model != "gpt2" || pre.as_deref().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
|
||||
.as_ref()
|
||||
.is_some_and(|types| types.len() != tokens.len())
|
||||
{
|
||||
return Err(gguf_error(
|
||||
"token_type length differs from vocabulary length",
|
||||
));
|
||||
}
|
||||
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",
|
||||
));
|
||||
}
|
||||
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 left.is_empty()
|
||||
|| right.is_empty()
|
||||
|| right.contains(' ')
|
||||
|| !vocab.contains(left)
|
||||
|| !vocab.contains(right)
|
||||
|| !seen_merges.insert(merge)
|
||||
{
|
||||
return Err(gguf_error("GGUF BPE merge is invalid or duplicated"));
|
||||
}
|
||||
}
|
||||
for &id in special_ids.values() {
|
||||
if id as usize >= tokens.len() {
|
||||
return Err(gguf_error("special token ID exceeds vocabulary"));
|
||||
}
|
||||
}
|
||||
Ok(GgufTokenizerMetadata {
|
||||
model,
|
||||
pre: pre.unwrap_or_else(|| "qwen35".to_owned()),
|
||||
tokens,
|
||||
merges,
|
||||
token_types,
|
||||
special_ids,
|
||||
chat_template,
|
||||
})
|
||||
}
|
||||
|
||||
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 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 => {
|
||||
let element = self.u32()?;
|
||||
let count = self.u64()?;
|
||||
match element {
|
||||
8 => {
|
||||
if count > MAX_GGUF_METADATA_ENTRIES {
|
||||
return Err(gguf_error("unreasonable GGUF string array count"));
|
||||
}
|
||||
let minimum_bytes = count
|
||||
.checked_mul(8)
|
||||
.ok_or_else(|| gguf_error("GGUF string array size overflow"))?;
|
||||
if minimum_bytes > self.remaining()? {
|
||||
return Err(gguf_error("GGUF string array exceeds remaining header"));
|
||||
}
|
||||
for _ in 0..count {
|
||||
let size = self.u64()?;
|
||||
if size > MAX_GGUF_HEADER_BYTES {
|
||||
return Err(gguf_error("GGUF string array element is too large"));
|
||||
}
|
||||
self.skip(size)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
9 => Err(gguf_error("nested GGUF arrays are unsupported")),
|
||||
_ => {
|
||||
let width = value_width(element)?;
|
||||
let bytes = count
|
||||
.checked_mul(width)
|
||||
.ok_or_else(|| gguf_error("GGUF array size overflow"))?;
|
||||
self.skip(bytes)
|
||||
}
|
||||
}
|
||||
}
|
||||
10..=12 => self.skip(8),
|
||||
_ => Err(gguf_error(format!("unknown GGUF metadata type {kind}"))),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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 +880,274 @@ 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()); // no tensors: metadata reader only.
|
||||
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();
|
||||
}
|
||||
|
||||
#[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_version_truncation_and_excessive_metadata_count() {
|
||||
let mut bytes = base();
|
||||
bytes[0] = b'X';
|
||||
with_bytes(&bytes, |path| {
|
||||
assert!(
|
||||
read_gguf_tokenizer_metadata(path)
|
||||
.unwrap_err()
|
||||
.to_string()
|
||||
.contains("GGUF")
|
||||
);
|
||||
});
|
||||
|
||||
let mut bytes = base();
|
||||
bytes[4..8].copy_from_slice(&2u32.to_le_bytes());
|
||||
with_bytes(&bytes, |path| {
|
||||
assert!(
|
||||
read_gguf_tokenizer_metadata(path)
|
||||
.unwrap_err()
|
||||
.to_string()
|
||||
.contains("v3")
|
||||
);
|
||||
});
|
||||
|
||||
let bytes = base();
|
||||
with_bytes(&bytes[..bytes.len() - 2], |path| {
|
||||
assert!(read_gguf_tokenizer_metadata(path).is_err());
|
||||
});
|
||||
|
||||
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());
|
||||
with_bytes(&bytes, |path| {
|
||||
assert!(
|
||||
read_gguf_tokenizer_metadata(path)
|
||||
.unwrap_err()
|
||||
.to_string()
|
||||
.contains("entry count")
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_oversized_string_and_truncated_or_excessive_arrays_before_allocation() {
|
||||
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]); // Keep the minimum metadata entry envelope intact.
|
||||
with_bytes(&bytes, |path| {
|
||||
assert!(
|
||||
read_gguf_tokenizer_metadata(path)
|
||||
.unwrap_err()
|
||||
.to_string()
|
||||
.contains("too large")
|
||||
);
|
||||
});
|
||||
|
||||
let mut bytes = base();
|
||||
bytes.extend_from_slice(&[0; 0]);
|
||||
// Replace the token array's count with a value above the explicit cap.
|
||||
let marker = b"tokenizer.ggml.tokens";
|
||||
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(&(MAX_TOKENIZER_ARRAY_ITEMS + 1).to_le_bytes());
|
||||
with_bytes(&bytes, |path| {
|
||||
assert!(read_gguf_tokenizer_metadata(path).is_err());
|
||||
});
|
||||
|
||||
let mut bytes = base();
|
||||
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(&u64::MAX.to_le_bytes());
|
||||
with_bytes(&bytes, |path| {
|
||||
assert!(read_gguf_tokenizer_metadata(path).is_err());
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_duplicate_tokenizer_metadata_and_duplicate_vocabulary_tokens() {
|
||||
let mut bytes = base();
|
||||
string_field(&mut bytes, "tokenizer.ggml.model", "gpt2");
|
||||
bytes[16..24].copy_from_slice(&8u64.to_le_bytes());
|
||||
with_bytes(&bytes, |path| {
|
||||
assert!(
|
||||
read_gguf_tokenizer_metadata(path)
|
||||
.unwrap_err()
|
||||
.to_string()
|
||||
.contains("duplicate tokenizer metadata")
|
||||
);
|
||||
});
|
||||
|
||||
let mut bytes = base();
|
||||
// Rewrite the third token "ab" to "a", preserving all offsets.
|
||||
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_invalid_tokenizer_types_ids_merges_and_unknown_metadata_types() {
|
||||
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());
|
||||
with_bytes(&bytes, |path| {
|
||||
assert!(read_gguf_tokenizer_metadata(path).is_err())
|
||||
});
|
||||
|
||||
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");
|
||||
with_bytes(&bytes, |path| {
|
||||
assert!(read_gguf_tokenizer_metadata(path).is_err())
|
||||
});
|
||||
|
||||
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);
|
||||
with_bytes(&bytes, |path| {
|
||||
assert!(read_gguf_tokenizer_metadata(path).is_err())
|
||||
});
|
||||
|
||||
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());
|
||||
with_bytes(&bytes, |path| {
|
||||
assert!(read_gguf_tokenizer_metadata(path).is_err())
|
||||
});
|
||||
}
|
||||
|
||||
#[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");
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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"]
|
||||
@@ -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"]
|
||||
|
||||
@@ -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
@@ -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,
|
||||
|
||||
@@ -796,8 +796,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 +808,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 +830,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.
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
|
||||
@@ -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()
|
||||
@@ -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)))
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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"
|
||||
|
||||
@@ -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()
|
||||
@@ -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__':
|
||||
|
||||
@@ -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])
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -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()
|
||||
@@ -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()
|
||||
@@ -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()
|
||||
|
||||
@@ -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()
|
||||
|
||||
Reference in New Issue
Block a user