Author SHA1 Message Date
Pavlo Ratushnyi b848e433a3 STRA-13: align desktop CI Rust helper target
Linux / keyless-cuda-gate (pull_request) Skipped
Desktop foundation / core (ubuntu-latest) (pull_request) Successful in 2m54s
Linux / keyless-cuda (pull_request) Skipped
Linux / static-cuda-package (pull_request) Skipped
Linux / verify (pull_request) Successful in 7m2s
Linux / hosted-cuda-package (pull_request) Skipped
Linux / linux-cli-container (pull_request) Successful in 29s
Linux / linux-static-cli (pull_request) Successful in 5m16s
Linux / release-cli (pull_request) Skipped
Set the desktop job target directory to desktop-core/target so workspace Rust builds produce the helper at the existing .NET and Python consumer paths. Preserve all workflow checks and event routing.
2026-10-08 00:25:07 +02:00
Pavlo Ratushnyi 3aea854d41 fix(ci): route desktop gates to Linux with pinned Rust bootstrap
Linux / keyless-cuda-gate (pull_request) Skipped
Desktop foundation / core (ubuntu-latest) (pull_request) Failing after 2m57s
Linux / verify (pull_request) Successful in 7m4s
Linux / keyless-cuda (pull_request) Skipped
Linux / static-cuda-package (pull_request) Skipped
Linux / hosted-cuda-package (pull_request) Skipped
Linux / linux-cli-container (pull_request) Successful in 4m6s
Linux / linux-static-cli (pull_request) Successful in 8m27s
Linux / release-cli (pull_request) Skipped
2026-10-08 00:00:59 +02:00
Pavlo Ratushnyi 3a478b603c feat(cuda): add fixed typed vector launch and isolated PTX gate
Linux / verify (pull_request) Successful in 6m15s
Linux / keyless-cuda-gate (pull_request) Skipped
Linux / keyless-cuda (pull_request) Skipped
Linux / static-cuda-package (pull_request) Skipped
Linux / hosted-cuda-package (pull_request) Skipped
Linux / linux-cli-container (pull_request) Failing after 4m2s
Linux / linux-static-cli (pull_request) Successful in 9m31s
Linux / release-cli (pull_request) Skipped
Desktop foundation / core (ubuntu-latest) (push) Failing after 13s
Desktop foundation / core (windows-latest) (push) Canceled after 0s
Desktop foundation / core (macos-latest) (push) Canceled after 0s
2026-10-07 23:43:54 +02:00
Pavlo Ratushnyi 0383253c60 STRA-102 install Docker for isolated driver mock CI gate
Linux / release-cli (pull_request) Skipped
Linux / linux-cli-container (pull_request) Successful in 2m27s
Linux / linux-static-cli (pull_request) Successful in 5m47s
Linux / verify (pull_request) Successful in 4m14s
Linux / keyless-cuda-gate (pull_request) Skipped
Linux / keyless-cuda (pull_request) Skipped
Linux / static-cuda-package (pull_request) Skipped
Linux / hosted-cuda-package (pull_request) Skipped
Desktop foundation / core (ubuntu-latest) (push) Failing after 4s
Desktop foundation / core (macos-latest) (push) Canceled after 0s
Desktop foundation / core (windows-latest) (push) Canceled after 0s
2026-10-07 23:13:13 +02:00
Pavlo Ratushnyi 7e61ab8007 STRA-102 implement independent CUDA Driver context and buffers
Linux / keyless-cuda-gate (pull_request) Skipped
Linux / verify (pull_request) Failing after 42s
Linux / keyless-cuda (pull_request) Skipped
Linux / static-cuda-package (pull_request) Skipped
Linux / hosted-cuda-package (pull_request) Skipped
Linux / linux-static-cli (pull_request) Skipped
Linux / linux-cli-container (pull_request) Skipped
Linux / release-cli (pull_request) Skipped
2026-10-07 23:09:48 +02:00
Pavlo Ratushnyi baf11daf8c STRA-102 port IQ2_S and IQ3_XXS preparation to Rust
Linux / keyless-cuda-gate (pull_request) Skipped
Linux / verify (pull_request) Successful in 4m50s
Linux / keyless-cuda (pull_request) Skipped
Linux / static-cuda-package (pull_request) Skipped
Linux / hosted-cuda-package (pull_request) Skipped
Linux / linux-cli-container (pull_request) Successful in 4m10s
Linux / linux-static-cli (pull_request) Successful in 8m9s
Linux / release-cli (pull_request) Skipped
Desktop foundation / core (ubuntu-latest) (push) Failing after 8s
Desktop foundation / core (macos-latest) (push) Canceled after 0s
Desktop foundation / core (windows-latest) (push) Canceled after 0s
2026-10-07 22:35:42 +02:00
Pavlo Ratushnyi c4b383661a STRA-101 make embedded payload lifetime test tolerate fd reuse
Linux / keyless-cuda-gate (pull_request) Skipped
Linux / verify (pull_request) Successful in 4m22s
Linux / keyless-cuda (pull_request) Skipped
Linux / static-cuda-package (pull_request) Skipped
Linux / hosted-cuda-package (pull_request) Skipped
Linux / linux-cli-container (pull_request) Successful in 4m19s
Linux / linux-static-cli (pull_request) Failing after 10m51s
Linux / release-cli (pull_request) Skipped
2026-10-07 22:04:20 +02:00
Pavlo Ratushnyi 4720ef135b fix(ci): verify fresh Gitea upload attachment URLs 2026-10-07 22:04:20 +02:00
Pavlo Ratushnyi 4fa9d307fe STRA-102 port Q6_K and Q2_0 preparation to Rust 2026-10-07 22:04:08 +02:00
Pavlo Ratushnyi 47ab90c7e0 STRA-102 port Q4_K and Q5_K preparation to Rust
Linux / keyless-cuda-gate (pull_request) Skipped
Linux / verify (pull_request) Successful in 3m52s
Linux / keyless-cuda (pull_request) Skipped
Linux / static-cuda-package (pull_request) Skipped
Linux / hosted-cuda-package (pull_request) Skipped
Linux / linux-cli-container (pull_request) Successful in 4m47s
Linux / release-cli (pull_request) Skipped
Linux / linux-static-cli (pull_request) Failing after 11m18s
2026-10-07 21:47:51 +02:00
Pavlo Ratushnyi 4ed6914d84 STRA-102 port Q8_0 and IQ4_XS preparation to Rust
Linux / keyless-cuda-gate (pull_request) Skipped
Linux / verify (pull_request) Failing after 3m22s
Linux / keyless-cuda (pull_request) Skipped
Linux / static-cuda-package (pull_request) Skipped
Linux / hosted-cuda-package (pull_request) Skipped
Linux / linux-static-cli (pull_request) Skipped
Linux / linux-cli-container (pull_request) Skipped
Linux / release-cli (pull_request) Skipped
2026-10-07 21:27:55 +02:00
Pavlo Ratushnyi 1c6d690003 feat(model): port IQ4_NL decoding to independent Rust core
Linux / keyless-cuda-gate (pull_request) Skipped
Linux / verify (pull_request) Successful in 4m58s
Linux / hosted-cuda-package (pull_request) Skipped
Linux / keyless-cuda (pull_request) Skipped
Linux / static-cuda-package (pull_request) Skipped
Linux / linux-cli-container (pull_request) Successful in 6m24s
Linux / linux-static-cli (pull_request) Failing after 12m5s
Linux / release-cli (pull_request) Skipped
2026-10-07 21:11:55 +02:00
Pavlo Ratushnyi a498381cb7 refactor(model): extract independent Rust IQ3 decoding core
Linux / keyless-cuda (pull_request) Skipped
Linux / static-cuda-package (pull_request) Skipped
Linux / hosted-cuda-package (pull_request) Skipped
Linux / keyless-cuda-gate (pull_request) Skipped
Linux / verify (pull_request) Successful in 5m16s
Linux / linux-cli-container (pull_request) Successful in 5m19s
Linux / release-cli (pull_request) Skipped
Linux / linux-static-cli (pull_request) Failing after 7m35s
2026-10-07 20:53:25 +02:00
Pavlo Ratushnyi 3bfc4a3f03 feat(engine): verify GGUF artifacts through owned Rust file handles
Linux / keyless-cuda-gate (pull_request) Skipped
Linux / verify (pull_request) Successful in 4m48s
Linux / keyless-cuda (pull_request) Skipped
Linux / static-cuda-package (pull_request) Skipped
Linux / hosted-cuda-package (pull_request) Skipped
Linux / linux-static-cli (pull_request) Failing after 7m42s
Linux / linux-cli-container (pull_request) Successful in 3m26s
Linux / release-cli (pull_request) Skipped
2026-10-07 20:33:15 +02:00
Pavlo Ratushnyi c6a3fc7e42 feat(engine): extract Rust GGUF foundation and enforce model capability tuples 2026-10-07 20:33:15 +02:00
Pavlo Ratushnyi f015052247 fix(ci): scope release write permission to Gitea publishers 2026-10-07 20:33:14 +02:00
Pavlo Ratushnyi 93109983fb fix(ci): verify actual Gitea release download routes 2026-10-07 20:00:02 +02:00
Pavlo Ratushnyi e028e5d414 fix(ci): publish verified previews through private Gitea API 2026-10-07 19:47:22 +02:00
Pavlo Ratushnyi 14bca78416 fix(ci): validate package loader and lifecycle in isolated Linux fixtures 2026-10-07 19:13:14 +02:00
Pavlo Ratushnyi 404be4c6a7 fix(ci): isolate Docker probes and workspace package provenance 2026-10-07 18:06:20 +02:00
Pavlo Ratushnyi 939dfdc813 fix(ci): install GNU time for hosted package assembly 2026-10-07 17:56:07 +02:00
Pavlo Ratushnyi e3ca4643b8 fix(ci): stage CUDA source inside GPU-hidden build container 2026-10-07 17:45:26 +02:00
Pavlo Ratushnyi 712de0f6bc fix(STRA-101): support Python 3.11 CUDA bootstrap 2026-10-07 17:12:25 +02:00
Pavlo Ratushnyi 8ec9ab5bce Pin Gitea rustup bootstrap and manual GPU gates 2026-10-07 16:44:56 +02:00
Pavlo Ratushnyi a671271317 Use root package install in Gitea job containers 2026-10-07 16:17:53 +02:00
Pavlo Ratushnyi 5c4aa294c8 Match Gitea Linux runner label 2026-10-07 16:04:52 +02:00
Pavlo Ratushnyi 5cc41008eb Build opt-in KAR PLE CUDA profile on Gitea 2026-10-07 16:03:43 +02:00
75 changed files with 11666 additions and 184 deletions
+12 -3
View File
@@ -1,20 +1,29 @@
name: Desktop foundation
on:
push:
paths: ['desktop-core/**', 'desktop/**', '.github/workflows/desktop.yml', 'rust-toolchain.toml']
# Main pushes exclude CLI release tags; feature branches use pull requests.
branches: [main]
paths: ['desktop-core/**', 'desktop/**', '.github/workflows/desktop.yml', 'rust-toolchain.toml', 'scripts/install-pinned-rustup.sh', 'Cargo.toml', 'Cargo.lock']
pull_request:
paths: ['desktop-core/**', 'desktop/**', '.github/workflows/desktop.yml', 'rust-toolchain.toml']
paths: ['desktop-core/**', 'desktop/**', '.github/workflows/desktop.yml', 'rust-toolchain.toml', 'scripts/install-pinned-rustup.sh', 'Cargo.toml', 'Cargo.lock']
permissions:
contents: read
jobs:
core:
env:
CARGO_TARGET_DIR: ${{ github.workspace }}/desktop-core/target
strategy:
fail-fast: false
matrix:
os: [ubuntu-latest, windows-latest, macos-latest]
# Windows/macOS validation is deferred and unqualified.
os: [ubuntu-latest]
runs-on: ${{ matrix.os }}
steps:
- uses: actions/checkout@v4
- name: Install Linux build tools
run: apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y ca-certificates build-essential python3 python-is-python3
- name: Install pinned Rust
run: scripts/install-pinned-rustup.sh rustup toolchain install 1.99.0 --profile minimal --component rustfmt --component clippy
- name: Format
run: cargo fmt --manifest-path desktop-core/Cargo.toml --check
- name: Tests
+250 -59
View File
@@ -15,6 +15,10 @@ on:
description: Build actual CUDA package on isolated hosted CPU (no GPU, private artifact)
type: boolean
default: false
hosted_cuda_ple:
description: Build the hosted package with experimental KAR PLE compiled (serving remains explicit and off by default)
type: boolean
default: false
static_cuda_package:
description: Build and audit static CUDA toolkit linkage on the private Linux runner (no inference)
type: boolean
@@ -25,18 +29,37 @@ permissions:
jobs:
verify:
runs-on: ubuntu-24.04
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Install build tools
run: sudo apt-get update && sudo apt-get install -y cmake ninja-build g++ python3-numpy
run: apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y cmake ninja-build g++ python3-numpy docker.io
- name: Install pinned Rust
run: rustup toolchain install 1.99.0 --profile minimal --component rustfmt --component clippy
run: scripts/install-pinned-rustup.sh rustup toolchain install 1.99.0 --profile minimal --component rustfmt --component clippy
- name: Local checks
run: scripts/check-local.sh
- name: GPU-hidden fixed PTX assembly
run: scripts/test-cuda-fixed-ptx.sh
keyless-cuda-gate:
if: gitea.event_name == 'workflow_dispatch'
runs-on: ubuntu-latest
outputs:
enabled: ${{ steps.select.outputs.enabled }}
steps:
- id: select
env:
KEYLESS_GPU: ${{ gitea.event.inputs.keyless_gpu }}
run: |
case "${KEYLESS_GPU:-false}" in
true) echo 'enabled=true' >> "$GITHUB_OUTPUT" ;;
false|'') echo 'enabled=false' >> "$GITHUB_OUTPUT" ;;
*) echo 'keyless_gpu must be a boolean input' >&2; exit 2 ;;
esac
keyless-cuda:
if: github.event_name == 'workflow_dispatch' && inputs.keyless_gpu
needs: [verify, keyless-cuda-gate]
if: needs.keyless-cuda-gate.outputs.enabled == 'true'
runs-on: [self-hosted, linux, x64, strata-gpu]
steps:
- uses: actions/checkout@v4
@@ -46,7 +69,10 @@ jobs:
run: scripts/check-kar-expert-gpu.sh
static-cuda-package:
if: github.event_name == 'workflow_dispatch' && inputs.static_cuda_package && github.event.repository.private
permissions:
contents: read
releases: write
if: gitea.event_name == 'workflow_dispatch' && gitea.event.inputs.static_cuda_package == 'true' && gitea.event.repository.private
needs: verify
runs-on: [self-hosted, linux, x64, strata-gpu]
steps:
@@ -59,14 +85,14 @@ jobs:
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
scripts/install-pinned-rustup.sh rustup toolchain install 1.99.0 --profile minimal --target 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" \
python3 scripts/build-linux-package.py --engine "$engine" --probe-in-runtime-image \
--sha256 "$(sha256sum "$engine" | cut -d ' ' -f 1)" --revision "$GITHUB_SHA" \
--build-features "${RUNNER_TEMP}/strata-static-cuda-${GITHUB_RUN_ID}/BUILD-FEATURES.json" \
--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
@@ -79,13 +105,18 @@ jobs:
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: Publish exact six-file static CUDA preview through Gitea
env:
GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }}
run: |
python3 scripts/publish-gitea-release.py --api-url https://git.vezha.io/api/v1 \
--repository "$GITHUB_REPOSITORY" --profile static-cuda \
--tag "static-cuda-preview-${GITHUB_RUN_ID}-${GITHUB_RUN_ATTEMPT}" --target "$GITHUB_SHA" \
--title "Static CUDA preview ${GITHUB_RUN_ID}.${GITHUB_RUN_ATTEMPT}" \
--notes 'Private build-only six-file preview. No hosted compiler/license receipt, GPU or model qualification.' \
--directory "${RUNNER_TEMP}/strata-package-${GITHUB_RUN_ID}"
- name: Remove uploaded package copy
if: always()
run: rm -rf -- "${RUNNER_TEMP}/strata-package-${GITHUB_RUN_ID}"
- name: Remove owned runtime image
if: always()
@@ -101,15 +132,20 @@ jobs:
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
permissions:
contents: read
releases: write
if: gitea.event_name == 'workflow_dispatch' && (gitea.event.inputs.hosted_cuda_package == 'true' || gitea.event.inputs.hosted_cuda_ple == 'true') && gitea.event.repository.private
needs: verify
runs-on: ubuntu-24.04
runs-on: ubuntu-latest
timeout-minutes: 150
env:
CUDA_VISIBLE_DEVICES: ''
NVIDIA_VISIBLE_DEVICES: void
BUILD_JOBS: '1'
CARGO_BUILD_JOBS: '2'
CUDA_ARCHITECTURES: '120'
STRATA_KAR_PLE: ${{ inputs.hosted_cuda_ple && '1' || '0' }}
steps:
- uses: actions/checkout@v4
- name: Install compatible host tools (no drivers)
@@ -117,35 +153,114 @@ jobs:
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 && DEBIAN_FRONTEND=noninteractive apt-get install -y ca-certificates musl-tools binutils docker.io python3 time
- name: Actual runtime-image loader boundary without GPU
run: PYTHONDONTWRITEBYTECODE=1 python3 scripts/test-package-loader-container.py
- name: Assemble pinned build-only CUDA components
run: python3 scripts/bootstrap-cuda-toolkit.py --output "$CUDAToolkit_ROOT"
- name: Build pinned GPU-hidden compiler image
env:
CUDA_BUILDER_BASE: ubuntu@sha256:f610ab94648195aa356059f5b41d6085c9d4d903c072430cdd1af7bdb646106b
CUDA_BUILDER_IMAGE: leleka-cuda-builder:${{ github.run_id }}
run: |
context="$RUNNER_TEMP/strata-cuda-builder-context"
mkdir -p "$context"
cp deploy/Dockerfile.cuda-builder "$context/Dockerfile"
cp /etc/ssl/certs/ca-certificates.crt "$context/runner-ca-bundle.crt"
docker build --platform linux/amd64 --build-arg "BUILDER_BASE=$CUDA_BUILDER_BASE" \
--tag "$CUDA_BUILDER_IMAGE" "$context"
docker image inspect --format '{{.Id}}' "$CUDA_BUILDER_IMAGE" > "$RUNNER_TEMP/CUDA-BUILDER-IMAGE-ID"
- name: Record actual toolchain
env:
CUDA_BUILDER_IMAGE: leleka-cuda-builder:${{ github.run_id }}
CUDA_BUILDER_BASE: ubuntu@sha256:f610ab94648195aa356059f5b41d6085c9d4d903c072430cdd1af7bdb646106b
run: |
"$CUDACXX" --version
g++-13 --version
docker run --rm --platform linux/amd64 --network none "$CUDA_BUILDER_IMAGE" g++-13 --version
df -h "$RUNNER_TEMP"
free -h
python3 - <<'PYTOOL'
import json, os, platform, subprocess
from pathlib import Path
info=json.loads((Path(os.environ['CUDAToolkit_ROOT'])/'TOOLKIT-PROVENANCE.json').read_text())
packages=subprocess.check_output(['docker','run','--rm','--platform','linux/amd64','--network','none',
os.environ['CUDA_BUILDER_IMAGE'],'dpkg-query','-W','-f=${binary:Package}=${Version}'+chr(10),
'binutils','ca-certificates','cmake','gcc-13','g++-13','git','make','python3'],text=True).splitlines()
gcc=subprocess.check_output(['docker','run','--rm','--platform','linux/amd64','--network','none',
os.environ['CUDA_BUILDER_IMAGE'],'g++-13','--version'],text=True)
info.update(source=os.environ['GITHUB_SHA'], runner_os=platform.platform(),
gcc=subprocess.check_output(['g++-13','--version'],text=True),
builder_base=os.environ['CUDA_BUILDER_BASE'],
builder_image_id=Path(os.environ['RUNNER_TEMP'],'CUDA-BUILDER-IMAGE-ID').read_text().strip(),
builder_packages=packages,
gcc=gcc,
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
CUDA_BUILDER_IMAGE: leleka-cuda-builder:${{ github.run_id }}
STRATA_KAR_PLE: ${{ inputs.hosted_cuda_ple && '1' || '0' }}
run: |
mkdir -p "$STRATA_BUILD_DIR"
container="leleka-cuda-build-${GITHUB_RUN_ID}"
volume="leleka-cuda-build-${GITHUB_RUN_ID}"
source_archive="$RUNNER_TEMP/strata-cuda-source.tar"
cleanup() {
docker rm -f "$container" >/dev/null 2>&1 || true
docker volume rm "$volume" >/dev/null 2>&1 || true
rm -f -- "$source_archive"
}
trap cleanup EXIT
git -C "$GITHUB_WORKSPACE" archive --format=tar "$GITHUB_SHA" > "$source_archive"
docker volume create "$volume" >/dev/null
docker create --name "$container" --platform linux/amd64 --network bridge --read-only \
--cap-drop ALL --security-opt no-new-privileges \
--tmpfs /tmp:rw,nosuid,size=2g --mount "type=volume,src=$volume,dst=/work" \
-e CUDA_VISIBLE_DEVICES= -e NVIDIA_VISIBLE_DEVICES=void \
"$CUDA_BUILDER_IMAGE" /bin/bash -euc 'sleep infinity' >/dev/null
docker start "$container" >/dev/null
docker exec "$container" mkdir -p /work/workspace /work/toolkit /work/build
docker exec "$container" chmod 0777 /work/build
# Stage tracked source only. docker cp streams the archive from the
# runner container; bind mounts cannot use its path on the daemon host.
docker cp "$source_archive" "$container:/work/source.tar"
docker exec "$container" tar -xf /work/source.tar -C /work/workspace
docker exec "$container" rm /work/source.tar
docker cp "$CUDAToolkit_ROOT/." "$container:/work/toolkit/"
docker exec --user "$(id -u):$(id -g)" \
-e CUDA_VISIBLE_DEVICES= -e NVIDIA_VISIBLE_DEVICES=void \
-e CUDACXX=/work/toolkit/bin/nvcc -e CUDAToolkit_ROOT=/work/toolkit \
-e CC=/usr/bin/gcc-13 -e CXX=/usr/bin/g++-13 -e CUDAHOSTCXX=/usr/bin/g++-13 \
-e BUILD_JOBS="$BUILD_JOBS" -e CUDA_ARCHITECTURES="$CUDA_ARCHITECTURES" \
-e STRATA_KAR_PLE="$STRATA_KAR_PLE" -e STRATA_BUILD_DIR=/work/build \
-e SOURCE_REVISION="$GITHUB_SHA" \
"$container" /bin/bash -euo pipefail -c '
if compgen -G "/dev/nvidia*" >/dev/null; then
echo "NVIDIA devices unexpectedly visible in build container" >&2
exit 1
fi
cd /work/workspace
scripts/build-static-cuda.sh
'
docker cp "$container:/work/build/strata" "$STRATA_BUILD_DIR/strata"
docker cp "$container:/work/build/BUILD-FEATURES.json" "$STRATA_BUILD_DIR/BUILD-FEATURES.json"
- name: Bind compile capability to CUDA toolchain provenance
run: |
python3 - <<'PYFEATURES'
import hashlib, json, os
from pathlib import Path
features_path=Path(os.environ['STRATA_BUILD_DIR'])/'BUILD-FEATURES.json'
features=json.loads(features_path.read_text())
toolchain_path=Path(os.environ['RUNNER_TEMP'])/'CUDA-TOOLCHAIN.json'
info=json.loads(toolchain_path.read_text())
info['build_features']=features['features']
info['build_features_sha256']=hashlib.sha256(features_path.read_bytes()).hexdigest()
toolchain_path.write_text(json.dumps(info,indent=2)+'\n')
PYFEATURES
- name: Install pinned Rust and musl target
run: |
rustup toolchain install 1.99.0 --profile minimal
rustup target add --toolchain 1.99.0 x86_64-unknown-linux-musl
scripts/install-pinned-rustup.sh rustup toolchain install 1.99.0 --profile minimal --target x86_64-unknown-linux-musl
- name: Assemble actual combined executable and runtime image
run: |
# Keep resource evidence even if the hosted runner terminates this job.
@@ -159,8 +274,9 @@ jobs:
trap 'kill "$resource_sampler" 2>/dev/null || true; wait "$resource_sampler" 2>/dev/null || true' EXIT
engine="$STRATA_BUILD_DIR/strata"
package="$RUNNER_TEMP/strata-hosted-cuda-package"
/usr/bin/time -v python3 scripts/build-linux-package.py --engine "$engine" \
/usr/bin/time -v python3 scripts/build-linux-package.py --engine "$engine" --probe-in-runtime-image \
--sha256 "$(sha256sum "$engine" | cut -d ' ' -f 1)" --revision "$GITHUB_SHA" \
--build-features "$STRATA_BUILD_DIR/BUILD-FEATURES.json" \
--cargo-target-dir "$RUNNER_TEMP/strata-hosted-package-build" --output "$package"
python3 scripts/build-runtime-image.py --package "$package" \
--receipt-sha256 "$(sha256sum "$package/SHA256SUMS" | cut -d ' ' -f 1)" \
@@ -168,16 +284,40 @@ jobs:
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"
python3 - <<'PYBIND'
import hashlib, json, os
from pathlib import Path
package=Path(os.environ['RUNNER_TEMP'])/'strata-hosted-cuda-package'
receipt=json.loads((package/'PROVENANCE.json').read_text())
image=json.loads((package/'IMAGE-PROVENANCE.json').read_text())
path=Path(os.environ['RUNNER_TEMP'])/'CUDA-TOOLCHAIN.json'
toolchain=json.loads(path.read_text())
with (package/'runtime-image.tar').open('rb') as archive:
archive_sha=hashlib.file_digest(archive, 'sha256').hexdigest()
toolchain['docker_builder']={
'source_commit': os.environ['GITHUB_SHA'],
'image_id': toolchain['builder_image_id'],
'engine_sha256': receipt['engine']['sha256'],
'build_features_sha256': receipt['build_features_sha256'],
'runtime_image_id': image['image'],
'runtime_archive_sha256': archive_sha}
path.write_text(json.dumps(toolchain,indent=2)+'\n')
PYBIND
cp "$RUNNER_TEMP/CUDA-TOOLCHAIN.json" "$package/CUDA-TOOLCHAIN.json"
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: Publish exact eight-file hosted CUDA preview through Gitea
env:
GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }}
run: |
python3 scripts/publish-gitea-release.py --api-url https://git.vezha.io/api/v1 \
--repository "$GITHUB_REPOSITORY" --profile cuda \
--tag "cuda-preview-${GITHUB_RUN_ID}-${GITHUB_RUN_ATTEMPT}" --target "$GITHUB_SHA" \
--title "Hosted CUDA preview ${GITHUB_RUN_ID}.${GITHUB_RUN_ATTEMPT}" \
--notes 'Private build-only preview. GPU-hidden loader identity and help passed; no GPU/model inference or performance qualification.' \
--directory "$RUNNER_TEMP/strata-hosted-cuda-package"
- name: Remove uploaded package copy
if: always()
run: rm -rf -- "$RUNNER_TEMP/strata-hosted-cuda-package"
- name: Remove owned intermediate image and build files
if: always()
@@ -188,18 +328,24 @@ jobs:
docker image rm "$image"
fi
rm -rf -- "$RUNNER_TEMP/strata-cuda-toolkit" "$RUNNER_TEMP/strata-hosted-cuda-engine" "$RUNNER_TEMP/strata-hosted-package-build"
docker image rm "leleka-cuda-builder:${GITHUB_RUN_ID}" 2>/dev/null || true
rm -rf -- "$RUNNER_TEMP/strata-cuda-builder-context" "$RUNNER_TEMP/CUDA-BUILDER-IMAGE-ID"
linux-static-cli:
permissions:
contents: read
releases: write
needs: verify
runs-on: ubuntu-24.04
runs-on: ubuntu-latest
env:
CARGO_TARGET_DIR: ${{ github.workspace }}/control-plane/target
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 && DEBIAN_FRONTEND=noninteractive apt-get install -y musl-tools cmake binutils python3-numpy docker.io
- name: Install pinned Rust and target
run: |
rustup toolchain install 1.99.0 --profile minimal
rustup target add --toolchain 1.99.0 x86_64-unknown-linux-musl
scripts/install-pinned-rustup.sh rustup toolchain install 1.99.0 --profile minimal --target x86_64-unknown-linux-musl
- name: Build static CLI
run: cargo build --manifest-path control-plane/Cargo.toml --locked --release --target x86_64-unknown-linux-musl --bin strata-next
- name: Verify ELF and checksum
@@ -253,12 +399,7 @@ jobs:
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: |
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
python3 scripts/smoke-systemd-manager.py control-plane/target/x86_64-unknown-linux-musl/release/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
- name: Native deployment readiness deadline without GPU
@@ -320,16 +461,25 @@ jobs:
docker image rm "$image"
rm "$receipt"
fi
- uses: actions/upload-artifact@v4
with:
name: strata-next-linux-x86_64-musl
path: dist/
- name: Publish exact four-file CLI preview through Gitea
env:
GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }}
run: |
python3 scripts/publish-gitea-release.py --api-url https://git.vezha.io/api/v1 \
--repository "$GITHUB_REPOSITORY" --profile cli \
--tag "cli-preview-${GITHUB_RUN_ID}-${GITHUB_RUN_ATTEMPT}" --target "$GITHUB_SHA" \
--title "CLI preview ${GITHUB_RUN_ID}.${GITHUB_RUN_ATTEMPT}" \
--notes 'CLI/control-plane preview. CUDA engine and model files are not included.' --directory dist
linux-cli-container:
needs: verify
runs-on: ubuntu-24.04
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Install Docker CLI and verify runner daemon
run: |
command -v docker >/dev/null 2>&1 || { apt-get update -qq; DEBIAN_FRONTEND=noninteractive apt-get install -y -qq docker.io; }
docker version
- 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
@@ -339,20 +489,61 @@ jobs:
run: docker image rm strata-cli-check || true
release-cli:
permissions:
contents: read
releases: write
if: startsWith(github.ref, 'refs/tags/v')
needs: [linux-static-cli, linux-cli-container]
runs-on: ubuntu-24.04
permissions:
contents: write
runs-on: ubuntu-latest
env:
CARGO_TARGET_DIR: ${{ github.workspace }}/control-plane/target
steps:
- uses: actions/download-artifact@v4
- uses: actions/checkout@v4
with:
name: strata-next-linux-x86_64-musl
path: dist/
- name: Publish CLI preview release
env:
GH_TOKEN: ${{ github.token }}
ref: ${{ github.ref }}
- name: Require the exact gated tag commit
run: test "$(git rev-parse HEAD)" = "$GITHUB_SHA"
- name: Install musl toolchain
run: apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y musl-tools cmake binutils python3
- name: Install pinned Rust and target
run: scripts/install-pinned-rustup.sh rustup toolchain install 1.99.0 --profile minimal --target x86_64-unknown-linux-musl
- name: Rebuild static CLI at the exact gated tag
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: |
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
binary=control-plane/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 verified tagged CLI preview through Gitea
env:
GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }}
run: |
python3 scripts/publish-gitea-release.py --api-url https://git.vezha.io/api/v1 \
--repository "$GITHUB_REPOSITORY" --profile cli --tag "$GITHUB_REF_NAME" --target "$GITHUB_SHA" \
--title "Strata Next ${GITHUB_REF_NAME}" \
--notes 'CLI/control-plane preview rebuilt at the exact tag after CLI and container gates passed. CUDA engine and model files are not included.' \
--directory dist
Generated
+24
View File
@@ -1007,6 +1007,28 @@ dependencies = [
name = "leleka-backend-api"
version = "0.1.0"
[[package]]
name = "leleka-cuda-driver"
version = "0.1.0"
dependencies = [
"libc",
]
[[package]]
name = "leleka-model-format"
version = "0.1.0"
dependencies = [
"sha2",
]
[[package]]
name = "leleka-quant-core"
version = "0.1.0"
dependencies = [
"hex",
"sha2",
]
[[package]]
name = "leleka-tokenizer"
version = "0.1.0"
@@ -2005,6 +2027,8 @@ dependencies = [
"http-body",
"http-body-util",
"jsonschema",
"leleka-model-format",
"leleka-quant-core",
"leleka-tokenizer",
"libc",
"regex",
+2 -2
View File
@@ -1,7 +1,7 @@
[workspace]
resolver = "3"
members = ["crates/backend-api", "crates/tokenizer", "control-plane", "desktop-core"]
default-members = ["crates/backend-api", "crates/tokenizer", "control-plane", "desktop-core"]
members = ["crates/backend-api", "crates/tokenizer", "crates/model-format", "crates/quant-core", "crates/cuda-driver", "control-plane", "desktop-core"]
default-members = ["crates/backend-api", "crates/tokenizer", "crates/model-format", "crates/quant-core", "control-plane", "desktop-core"]
[workspace.package]
edition = "2024"
+2
View File
@@ -14,6 +14,8 @@ axum = "0.8"
futures-core = "0.3"
hex = "0.4"
leleka-tokenizer = { path = "../crates/tokenizer" }
leleka-model-format = { path = "../crates/model-format" }
leleka-quant-core = { path = "../crates/quant-core" }
http-body = "1"
jsonschema = { version = "0.58.4", default-features = false }
libc = "0.2"
+14 -3
View File
@@ -118,7 +118,7 @@ mod tests {
#[cfg(target_os = "linux")]
#[test]
fn sealed_payload_is_exact_immutable_and_removed_on_drop() {
use std::io::Write;
use std::{io::Write, 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");
@@ -126,8 +126,19 @@ mod tests {
assert!(other.write_all(b"x").is_err());
assert!(other.set_len(0).is_err());
assert!(other.set_len(100).is_err());
drop(other);
// Keep a witness open so this inode cannot be recycled during the check.
// Parallel tests can reuse the original descriptor number after Drop.
let original = other.metadata().unwrap();
assert_eq!(std::fs::metadata(&path).unwrap().ino(), original.ino());
drop(engine);
assert!(!path.exists());
match std::fs::metadata(&path) {
Ok(current) => assert_ne!(
(current.dev(), current.ino()),
(original.dev(), original.ino()),
"original descriptor still refers to the payload after Drop"
),
Err(error) => assert_eq!(error.kind(), std::io::ErrorKind::NotFound),
}
drop(other);
}
}
File diff suppressed because it is too large Load Diff
+945
View File
@@ -3,6 +3,8 @@
use std::io::{Read, Seek, SeekFrom};
use leleka_quant_core::{iq2_s, iq3_xxs, iq4_nl, iq4_xs, q2_0, q4_k, q5_k, q6_k, q8_0};
use crate::{ggml_bridge, gguf, iq3_s, kar_codec};
pub const SOURCE_CHUNK_BYTES: usize = 256 * iq3_s::BLOCK_BYTES;
@@ -23,6 +25,25 @@ where
{
let (block_elements, block_bytes) = gguf::block_geometry(source_kind)
.ok_or_else(|| format!("unsupported GGUF source kind {source_kind}"))?;
let rust_geometry = match source_kind {
8 => Some((q8_0::BLOCK_ELEMENTS, q8_0::BLOCK_BYTES, "Q8_0")),
12 => Some((q4_k::BLOCK_ELEMENTS, q4_k::BLOCK_BYTES, "Q4_K")),
13 => Some((q5_k::BLOCK_ELEMENTS, q5_k::BLOCK_BYTES, "Q5_K")),
14 => Some((q6_k::BLOCK_ELEMENTS, q6_k::BLOCK_BYTES, "Q6_K")),
42 => Some((q2_0::BLOCK_ELEMENTS, q2_0::BLOCK_BYTES, "Q2_0")),
18 => Some((iq3_xxs::BLOCK_ELEMENTS, iq3_xxs::BLOCK_BYTES, "IQ3_XXS")),
22 => Some((iq2_s::BLOCK_ELEMENTS, iq2_s::BLOCK_BYTES, "IQ2_S")),
20 => Some((iq4_nl::BLOCK_ELEMENTS, iq4_nl::BLOCK_BYTES, "IQ4_NL")),
23 => Some((iq4_xs::BLOCK_ELEMENTS, iq4_xs::BLOCK_BYTES, "IQ4_XS")),
_ => None,
};
if let Some((elements, bytes, format)) = rust_geometry
&& (block_elements != elements as u64 || block_bytes != bytes as u64)
{
return Err(format!(
"{format} decoder geometry differs from GGUF source kind {source_kind}"
));
}
let block_bytes = usize::try_from(block_bytes).map_err(|_| "GGUF block is too large")?;
if block_bytes > SOURCE_CHUNK_BYTES {
return Err("GGUF block exceeds bounded source chunk".into());
@@ -60,6 +81,70 @@ where
}
callback(source, &derived)?;
}
8 => {
for block in source.as_chunks::<{ q8_0::BLOCK_BYTES }>().0 {
for value in q8_0::decode_block(block)? {
derived.extend_from_slice(&value.to_le_bytes());
}
}
callback(source, &derived)?;
}
12 => {
for block in source.as_chunks::<{ q4_k::BLOCK_BYTES }>().0 {
for value in q4_k::decode_block(block)? {
derived.extend_from_slice(&value.to_le_bytes());
}
}
callback(source, &derived)?;
}
13 => {
for block in source.as_chunks::<{ q5_k::BLOCK_BYTES }>().0 {
for value in q5_k::decode_block(block)? {
derived.extend_from_slice(&value.to_le_bytes());
}
}
callback(source, &derived)?;
}
14 => {
for block in source.as_chunks::<{ q6_k::BLOCK_BYTES }>().0 {
for value in q6_k::decode_block(block)? {
derived.extend_from_slice(&value.to_le_bytes());
}
}
callback(source, &derived)?;
}
42 => {
for block in source.as_chunks::<{ q2_0::BLOCK_BYTES }>().0 {
for value in q2_0::decode_block(block)? {
derived.extend_from_slice(&value.to_le_bytes());
}
}
callback(source, &derived)?;
}
18 => {
for block in source.as_chunks::<{ iq3_xxs::BLOCK_BYTES }>().0 {
for value in iq3_xxs::decode_block(block)? {
derived.extend_from_slice(&value.to_le_bytes());
}
}
callback(source, &derived)?;
}
22 => {
for block in source.as_chunks::<{ iq2_s::BLOCK_BYTES }>().0 {
for value in iq2_s::decode_block(block)? {
derived.extend_from_slice(&value.to_le_bytes());
}
}
callback(source, &derived)?;
}
20 => {
for block in source.as_chunks::<{ iq4_nl::BLOCK_BYTES }>().0 {
for value in iq4_nl::decode_block(block)? {
derived.extend_from_slice(&value.to_le_bytes());
}
}
callback(source, &derived)?;
}
21 => {
for block in source.as_chunks::<{ iq3_s::BLOCK_BYTES }>().0 {
for value in iq3_s::decode_block(block)? {
@@ -68,6 +153,14 @@ where
}
callback(source, &derived)?;
}
23 => {
for block in source.as_chunks::<{ iq4_xs::BLOCK_BYTES }>().0 {
for value in iq4_xs::decode_block(block)? {
derived.extend_from_slice(&value.to_le_bytes());
}
}
callback(source, &derived)?;
}
_ => {
let values = (count / block_bytes)
.checked_mul(block_elements as usize)
@@ -134,6 +227,311 @@ mod tests {
);
}
#[test]
fn iq4_stream_spans_chunks_with_exact_c_parity_and_source_offsets() {
let blocks_per_chunk = SOURCE_CHUNK_BYTES / iq4_nl::BLOCK_BYTES;
let blocks = blocks_per_chunk + 257;
let prefix = 13;
let mut source = vec![0xa5; prefix];
for block_index in 0..blocks {
let mut block = [0u8; iq4_nl::BLOCK_BYTES];
let scale: u16 = [0x0001, 0x03ff, 0x0400, 0x3800, 0xbc00, 0x7bff][block_index % 6];
block[..2].copy_from_slice(&scale.to_le_bytes());
for (position, byte) in block[2..].iter_mut().enumerate() {
*byte = (block_index + position * 17) as u8;
}
source.extend_from_slice(&block);
}
let source_bytes = blocks * iq4_nl::BLOCK_BYTES;
source.extend_from_slice(&[0x5a; 31]);
let mut cursor = Cursor::new(&source);
let mut consumed = 0;
let mut chunks = Vec::new();
let output_bytes = visit(
&mut cursor,
prefix as u64,
20,
source_bytes as u64,
|raw, derived| {
assert!(raw.len() <= SOURCE_CHUNK_BYTES);
assert!(raw.len().is_multiple_of(iq4_nl::BLOCK_BYTES));
assert!(derived.len() <= blocks_per_chunk * iq4_nl::BLOCK_ELEMENTS * 4);
assert_eq!(
raw,
&source[prefix + consumed..prefix + consumed + raw.len()]
);
let mut reference =
vec![0.0; raw.len() / iq4_nl::BLOCK_BYTES * iq4_nl::BLOCK_ELEMENTS];
ggml_bridge::decode_into(20, raw, &mut reference).unwrap();
let reference_bytes: Vec<u8> = reference
.iter()
.flat_map(|value| value.to_le_bytes())
.collect();
assert_eq!(derived, reference_bytes);
consumed += raw.len();
chunks.push((raw.len(), derived.len()));
Ok(())
},
)
.unwrap();
assert_eq!(
chunks,
[
(
blocks_per_chunk * iq4_nl::BLOCK_BYTES,
blocks_per_chunk * iq4_nl::BLOCK_ELEMENTS * 4
),
(257 * iq4_nl::BLOCK_BYTES, 257 * iq4_nl::BLOCK_ELEMENTS * 4),
]
);
assert_eq!(consumed, source_bytes);
assert_eq!(output_bytes, (blocks * iq4_nl::BLOCK_ELEMENTS * 4) as u64);
assert_eq!(cursor.position(), (prefix + source_bytes) as u64);
}
#[test]
fn iq4_stream_refuses_invalid_shapes_before_seek_or_callback() {
for source_bytes in [0, 1, 17, 19, 37] {
let mut cursor = Cursor::new([0u8; 64]);
cursor.set_position(7);
let mut calls = 0;
let error = visit(&mut cursor, 13, 20, source_bytes, |_, _| {
calls += 1;
Ok(())
})
.unwrap_err();
assert_eq!(error, "GGUF source tensor is empty or not block-aligned");
assert_eq!(calls, 0);
assert_eq!(cursor.position(), 7);
}
}
#[test]
fn iq4_stream_truncation_never_delivers_an_incomplete_chunk() {
let chunk_bytes = SOURCE_CHUNK_BYTES / iq4_nl::BLOCK_BYTES * iq4_nl::BLOCK_BYTES;
for available in [
iq4_nl::BLOCK_BYTES - 1,
chunk_bytes + iq4_nl::BLOCK_BYTES - 1,
] {
let requested = if available < chunk_bytes {
iq4_nl::BLOCK_BYTES
} else {
chunk_bytes + iq4_nl::BLOCK_BYTES
};
let mut calls = 0;
let result = visit(
&mut Cursor::new(vec![0u8; available]),
0,
20,
requested as u64,
|raw, derived| {
calls += 1;
assert_eq!(raw.len(), chunk_bytes);
assert_eq!(
derived.len(),
chunk_bytes / iq4_nl::BLOCK_BYTES * iq4_nl::BLOCK_ELEMENTS * 4
);
Ok(())
},
);
assert!(result.is_err());
assert_eq!(calls, usize::from(available >= chunk_bytes));
}
}
#[test]
fn iq4_stream_callback_failure_stops_without_reading_the_next_chunk() {
let chunk_bytes = SOURCE_CHUNK_BYTES / iq4_nl::BLOCK_BYTES * iq4_nl::BLOCK_BYTES;
for fail_on in [1, 2] {
let mut cursor = Cursor::new(vec![0u8; chunk_bytes * 3]);
let mut calls = 0;
let error = visit(&mut cursor, 0, 20, (chunk_bytes * 3) as u64, |raw, _| {
calls += 1;
assert_eq!(raw.len(), chunk_bytes);
if calls == fail_on {
Err("owned callback failure".into())
} else {
Ok(())
}
})
.unwrap_err();
assert_eq!(error, "owned callback failure");
assert_eq!(calls, fail_on);
assert_eq!(cursor.position(), (chunk_bytes * fail_on) as u64);
}
}
#[test]
fn iq4_stream_preserves_existing_nonfinite_classification_and_infinity_signs() {
for scale in [0x7c00u16, 0xfc00, 0x7c01, 0x7fff, 0xfc01, 0xffff] {
let mut source = AlignedSource([0u8; SOURCE_CHUNK_BYTES]);
source.0[..2].copy_from_slice(&scale.to_le_bytes());
for (position, byte) in source.0[2..iq4_nl::BLOCK_BYTES].iter_mut().enumerate() {
*byte = ((position as u8) << 4) | (15 - position as u8);
}
let raw = &source.0[..iq4_nl::BLOCK_BYTES];
let mut reference = [0.0; iq4_nl::BLOCK_ELEMENTS];
ggml_bridge::decode_into(20, raw, &mut reference).unwrap();
let mut calls = 0;
let count = visit(
&mut Cursor::new(raw),
0,
20,
iq4_nl::BLOCK_BYTES as u64,
|_, derived| {
calls += 1;
for (word, reference) in derived.as_chunks::<4>().0.iter().zip(reference) {
let actual = f32::from_le_bytes(*word);
if reference.is_nan() {
assert!(actual.is_nan());
} else {
assert!(reference.is_infinite());
assert_eq!(actual.to_bits(), reference.to_bits());
}
}
assert_eq!(derived.len(), iq4_nl::BLOCK_ELEMENTS * 4);
Ok(())
},
)
.unwrap();
assert_eq!(calls, 1);
assert_eq!(count, (iq4_nl::BLOCK_ELEMENTS * 4) as u64);
}
}
#[test]
fn q8_and_iq4xs_streams_preserve_bounded_c_bytes_offsets_and_receipts() {
for kind in [8, 23] {
let (elements, bytes) = gguf::block_geometry(kind).unwrap();
let bytes = bytes as usize;
let per_chunk = SOURCE_CHUNK_BYTES / bytes;
let blocks = per_chunk + 17;
let prefix = 11;
let mut source = vec![0xa5; prefix];
for number in 0..blocks {
let mut block = vec![0u8; bytes];
let scale: u16 = [0, 0x8000, 1, 0x83ff, 0x0400, 0x3800, 0xbc00, 0x7bff][number % 8];
block[..2].copy_from_slice(&scale.to_le_bytes());
for (position, byte) in block[2..].iter_mut().enumerate() {
*byte = (number * 17 + position * 29) as u8;
}
source.extend_from_slice(&block);
}
let source_bytes = blocks * bytes;
source.extend_from_slice(&[0x5a; 19]);
let mut cursor = Cursor::new(&source);
let mut consumed = 0;
let mut chunks = Vec::new();
let receipt = visit(
&mut cursor,
prefix as u64,
kind,
source_bytes as u64,
|raw, derived| {
assert!(raw.len() <= SOURCE_CHUNK_BYTES);
assert_eq!(
raw,
&source[prefix + consumed..prefix + consumed + raw.len()]
);
let mut oracle = vec![0.0; raw.len() / bytes * elements as usize];
ggml_bridge::decode_into(kind, raw, &mut oracle).unwrap();
let expected: Vec<u8> = oracle
.iter()
.flat_map(|value| value.to_le_bytes())
.collect();
assert_eq!(derived, expected, "kind {kind}");
assert!(derived.len() <= per_chunk * elements as usize * 4);
chunks.push((raw.len(), derived.len()));
consumed += raw.len();
Ok(())
},
)
.unwrap();
assert_eq!(
chunks,
[
(per_chunk * bytes, per_chunk * elements as usize * 4),
(17 * bytes, 17 * elements as usize * 4)
]
);
assert_eq!(consumed, source_bytes);
assert_eq!(receipt, blocks as u64 * elements * 4);
assert_eq!(cursor.position(), (prefix + source_bytes) as u64);
let mut calls = 0;
assert!(
visit(
&mut Cursor::new(&source),
prefix as u64,
kind,
source_bytes as u64 - 1,
|_, _| {
calls += 1;
Ok(())
}
)
.is_err()
);
assert_eq!(calls, 0);
let mut truncated = Cursor::new(&source[..prefix + bytes - 1]);
assert!(
visit(&mut truncated, prefix as u64, kind, bytes as u64, |_, _| {
calls += 1;
Ok(())
})
.is_err()
);
assert_eq!(calls, 0);
let mut cursor = Cursor::new(&source);
let error = visit(
&mut cursor,
prefix as u64,
kind,
source_bytes as u64,
|_, _| {
calls += 1;
Err("owned callback abort".into())
},
)
.unwrap_err();
assert_eq!(error, "owned callback abort");
assert_eq!(calls, 1);
assert_eq!(cursor.position(), (prefix + per_chunk * bytes) as u64);
}
}
#[test]
fn q8_and_iq4xs_streams_preserve_nonfinite_classification_and_infinity_bits() {
for kind in [8, 23] {
let (elements, bytes) = gguf::block_geometry(kind).unwrap();
for scale in [0x7c00u16, 0xfc00, 0x7c01, 0xfc01, 0x7e00, 0xfe00] {
let mut block = vec![0u8; bytes as usize];
block[..2].copy_from_slice(&scale.to_le_bytes());
for (position, byte) in block[2..].iter_mut().enumerate() {
*byte = (position * 29) as u8;
}
let mut oracle = vec![0.0; elements as usize];
ggml_bridge::decode_into(kind, &block, &mut oracle).unwrap();
let mut calls = 0;
let receipt = visit(&mut Cursor::new(&block), 0, kind, bytes, |raw, derived| {
assert_eq!(raw, block);
for (actual, reference) in derived.as_chunks::<4>().0.iter().zip(&oracle) {
let actual = f32::from_le_bytes(*actual);
if reference.is_nan() {
assert!(actual.is_nan());
} else {
assert_eq!(actual.to_bits(), reference.to_bits());
}
}
calls += 1;
Ok(())
})
.unwrap();
assert_eq!(calls, 1);
assert_eq!(receipt, elements * 4);
}
}
}
#[test]
fn actual_target_quant_types_decode_one_block_each() {
for kind in [8, 12, 13, 14, 18, 20, 21, 22, 23, 42] {
@@ -158,4 +556,551 @@ mod tests {
);
}
}
#[test]
fn q4_q5_k_streams_preserve_bounded_c_bytes_offsets_receipts_and_failure_semantics() {
let edges = [
0x0000u16, 0x8000, 0x0001, 0x83ff, 0x0400, 0x3555, 0xbc00, 0x7bff,
];
for kind in [12, 13] {
let (elements, bytes) = gguf::block_geometry(kind).unwrap();
let bytes = bytes as usize;
let per_chunk = SOURCE_CHUNK_BYTES / bytes;
let blocks = per_chunk + 17;
let prefix = 11;
let mut source = vec![0xa5; prefix];
for number in 0..blocks {
let mut block = vec![0u8; bytes];
block[..2].copy_from_slice(&edges[number % edges.len()].to_le_bytes());
block[2..4].copy_from_slice(&edges[(number * 7 + 3) % edges.len()].to_le_bytes());
for (position, byte) in block[4..].iter_mut().enumerate() {
*byte = (number * 17 + position * 29) as u8;
}
source.extend_from_slice(&block);
}
let requested = blocks * bytes;
source.extend_from_slice(&[0x5a; 19]);
let mut cursor = Cursor::new(&source);
let mut consumed = 0;
let mut chunks = Vec::new();
let receipt = visit(
&mut cursor,
prefix as u64,
kind,
requested as u64,
|raw, derived| {
assert!(raw.len() <= SOURCE_CHUNK_BYTES);
assert_eq!(
raw,
&source[prefix + consumed..prefix + consumed + raw.len()]
);
let mut oracle = vec![0.0; raw.len() / bytes * elements as usize];
ggml_bridge::decode_into(kind, raw, &mut oracle).unwrap();
let expected: Vec<u8> = oracle
.iter()
.flat_map(|value| value.to_le_bytes())
.collect();
assert_eq!(derived, expected, "kind {kind}");
assert!(derived.len() <= per_chunk * elements as usize * 4);
chunks.push((raw.len(), derived.len()));
consumed += raw.len();
Ok(())
},
)
.unwrap();
assert_eq!(
chunks,
[
(per_chunk * bytes, per_chunk * elements as usize * 4),
(17 * bytes, 17 * elements as usize * 4)
]
);
assert_eq!(consumed, requested);
assert_eq!(receipt, blocks as u64 * elements * 4);
assert_eq!(cursor.position(), (prefix + requested) as u64);
for malformed in [0, 1, bytes - 1, bytes + 1] {
let mut cursor = Cursor::new(&source);
cursor.set_position(7);
let mut calls = 0;
assert!(
visit(
&mut cursor,
prefix as u64,
kind,
malformed as u64,
|_, _| {
calls += 1;
Ok(())
}
)
.is_err()
);
assert_eq!(calls, 0);
assert_eq!(cursor.position(), 7);
}
for delivered in [0, 1] {
let available = delivered * per_chunk * bytes + bytes - 1;
let required = delivered * per_chunk * bytes + bytes;
let mut calls = 0;
assert!(
visit(
&mut Cursor::new(&source[..prefix + available]),
prefix as u64,
kind,
required as u64,
|raw, derived| {
calls += 1;
assert_eq!(raw.len(), per_chunk * bytes);
assert_eq!(derived.len(), per_chunk * elements as usize * 4);
Ok(())
}
)
.is_err()
);
assert_eq!(calls, delivered);
}
for fail_on in [1, 2] {
let mut cursor = Cursor::new(&source);
let mut calls = 0;
let error = visit(
&mut cursor,
prefix as u64,
kind,
requested as u64,
|_, _| {
calls += 1;
if calls == fail_on {
Err("owned callback abort".into())
} else {
Ok(())
}
},
)
.unwrap_err();
assert_eq!(error, "owned callback abort");
assert_eq!(calls, fail_on);
assert_eq!(
cursor.position(),
(prefix
+ if fail_on == 1 {
per_chunk * bytes
} else {
requested
}) as u64
);
}
}
}
#[test]
fn q4_q5_k_streams_preserve_both_nonfinite_scale_roles_and_zero_packed_fields() {
let scales = [
0x0000u16, 0x8000, 0x3c00, 0xbc00, 0x7c00, 0xfc00, 0x7c01, 0xfc01, 0x7e00, 0xfe00,
];
for kind in [12, 13] {
let (elements, bytes) = gguf::block_geometry(kind).unwrap();
for d in scales {
for dmin in scales {
for zero_fields in [false, true] {
let mut block = vec![0u8; bytes as usize];
block[..2].copy_from_slice(&d.to_le_bytes());
block[2..4].copy_from_slice(&dmin.to_le_bytes());
if !zero_fields {
for (position, byte) in block[4..].iter_mut().enumerate() {
*byte = (position * 29 + 17) as u8;
}
}
let mut oracle = vec![0.0; elements as usize];
ggml_bridge::decode_into(kind, &block, &mut oracle).unwrap();
let mut calls = 0;
let receipt =
visit(&mut Cursor::new(&block), 0, kind, bytes, |raw, derived| {
assert_eq!(raw, block);
assert_eq!(derived.len(), elements as usize * 4);
for (actual, reference) in
derived.as_chunks::<4>().0.iter().zip(&oracle)
{
let actual = f32::from_le_bytes(*actual);
if reference.is_nan() {
assert!(actual.is_nan());
} else {
assert_eq!(actual.to_bits(), reference.to_bits());
}
}
calls += 1;
Ok(())
})
.unwrap();
assert_eq!(calls, 1);
assert_eq!(receipt, elements * 4);
}
}
}
}
}
#[test]
fn q6_q2_streams_preserve_bounded_c_bytes_offsets_receipts_and_failure_semantics() {
let edges = [
0x0000u16, 0x8000, 0x0001, 0x83ff, 0x0400, 0x3555, 0xbc00, 0x7bff,
];
for kind in [14, 42] {
let (elements, bytes) = gguf::block_geometry(kind).unwrap();
let bytes = bytes as usize;
let per_chunk = SOURCE_CHUNK_BYTES / bytes;
let blocks = per_chunk + 17;
let prefix = 11;
let mut source = vec![0xa5; prefix];
for number in 0..blocks {
let mut block = vec![0u8; bytes];
for (position, byte) in block.iter_mut().enumerate() {
*byte = (number * 17 + position * 29) as u8;
}
let header = if kind == 14 { 208 } else { 0 };
block[header..header + 2]
.copy_from_slice(&edges[number % edges.len()].to_le_bytes());
source.extend_from_slice(&block);
}
let requested = blocks * bytes;
source.extend_from_slice(&[0x5a; 19]);
let mut cursor = Cursor::new(&source);
let mut consumed = 0;
let mut chunks = Vec::new();
let receipt = visit(
&mut cursor,
prefix as u64,
kind,
requested as u64,
|raw, derived| {
assert!(raw.len() <= SOURCE_CHUNK_BYTES);
assert_eq!(
raw,
&source[prefix + consumed..prefix + consumed + raw.len()]
);
let mut oracle = vec![0.0; raw.len() / bytes * elements as usize];
ggml_bridge::decode_into(kind, raw, &mut oracle).unwrap();
let expected: Vec<u8> = oracle
.iter()
.flat_map(|value| value.to_le_bytes())
.collect();
assert_eq!(derived, expected, "kind {kind}");
assert!(derived.len() <= per_chunk * elements as usize * 4);
chunks.push((raw.len(), derived.len()));
consumed += raw.len();
Ok(())
},
)
.unwrap();
assert_eq!(
chunks,
[
(per_chunk * bytes, per_chunk * elements as usize * 4),
(17 * bytes, 17 * elements as usize * 4)
]
);
assert_eq!(consumed, requested);
assert_eq!(receipt, blocks as u64 * elements * 4);
assert_eq!(cursor.position(), (prefix + requested) as u64);
for malformed in [0, 1, bytes - 1, bytes + 1] {
let mut cursor = Cursor::new(&source);
cursor.set_position(7);
let mut calls = 0;
assert!(
visit(
&mut cursor,
prefix as u64,
kind,
malformed as u64,
|_, _| {
calls += 1;
Ok(())
}
)
.is_err()
);
assert_eq!(calls, 0);
assert_eq!(cursor.position(), 7);
}
for delivered in [0, 1] {
let available = delivered * per_chunk * bytes + bytes - 1;
let required = delivered * per_chunk * bytes + bytes;
let mut calls = 0;
assert!(
visit(
&mut Cursor::new(&source[..prefix + available]),
prefix as u64,
kind,
required as u64,
|raw, derived| {
calls += 1;
assert_eq!(raw.len(), per_chunk * bytes);
assert_eq!(derived.len(), per_chunk * elements as usize * 4);
Ok(())
}
)
.is_err()
);
assert_eq!(calls, delivered);
}
for fail_on in [1, 2] {
let mut cursor = Cursor::new(&source);
let mut calls = 0;
let error = visit(
&mut cursor,
prefix as u64,
kind,
requested as u64,
|_, _| {
calls += 1;
if calls == fail_on {
Err("owned callback abort".into())
} else {
Ok(())
}
},
)
.unwrap_err();
assert_eq!(error, "owned callback abort");
assert_eq!(calls, fail_on);
assert_eq!(
cursor.position(),
(prefix
+ if fail_on == 1 {
per_chunk * bytes
} else {
requested
}) as u64
);
}
}
}
#[test]
fn q6_q2_streams_preserve_nonfinite_headers_and_zero_factors() {
for kind in [14, 42] {
let (elements, bytes) = gguf::block_geometry(kind).unwrap();
for bits in [
0x0000u16, 0x8000, 0x7c00, 0xfc00, 0x7c01, 0xfc01, 0x7e00, 0xfe00,
] {
for variant in 0..3 {
let mut block = vec![0u8; bytes as usize];
for (position, byte) in block.iter_mut().enumerate() {
*byte = (position * 29 + 17) as u8;
}
if kind == 14 {
if variant == 1 {
block[192..208].fill(0);
}
if variant == 2 {
block[..128].fill(0);
block[128..192].fill(0xaa);
}
} else if variant != 0 {
block[2..].fill(if variant == 1 { 0x55 } else { 0 });
}
let header = if kind == 14 { 208 } else { 0 };
block[header..header + 2].copy_from_slice(&bits.to_le_bytes());
let mut oracle = vec![0.0; elements as usize];
ggml_bridge::decode_into(kind, &block, &mut oracle).unwrap();
let mut calls = 0;
let receipt =
visit(&mut Cursor::new(&block), 0, kind, bytes, |raw, derived| {
assert_eq!(raw, block);
assert_eq!(derived.len(), elements as usize * 4);
for (actual, reference) in
derived.as_chunks::<4>().0.iter().zip(&oracle)
{
let actual = f32::from_le_bytes(*actual);
if reference.is_nan() {
assert!(actual.is_nan());
} else {
assert_eq!(actual.to_bits(), reference.to_bits());
}
}
calls += 1;
Ok(())
})
.unwrap();
assert_eq!(calls, 1);
assert_eq!(receipt, elements * 4);
}
}
}
}
#[test]
fn iq2s_iq3xxs_streams_preserve_bounded_c_bytes_offsets_receipts_and_failure_semantics() {
let edges = [
0x0000u16, 0x8000, 0x0001, 0x83ff, 0x0400, 0x3555, 0xbc00, 0x7bff,
];
for kind in [22, 18] {
let (elements, bytes) = gguf::block_geometry(kind).unwrap();
let bytes = bytes as usize;
let per_chunk = SOURCE_CHUNK_BYTES / bytes;
let blocks = per_chunk + 17;
let prefix = 11;
let mut source = vec![0xa5; prefix];
for number in 0..blocks {
let mut block = vec![0u8; bytes];
for (position, byte) in block.iter_mut().enumerate() {
*byte = (number * 17 + position * 29) as u8;
}
let header = 0;
block[header..header + 2]
.copy_from_slice(&edges[number % edges.len()].to_le_bytes());
source.extend_from_slice(&block);
}
let requested = blocks * bytes;
source.extend_from_slice(&[0x5a; 19]);
let mut cursor = Cursor::new(&source);
let mut consumed = 0;
let mut chunks = Vec::new();
let receipt = visit(
&mut cursor,
prefix as u64,
kind,
requested as u64,
|raw, derived| {
assert!(raw.len() <= SOURCE_CHUNK_BYTES);
assert_eq!(
raw,
&source[prefix + consumed..prefix + consumed + raw.len()]
);
let mut oracle = vec![0.0; raw.len() / bytes * elements as usize];
ggml_bridge::decode_into(kind, raw, &mut oracle).unwrap();
let expected: Vec<u8> = oracle
.iter()
.flat_map(|value| value.to_le_bytes())
.collect();
assert_eq!(derived, expected, "kind {kind}");
assert!(derived.len() <= per_chunk * elements as usize * 4);
chunks.push((raw.len(), derived.len()));
consumed += raw.len();
Ok(())
},
)
.unwrap();
assert_eq!(
chunks,
[
(per_chunk * bytes, per_chunk * elements as usize * 4),
(17 * bytes, 17 * elements as usize * 4)
]
);
assert_eq!(consumed, requested);
assert_eq!(receipt, blocks as u64 * elements * 4);
assert_eq!(cursor.position(), (prefix + requested) as u64);
for malformed in [0, 1, bytes - 1, bytes + 1] {
let mut cursor = Cursor::new(&source);
cursor.set_position(7);
let mut calls = 0;
assert!(
visit(
&mut cursor,
prefix as u64,
kind,
malformed as u64,
|_, _| {
calls += 1;
Ok(())
}
)
.is_err()
);
assert_eq!(calls, 0);
assert_eq!(cursor.position(), 7);
}
for delivered in [0, 1] {
let available = delivered * per_chunk * bytes + bytes - 1;
let required = delivered * per_chunk * bytes + bytes;
let mut calls = 0;
assert!(
visit(
&mut Cursor::new(&source[..prefix + available]),
prefix as u64,
kind,
required as u64,
|raw, derived| {
calls += 1;
assert_eq!(raw.len(), per_chunk * bytes);
assert_eq!(derived.len(), per_chunk * elements as usize * 4);
Ok(())
}
)
.is_err()
);
assert_eq!(calls, delivered);
}
for fail_on in [1, 2] {
let mut cursor = Cursor::new(&source);
let mut calls = 0;
let error = visit(
&mut cursor,
prefix as u64,
kind,
requested as u64,
|_, _| {
calls += 1;
if calls == fail_on {
Err("owned callback abort".into())
} else {
Ok(())
}
},
)
.unwrap_err();
assert_eq!(error, "owned callback abort");
assert_eq!(calls, fail_on);
assert_eq!(
cursor.position(),
(prefix
+ if fail_on == 1 {
per_chunk * bytes
} else {
requested
}) as u64
);
}
}
}
#[test]
fn iq2s_iq3xxs_streams_preserve_nonfinite_signed_zero_and_zero_packed_fields() {
for kind in [22, 18] {
let (elements, bytes) = gguf::block_geometry(kind).unwrap();
for bits in [
0x0000u16, 0x8000, 0x7c00, 0xfc00, 0x7c01, 0xfc01, 0x7e00, 0xfe00,
] {
for zero_fields in [false, true] {
let mut block = vec![0; bytes as usize];
if !zero_fields {
for (field, byte) in block[2..].iter_mut().enumerate() {
*byte = (field * 29 + 17) as u8;
}
}
block[..2].copy_from_slice(&bits.to_le_bytes());
let mut oracle = vec![0.0; elements as usize];
ggml_bridge::decode_into(kind, &block, &mut oracle).unwrap();
let mut calls = 0;
let receipt =
visit(&mut Cursor::new(&block), 0, kind, bytes, |raw, derived| {
assert_eq!(raw, block);
assert_eq!(derived.len(), elements as usize * 4);
for (actual, expected) in derived.as_chunks::<4>().0.iter().zip(&oracle)
{
let actual = f32::from_le_bytes(*actual);
if expected.is_nan() {
assert!(actual.is_nan());
} else {
assert_eq!(actual.to_bits(), expected.to_bits());
}
}
calls += 1;
Ok(())
})
.unwrap();
assert_eq!(calls, 1);
assert_eq!(receipt, elements * 4);
}
}
}
}
}
+1 -16
View File
@@ -322,22 +322,7 @@ fn f64_to_f16_bits(value: f64) -> u16 {
sign | ((half_exponent as u16) << 10) | ((rounded >> 42) as u16)
}
pub fn f16_bits_to_f32(bits: u16) -> f32 {
let sign = (u32::from(bits & 0x8000)) << 16;
let exponent = (bits >> 10) & 0x1f;
let mantissa = u32::from(bits & 0x03ff);
let result = match exponent {
0 if mantissa == 0 => sign,
0 => {
let leading = mantissa.leading_zeros() - 21;
let normalized = mantissa << leading;
sign | ((113 - leading) << 23) | ((normalized & 0x03ff) << 13)
}
31 => sign | 0x7f80_0000 | (mantissa << 13),
_ => sign | ((u32::from(exponent) + 112) << 23) | (mantissa << 13),
};
f32::from_bits(result)
}
pub use leleka_quant_core::f16_bits_to_f32;
#[cfg(test)]
mod tests {
+2 -3
View File
@@ -10,12 +10,11 @@ pub mod embedded_engine;
mod embedded_spec;
pub mod engine_probe;
pub mod ggml_bridge;
pub mod gguf;
pub use leleka_model_format::gguf;
pub mod gguf_f32_stream;
mod history_store;
mod immutable_directory;
pub mod iq3_s;
mod iq3s_grid;
pub use leleka_quant_core::iq3_s;
pub mod kar;
pub mod kar_codec;
pub mod kar_fixture;
+182 -34
View File
@@ -8,7 +8,9 @@ use std::sync::Mutex;
use std::sync::mpsc::{self, Receiver, RecvError, SendError, Sender};
/// Version understood by this crate and advertised in [`BackendIdentity`].
pub const BACKEND_API_VERSION: u16 = 1;
// Version 2 replaces independent capability axes with explicit model tuples.
// Version 1 identities must be refused rather than reinterpreted as version 2.
pub const BACKEND_API_VERSION: u16 = 2;
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct BackendIdentity {
@@ -42,7 +44,11 @@ impl ModelDescriptor {
("architecture", self.architecture.as_str()),
("weight_format", self.weight_format.as_str()),
] {
if value.trim().is_empty() {
if value.is_empty()
|| value
.chars()
.any(|ch| ch.is_whitespace() || ch.is_control())
{
return Err(ContractError::InvalidField(field));
}
}
@@ -56,27 +62,38 @@ impl ModelDescriptor {
}
}
/// One explicitly supported family, architecture and weight format combination.
///
/// Advertising two tuples does not advertise any combination of their fields.
/// An artifact digest is supplied by the descriptor and verified during loading.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct SupportedModelTuple {
pub family: String,
pub architecture: String,
pub weight_format: String,
}
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct BackendCapabilities {
pub supported_families: Vec<String>,
pub supported_architectures: Vec<String>,
pub supported_weight_formats: Vec<String>,
/// Exact supported combinations. An empty list advertises no model support.
pub supported_models: Vec<SupportedModelTuple>,
pub max_concurrent_generations: usize,
pub supports_cancellation: bool,
pub supports_tool_call_streaming: bool,
}
impl BackendCapabilities {
/// Refuse malformed descriptors and combinations not explicitly advertised.
///
/// This checks declared compatibility only; it does not verify artifact bytes
/// or admit memory, concurrency, hardware, or an experimental runtime mode.
pub fn supports(&self, model: &ModelDescriptor) -> bool {
self.supported_families.iter().any(|v| v == &model.family)
&& self
.supported_architectures
.iter()
.any(|v| v == &model.architecture)
&& self
.supported_weight_formats
.iter()
.any(|v| v == &model.weight_format)
model.validate().is_ok()
&& self.supported_models.iter().any(|supported| {
supported.family == model.family
&& supported.architecture == model.architecture
&& supported.weight_format == model.weight_format
})
}
}
@@ -179,8 +196,8 @@ impl fmt::Display for ContractError {
impl std::error::Error for ContractError {}
/// Implemented by runtime backends. A backend must not claim a model family or
/// format until it can load and serve it with the declared semantics.
/// Implemented by runtime backends. A backend must not advertise a model tuple
/// until it can load and serve that combination with the declared semantics.
pub trait Backend: Send {
fn identity(&self) -> BackendIdentity;
fn capabilities(&self) -> BackendCapabilities;
@@ -321,10 +338,10 @@ mod tests {
fn model() -> ModelDescriptor {
ModelDescriptor {
family: "qwen3_moe".into(),
architecture: "qwen3_moe_v1".into(),
family: "fixture_alpha".into(),
architecture: "fixture_arch_a".into(),
artifact_digest: format!("sha256:{}", "a".repeat(64)),
weight_format: "gguf:iq3_s".into(),
weight_format: "fixture:format_a".into(),
}
}
@@ -339,20 +356,148 @@ mod tests {
);
}
#[test]
fn capabilities_match_family_architecture_and_format_together() {
let capabilities = BackendCapabilities {
supported_families: vec!["qwen3_moe".into()],
supported_architectures: vec!["qwen3_moe_v1".into()],
supported_weight_formats: vec!["gguf:iq3_s".into()],
fn capabilities() -> BackendCapabilities {
BackendCapabilities {
supported_models: vec![
SupportedModelTuple {
family: "fixture_alpha".into(),
architecture: "fixture_arch_a".into(),
weight_format: "fixture:format_a".into(),
},
SupportedModelTuple {
family: "fixture_beta".into(),
architecture: "fixture_arch_b".into(),
weight_format: "fixture:format_b".into(),
},
],
max_concurrent_generations: 2,
supports_cancellation: true,
supports_tool_call_streaming: true,
}
}
#[test]
fn capabilities_admit_only_explicit_tuples_not_their_cartesian_product() {
let capabilities = capabilities();
let mut admitted = 0;
for family in ["fixture_alpha", "fixture_beta"] {
for architecture in ["fixture_arch_a", "fixture_arch_b"] {
for weight_format in ["fixture:format_a", "fixture:format_b"] {
let descriptor = ModelDescriptor {
family: family.into(),
architecture: architecture.into(),
weight_format: weight_format.into(),
..model()
};
let expected = matches!(
(family, architecture, weight_format),
("fixture_alpha", "fixture_arch_a", "fixture:format_a")
| ("fixture_beta", "fixture_arch_b", "fixture:format_b")
);
let actual = capabilities.supports(&descriptor);
assert_eq!(actual, expected, "{descriptor:?}");
admitted += usize::from(actual);
}
}
}
assert_eq!(admitted, 2);
for unknown in [
ModelDescriptor {
family: "fixture_unknown".into(),
..model()
},
ModelDescriptor {
architecture: "fixture_arch_unknown".into(),
..model()
},
ModelDescriptor {
weight_format: "fixture:unknown".into(),
..model()
},
] {
assert!(!capabilities.supports(&unknown));
}
}
#[test]
fn empty_capabilities_advertise_no_models() {
assert!(!BackendCapabilities::default().supports(&model()));
let empty = BackendCapabilities {
supported_models: Vec::new(),
..capabilities()
};
assert!(capabilities.supports(&model()));
let mut unsupported = model();
unsupported.weight_format = "gguf:unknown".into();
assert!(!capabilities.supports(&unsupported));
assert!(!empty.supports(&model()));
}
#[test]
fn invalid_digests_are_refused_even_for_an_explicit_tuple() {
for digest in [
String::new(),
"sha256:abc".into(),
format!("sha256:{}", "a".repeat(63)),
format!("sha256:{}", "a".repeat(65)),
format!("sha256:{}", "z".repeat(64)),
format!("SHA256:{}", "a".repeat(64)),
format!("sha256:{} ", "a".repeat(64)),
] {
let descriptor = ModelDescriptor {
artifact_digest: digest,
..model()
};
assert_eq!(
descriptor.validate(),
Err(ContractError::InvalidField("artifact_digest"))
);
assert!(!capabilities().supports(&descriptor));
}
}
#[test]
fn malformed_fields_cannot_be_admitted_even_if_a_backend_lists_them() {
for invalid in [
"",
" ",
"fixture alpha",
" fixture",
"fixture ",
"fixture\n",
"fixture\0",
] {
for field in ["family", "architecture", "weight_format"] {
let mut descriptor = model();
let mut capabilities = capabilities();
let supported = &mut capabilities.supported_models[0];
match field {
"family" => {
descriptor.family = invalid.into();
supported.family = invalid.into();
}
"architecture" => {
descriptor.architecture = invalid.into();
supported.architecture = invalid.into();
}
"weight_format" => {
descriptor.weight_format = invalid.into();
supported.weight_format = invalid.into();
}
_ => unreachable!(),
}
assert_eq!(
descriptor.validate(),
Err(ContractError::InvalidField(field))
);
assert!(!capabilities.supports(&descriptor), "{field}: {invalid:?}");
}
}
}
#[test]
fn supported_tuple_does_not_pin_or_verify_artifact_bytes() {
let descriptor = ModelDescriptor {
artifact_digest: format!("sha256:{}", "b".repeat(64)),
..model()
};
assert!(capabilities().supports(&descriptor));
}
#[test]
@@ -363,11 +508,14 @@ mod tests {
api_version: BACKEND_API_VERSION,
};
assert!(current.supports_current_api());
let older = BackendIdentity {
api_version: 0,
..current
};
assert!(!older.supports_current_api());
assert_eq!(BACKEND_API_VERSION, 2);
for api_version in [0, 1, 3, u16::MAX] {
let incompatible = BackendIdentity {
api_version,
..current.clone()
};
assert!(!incompatible.supports_current_api());
}
}
#[test]
+23
View File
@@ -0,0 +1,23 @@
[package]
name = "leleka-cuda-driver"
version = "0.1.0"
description = "Opt-in bounded CUDA Driver context and byte-buffer foundation"
edition.workspace = true
license.workspace = true
rust-version.workspace = true
[features]
default = []
cuda-driver = []
[target.'cfg(all(target_os = "linux", target_pointer_width = "64"))'.dependencies]
libc = "=0.2.190"
# The workspace unsafe forbid remains unchanged. Only private ffi.rs may allow
# unsafe code; all other modules deny it, and unsafe operations require blocks.
[lints.rust]
unsafe_code = "deny"
unsafe_op_in_unsafe_fn = "deny"
[lints.clippy]
all = "warn"
+445
View File
@@ -0,0 +1,445 @@
//! Private audited C ABI boundary. No host or device pointers are exported.
//! Behavior references: CUDA Driver API archive 13.0.1 context management,
//! memory management, and api-sync-behavior.html. Exact create/pointer ABI was
//! checked against the official pinned CUDA 13.0.88 cuda.h (line 25633 declares
//! cuCtxCreate_v2 with THREE arguments; line 90 maps today's cuCtxCreate alias
//! to cuCtxCreate_v4; line 274 defines the 64-bit CUdeviceptr). This header is
//! verification evidence only and is not a production dependency. Do not infer
//! a fixed export ABI from the newer alias.
use crate::{Error, Result};
#[derive(Clone, Copy, PartialEq, Eq)]
pub(crate) struct ContextHandle(usize);
#[derive(Clone, Copy, PartialEq, Eq)]
pub(crate) struct BufferHandle(u64);
#[derive(Clone, Copy)]
pub(crate) struct ModuleHandle(usize);
#[derive(Clone, Copy)]
pub(crate) struct FunctionHandle(usize);
struct ArgumentStorage {
addresses: [u64; 3],
count: u32,
parameters: [*mut std::ffi::c_void; 4],
}
// Convert the allocation to raw ownership BEFORE forming field pointers.
// A later move or mutable borrow of a Box must not retag/invalidate pointers
// derived from it (std::boxed unsafe-code considerations). This owner moves
// only a NonNull value; it never creates a reference to the pointed-to storage.
// Drop reconstructs the Box once, after completion or before any launch attempt.
pub(crate) struct LaunchArguments {
storage: std::ptr::NonNull<ArgumentStorage>,
}
impl LaunchArguments {
pub(crate) fn new(a: BufferHandle, b: BufferHandle, output: BufferHandle, count: u32) -> Self {
let storage = Box::into_raw(Box::new(ArgumentStorage {
addresses: [a.0, b.0, output.0],
count,
parameters: [std::ptr::null_mut(); 4],
}));
// SAFETY: the non-null allocation is now uniquely raw-owned and stable.
// Initialize all self-referential pointers without borrowing/moving a
// Box or creating new references to the entire allocation.
unsafe {
for i in 0..3 {
(*storage).parameters[i] = (&raw mut (*storage).addresses[i]).cast();
}
(*storage).parameters[3] = (&raw mut (*storage).count).cast();
}
Self {
storage: std::ptr::NonNull::new(storage).expect("Box allocation is non-null"),
}
}
}
impl Drop for LaunchArguments {
fn drop(&mut self) {
// SAFETY: exactly one owner reconstructs this Box. The caller only
// permits Drop before a launch or after successful synchronization;
// ambiguous completion forgets this owner and retains the allocation.
unsafe {
drop(Box::from_raw(self.storage.as_ptr()));
}
}
}
#[cfg(all(
feature = "cuda-driver",
target_os = "linux",
target_pointer_width = "64"
))]
mod enabled {
use super::*;
use libc::{c_int, c_uint, c_void};
type CuResult = c_int;
type CuDevice = c_int;
type CuContext = *mut c_void;
type CuDevicePtr = u64;
type Init = unsafe extern "C" fn(c_uint) -> CuResult;
type DriverGetVersion = unsafe extern "C" fn(*mut c_int) -> CuResult;
type DeviceGet = unsafe extern "C" fn(*mut CuDevice, c_int) -> CuResult;
type ContextCreateV2 = unsafe extern "C" fn(*mut CuContext, c_uint, CuDevice) -> CuResult;
type ContextDestroyV2 = unsafe extern "C" fn(CuContext) -> CuResult;
type ContextPushCurrentV2 = unsafe extern "C" fn(CuContext) -> CuResult;
type ContextPopCurrentV2 = unsafe extern "C" fn(*mut CuContext) -> CuResult;
type ContextSynchronize = unsafe extern "C" fn() -> CuResult;
type MemAllocV2 = unsafe extern "C" fn(*mut CuDevicePtr, usize) -> CuResult;
type MemFreeV2 = unsafe extern "C" fn(CuDevicePtr) -> CuResult;
type MemcpyHtoDV2 = unsafe extern "C" fn(CuDevicePtr, *const c_void, usize) -> CuResult;
type ModuleLoadData = unsafe extern "C" fn(*mut *mut c_void, *const c_void) -> CuResult;
type ModuleGetFunction =
unsafe extern "C" fn(*mut *mut c_void, *mut c_void, *const libc::c_char) -> CuResult;
type ModuleUnload = unsafe extern "C" fn(*mut c_void) -> CuResult;
type LaunchKernel = unsafe extern "C" fn(
*mut c_void,
c_uint,
c_uint,
c_uint,
c_uint,
c_uint,
c_uint,
c_uint,
*mut c_void,
*mut *mut c_void,
*mut *mut c_void,
) -> CuResult;
static FIXED_PTX: &[u8] = concat!(include_str!("vector_add.ptx"), "\0").as_bytes();
type MemcpyDtoHV2 = unsafe extern "C" fn(*mut c_void, CuDevicePtr, usize) -> CuResult;
struct Library(*mut c_void);
impl Drop for Library {
fn drop(&mut self) {
// SAFETY: this is the successful dlopen handle, owned exactly once.
// All loaded functions live in Api alongside this Library. Driver
// owner borrows retain Api through all resource operations/cleanup.
unsafe {
libc::dlclose(self.0);
}
}
}
pub(crate) struct Api {
_library: Library,
init: Init,
version: DriverGetVersion,
device: DeviceGet,
create: ContextCreateV2,
destroy: ContextDestroyV2,
push: ContextPushCurrentV2,
pop: ContextPopCurrentV2,
synchronize: ContextSynchronize,
allocate: MemAllocV2,
free: MemFreeV2,
copy_from: MemcpyHtoDV2,
copy_to: MemcpyDtoHV2,
load_module: ModuleLoadData,
get_function: ModuleGetFunction,
unload_module: ModuleUnload,
launch_kernel: LaunchKernel,
}
fn check(operation: &'static str, code: CuResult) -> Result<()> {
if code == 0 {
Ok(())
} else {
Err(Error::Driver { operation, code })
}
}
impl Api {
pub(crate) fn load() -> Result<Self> {
// SAFETY: a fixed NUL-terminated soname, no caller-provided paths;
// immediate local symbol resolution, with null checked before use.
let handle = unsafe {
libc::dlopen(c"libcuda.so.1".as_ptr(), libc::RTLD_NOW | libc::RTLD_LOCAL)
};
if handle.is_null() {
return Err(Error::LibraryUnavailable);
}
let library = Library(handle);
macro_rules! symbol {
($name:literal, $ty:ty) => {{
// SAFETY: valid owned library handle and static C name.
let address = unsafe { libc::dlsym(library.0, $name.as_ptr()) };
if address.is_null() {
return Err(Error::MissingSymbol(
$name.to_str().expect("static ASCII symbol"),
));
}
// SAFETY: the fixed ABI name is paired with its exact
// documented signature. Linux64 supports dlsym function
// addresses; no generic or caller-selected reinterpretation.
unsafe { std::mem::transmute::<*mut c_void, $ty>(address) }
}};
}
let init = symbol!(c"cuInit", Init);
let version = symbol!(c"cuDriverGetVersion", DriverGetVersion);
let device = symbol!(c"cuDeviceGet", DeviceGet);
let create = symbol!(c"cuCtxCreate_v2", ContextCreateV2);
let destroy = symbol!(c"cuCtxDestroy_v2", ContextDestroyV2);
let push = symbol!(c"cuCtxPushCurrent_v2", ContextPushCurrentV2);
let pop = symbol!(c"cuCtxPopCurrent_v2", ContextPopCurrentV2);
let synchronize = symbol!(c"cuCtxSynchronize", ContextSynchronize);
let allocate = symbol!(c"cuMemAlloc_v2", MemAllocV2);
let free = symbol!(c"cuMemFree_v2", MemFreeV2);
let copy_from = symbol!(c"cuMemcpyHtoD_v2", MemcpyHtoDV2);
let copy_to = symbol!(c"cuMemcpyDtoH_v2", MemcpyDtoHV2);
let load_module = symbol!(c"cuModuleLoadData", ModuleLoadData);
let get_function = symbol!(c"cuModuleGetFunction", ModuleGetFunction);
let unload_module = symbol!(c"cuModuleUnload", ModuleUnload);
let launch_kernel = symbol!(c"cuLaunchKernel", LaunchKernel);
Ok(Self {
_library: library,
init,
version,
device,
create,
destroy,
push,
pop,
synchronize,
allocate,
free,
copy_from,
copy_to,
load_module,
get_function,
unload_module,
launch_kernel,
})
}
pub(crate) fn load_fixed_module(&self) -> Result<ModuleHandle> {
let mut module = std::ptr::null_mut();
// SAFETY: current owned context, writable module out pointer, and
// static trusted NUL-terminated PTX remains live indefinitely.
check("cuModuleLoadData", unsafe {
(self.load_module)(&mut module, FIXED_PTX.as_ptr().cast())
})?;
if module.is_null() {
return Err(Error::InvalidDriverValue("cuModuleLoadData"));
}
Ok(ModuleHandle(module as usize))
}
pub(crate) fn fixed_function(&self, module: ModuleHandle) -> Result<FunctionHandle> {
let mut function = std::ptr::null_mut();
// SAFETY: live private module in current owner context; fixed C
// entry name; valid writable opaque function output.
check("cuModuleGetFunction", unsafe {
(self.get_function)(
&mut function,
module.0 as *mut c_void,
c"leleka_vector_add_f32".as_ptr(),
)
})?;
if function.is_null() {
return Err(Error::InvalidDriverValue("cuModuleGetFunction"));
}
Ok(FunctionHandle(function as usize))
}
pub(crate) fn unload(&self, module: ModuleHandle) -> Result<()> {
// SAFETY: usable handle was consumed before this single attempt,
// current context owns it, and all prior work completed. It is
// never retried or reused even when unload reports failure.
check("cuModuleUnload", unsafe {
(self.unload_module)(module.0 as *mut c_void)
})
}
pub(crate) fn launch(
&self,
function: FunctionHandle,
grid: u32,
arguments: &mut LaunchArguments,
) -> Result<()> {
// SAFETY: fixed live function/owner context; checked exact shapes,
// nonaliasing output and grid; six fixed dimensions + sharedBytes;
// null stream/extra. Four pointer entries address initialized typed
// boxed values, NOT device addresses interpreted as host pointers.
// Caller keeps the entire box/table alive through mandatory sync,
// and retains it permanently on ambiguous completion.
check("cuLaunchKernel", unsafe {
(self.launch_kernel)(
function.0 as *mut c_void,
grid,
1,
1,
128,
1,
1,
0,
std::ptr::null_mut(),
(&raw mut (*arguments.storage.as_ptr()).parameters).cast(),
std::ptr::null_mut(),
)
})
}
pub(crate) fn init(&self) -> Result<()> {
// SAFETY: resolved exact ABI, mandated zero flags, live library.
check("cuInit", unsafe { (self.init)(0) })
}
pub(crate) fn version(&self) -> Result<i32> {
let mut value = 0;
// SAFETY: resolved ABI and valid initialized writable C int.
check("cuDriverGetVersion", unsafe { (self.version)(&mut value) })?;
Ok(value)
}
pub(crate) fn device(&self, ordinal: i32) -> Result<i32> {
let mut value = 0;
// SAFETY: resolved ABI, valid out pointer, ordinal prevalidated.
check("cuDeviceGet", unsafe { (self.device)(&mut value, ordinal) })?;
Ok(value)
}
pub(crate) fn create(&self, device: i32) -> Result<ContextHandle> {
let mut context = std::ptr::null_mut();
// SAFETY: exact legacy v2 THREE-argument ABI, zero flags, a device
// returned by cuDeviceGet, and a valid writable context pointer.
check("cuCtxCreate_v2", unsafe {
(self.create)(&mut context, 0, device)
})?;
if context.is_null() {
return Err(Error::InvalidDriverValue("cuCtxCreate_v2"));
}
Ok(ContextHandle(context as usize))
}
pub(crate) fn destroy(&self, context: ContextHandle) -> Result<()> {
// SAFETY: this handle was created by this Api and remains owned by
// the caller context. No buffer can outlive the borrow owner. This
// API explicitly supports destroying a non-current owned context.
check("cuCtxDestroy_v2", unsafe {
(self.destroy)(context.0 as CuContext)
})
}
pub(crate) fn push(&self, context: ContextHandle) -> Result<()> {
// SAFETY: live private context, same creating thread (Rc owners).
check("cuCtxPushCurrent_v2", unsafe {
(self.push)(context.0 as CuContext)
})
}
pub(crate) fn pop(&self) -> Result<ContextHandle> {
let mut context = std::ptr::null_mut();
// SAFETY: called after successful create/push on the same thread,
// valid out pointer. Callers verify identity and poison on failure.
check("cuCtxPopCurrent_v2", unsafe { (self.pop)(&mut context) })?;
Ok(ContextHandle(context as usize))
}
pub(crate) fn synchronize(&self) -> Result<()> {
// SAFETY: caller guard makes its live owned context current.
check("cuCtxSynchronize", unsafe { (self.synchronize)() })
}
pub(crate) fn allocate(&self, bytes: usize) -> Result<BufferHandle> {
let mut ptr = 0;
// SAFETY: current-context guard; nonzero, bounded size validated
// before mutation; valid u64 CUdeviceptr output on Linux64.
check("cuMemAlloc_v2", unsafe { (self.allocate)(&mut ptr, bytes) })?;
if ptr == 0 {
return Err(Error::InvalidDriverValue("cuMemAlloc_v2"));
}
Ok(BufferHandle(ptr))
}
pub(crate) fn free(&self, buffer: BufferHandle) -> Result<()> {
// SAFETY: uniquely owned allocation, owner context is current.
// Poisoned/uncertain contexts never enter this operation.
check("cuMemFree_v2", unsafe { (self.free)(buffer.0) })
}
pub(crate) fn copy_from(&self, buffer: BufferHandle, owned: &[u8]) -> Result<()> {
// SAFETY: buffer owner is current, exact allocation size checked,
// and the caller owns this staging allocation. It synchronizes on
// both success/error and leaks staging on ambiguous completion, so
// the pointer stays valid even if the call retains it after return.
check("cuMemcpyHtoD_v2", unsafe {
(self.copy_from)(buffer.0, owned.as_ptr().cast(), owned.len())
})
}
pub(crate) fn copy_to(&self, buffer: BufferHandle, owned: &mut [u8]) -> Result<()> {
// SAFETY: valid owned writable staging of exactly the allocation
// size; current owner context; caller synchronizes or leaks as
// above. No borrowed output is passed directly to the driver.
check("cuMemcpyDtoH_v2", unsafe {
(self.copy_to)(owned.as_mut_ptr().cast(), buffer.0, owned.len())
})
}
}
}
#[cfg(all(
feature = "cuda-driver",
target_os = "linux",
target_pointer_width = "64"
))]
pub(crate) use enabled::Api;
#[cfg(not(all(
feature = "cuda-driver",
target_os = "linux",
target_pointer_width = "64"
)))]
pub(crate) struct Api;
#[cfg(not(all(
feature = "cuda-driver",
target_os = "linux",
target_pointer_width = "64"
)))]
impl Api {
pub(crate) fn load() -> Result<Self> {
if cfg!(feature = "cuda-driver") {
Err(Error::UnsupportedPlatform)
} else {
Err(Error::Disabled)
}
}
pub(crate) fn load_fixed_module(&self) -> Result<ModuleHandle> {
Err(Error::UnsupportedPlatform)
}
pub(crate) fn fixed_function(&self, module: ModuleHandle) -> Result<FunctionHandle> {
let _ = module.0;
Err(Error::UnsupportedPlatform)
}
pub(crate) fn unload(&self, module: ModuleHandle) -> Result<()> {
let _ = module.0;
Err(Error::UnsupportedPlatform)
}
pub(crate) fn launch(
&self,
function: FunctionHandle,
_: u32,
arguments: &mut LaunchArguments,
) -> Result<()> {
let _ = (function.0, arguments.storage);
Err(Error::UnsupportedPlatform)
}
// These methods cannot be reached through the safe API: load always fails.
pub(crate) fn init(&self) -> Result<()> {
Err(Error::UnsupportedPlatform)
}
pub(crate) fn version(&self) -> Result<i32> {
Err(Error::UnsupportedPlatform)
}
pub(crate) fn device(&self, _: i32) -> Result<i32> {
Err(Error::UnsupportedPlatform)
}
pub(crate) fn create(&self, _: i32) -> Result<ContextHandle> {
Err(Error::UnsupportedPlatform)
}
pub(crate) fn destroy(&self, _: ContextHandle) -> Result<()> {
Err(Error::UnsupportedPlatform)
}
pub(crate) fn push(&self, _: ContextHandle) -> Result<()> {
Err(Error::UnsupportedPlatform)
}
pub(crate) fn pop(&self) -> Result<ContextHandle> {
Err(Error::UnsupportedPlatform)
}
pub(crate) fn synchronize(&self) -> Result<()> {
Err(Error::UnsupportedPlatform)
}
pub(crate) fn allocate(&self, _: usize) -> Result<BufferHandle> {
Err(Error::UnsupportedPlatform)
}
pub(crate) fn free(&self, _: BufferHandle) -> Result<()> {
Err(Error::UnsupportedPlatform)
}
pub(crate) fn copy_from(&self, _: BufferHandle, _: &[u8]) -> Result<()> {
Err(Error::UnsupportedPlatform)
}
pub(crate) fn copy_to(&self, _: BufferHandle, _: &mut [u8]) -> Result<()> {
Err(Error::UnsupportedPlatform)
}
}
+541
View File
@@ -0,0 +1,541 @@
//! Opt-in CUDA Driver context and bounded byte buffers, without inference.
//!
//! Enable `cuda-driver` and explicitly call [`Driver::load`] on Linux 64-bit.
//! Resources are confined to their creating thread and borrow their owners.
//! Copies stage owned bytes and synchronize before publishing host output.
//! A failed synchronization poisons the context and intentionally leaks the
//! bounded staging allocation: completion cannot safely be inferred from an
//! error, including a subsequent context-destruction result.
#![deny(unsafe_code)]
#![deny(unsafe_op_in_unsafe_fn)]
use std::{cell::Cell, fmt, marker::PhantomData, rc::Rc};
#[allow(unsafe_code)]
mod ffi;
/// Errors retain CUDA operation names/codes and any subsequent cleanup errors.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Error {
Disabled,
UnsupportedPlatform,
LibraryUnavailable,
MissingSymbol(&'static str),
InvalidDriverValue(&'static str),
Driver {
operation: &'static str,
code: i32,
},
ContextMismatch,
InvalidVectorShape,
OutputAliasesInput,
InvalidOrdinal,
InvalidSize,
BudgetExceeded,
ShapeMismatch {
expected: usize,
actual: usize,
},
HostAllocation,
ContextPoisoned,
UnexpectedContext,
Multiple {
primary: Box<Error>,
secondary: Box<Error>,
},
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Disabled => f.write_str("CUDA Driver feature is disabled"),
Self::UnsupportedPlatform => {
f.write_str("CUDA Driver requires Linux with 64-bit pointers")
}
Self::LibraryUnavailable => f.write_str("cannot load libcuda.so.1"),
Self::MissingSymbol(symbol) => write!(f, "missing CUDA Driver symbol {symbol}"),
Self::InvalidDriverValue(operation) => {
write!(f, "{operation} returned an invalid handle on success")
}
Self::Driver { operation, code } => {
write!(f, "{operation} failed with CUDA code {code}")
}
Self::ContextMismatch => {
f.write_str("vector buffers must belong to this exact context")
}
Self::InvalidVectorShape => {
f.write_str("vector shape must be nonempty f32 bytes with a bounded u32 count/grid")
}
Self::OutputAliasesInput => f.write_str("vector output must not alias an input"),
Self::InvalidOrdinal => f.write_str("device ordinal must be nonnegative"),
Self::InvalidSize => f.write_str("byte size must be nonzero and fit isize"),
Self::BudgetExceeded => f.write_str("allocation exceeds context byte budget"),
Self::ShapeMismatch { expected, actual } => {
write!(f, "byte shape mismatch: expected {expected}, got {actual}")
}
Self::HostAllocation => f.write_str("cannot allocate owned host staging memory"),
Self::ContextPoisoned => {
f.write_str("context is poisoned after uncertain completion or restoration")
}
Self::UnexpectedContext => f.write_str("CUDA pop returned a different context"),
Self::Multiple { primary, secondary } => {
write!(f, "{primary}; subsequent error: {secondary}")
}
}
}
}
impl std::error::Error for Error {}
pub type Result<T> = std::result::Result<T, Error>;
fn combine<T>(primary: Result<T>, secondary: Result<()>) -> Result<T> {
match (primary, secondary) {
(Ok(value), Ok(())) => Ok(value),
(Err(error), Ok(())) | (Ok(_), Err(error)) => Err(error),
(Err(primary), Err(secondary)) => Err(Error::Multiple {
primary: Box::new(primary),
secondary: Box::new(secondary),
}),
}
}
fn valid_size(bytes: usize) -> Result<()> {
if bytes == 0 || bytes > isize::MAX as usize {
Err(Error::InvalidSize)
} else {
Ok(())
}
}
/// A loaded fixed ABI. No resources can be sent or shared between threads.
pub struct Driver {
api: Rc<ffi::Api>,
version: i32,
}
impl Driver {
/// Resolve the entire fixed ABI before initializing CUDA.
pub fn load() -> Result<Self> {
let api = Rc::new(ffi::Api::load()?);
api.init()?;
let version = api.version()?;
Ok(Self { api, version })
}
pub fn version(&self) -> i32 {
self.version
}
pub fn device(&self, ordinal: i32) -> Result<Device<'_>> {
if ordinal < 0 {
return Err(Error::InvalidOrdinal);
}
Ok(Device {
driver: self,
handle: self.api.device(ordinal)?,
})
}
}
/// A device selected through its owner driver, without a public raw handle.
pub struct Device<'driver> {
driver: &'driver Driver,
handle: i32,
}
impl<'driver> Device<'driver> {
pub fn create_context(&self, byte_budget: usize) -> Result<Context<'driver>> {
valid_size(byte_budget)?;
let api = &self.driver.api;
let handle = api.create(self.handle)?;
let restore = api.pop().and_then(|popped| {
if popped == handle {
Ok(())
} else {
Err(Error::UnexpectedContext)
}
});
if let Err(error) = restore {
let cleanup = api.destroy(handle);
if cleanup.is_err() {
// The driver may still own a live context; keep its ABI loaded.
std::mem::forget(Rc::clone(api));
}
return combine(Err(error), cleanup);
}
Ok(Context {
driver: self.driver,
handle: Some(handle),
budget: byte_budget,
allocated: Cell::new(0),
poisoned: Cell::new(false),
kernel: Cell::new(None),
})
}
}
/// A private context with a budget for actual live allocations.
pub struct Context<'driver> {
driver: &'driver Driver,
handle: Option<ffi::ContextHandle>,
budget: usize,
allocated: Cell<usize>,
poisoned: Cell<bool>,
kernel: Cell<Option<FixedKernel>>,
}
#[derive(Clone, Copy)]
struct FixedKernel {
module: ffi::ModuleHandle,
function: ffi::FunctionHandle,
}
// Wider integer arithmetic also covers the final partial block at u32::MAX.
fn vector_shape(bytes: usize) -> Result<(u32, u32)> {
if valid_size(bytes).is_err() || !bytes.is_multiple_of(4) {
return Err(Error::InvalidVectorShape);
}
let count = u32::try_from(bytes / 4).map_err(|_| Error::InvalidVectorShape)?;
let grid = u64::from(count)
.checked_add(127)
.ok_or(Error::InvalidVectorShape)?
/ 128;
if grid == 0 || grid > i32::MAX as u64 {
return Err(Error::InvalidVectorShape);
}
Ok((
count,
u32::try_from(grid).map_err(|_| Error::InvalidVectorShape)?,
))
}
impl Context<'_> {
pub fn budget_bytes(&self) -> usize {
self.budget
}
/// Failed frees remain charged until context destruction.
pub fn allocated_bytes(&self) -> usize {
self.allocated.get()
}
fn enter(&self) -> Result<CurrentGuard<'_, '_>> {
if self.poisoned.get() {
return Err(Error::ContextPoisoned);
}
let handle = self.handle.ok_or(Error::ContextPoisoned)?;
self.driver.api.push(handle)?;
Ok(CurrentGuard {
context: self,
active: true,
})
}
pub fn allocate(&self, bytes: usize) -> Result<DeviceBuffer<'_>> {
valid_size(bytes)?;
let total = self
.allocated
.get()
.checked_add(bytes)
.ok_or(Error::BudgetExceeded)?;
if total > self.budget {
return Err(Error::BudgetExceeded);
}
let guard = self.enter()?;
let allocation = self.driver.api.allocate(bytes);
if allocation.is_ok() {
self.allocated.set(total);
}
// A successful allocation whose pop fails stays charged. The poisoned
// context owns that allocation until destruction, so no unguarded free.
let handle = combine(allocation, guard.finish())?;
Ok(DeviceBuffer {
context: self,
handle: Some(handle),
bytes,
_thread: PhantomData,
})
}
pub fn synchronize(&self) -> Result<()> {
let guard = self.enter()?;
let sync = self.driver.api.synchronize();
if sync.is_err() {
self.poisoned.set(true);
}
combine(sync, guard.finish())
}
/// Add two exact f32 byte vectors with the fixed trusted kernel. The
/// output is usable as a computed vector only after a successful return.
pub fn vector_add_f32(
&self,
a: &DeviceBuffer<'_>,
b: &DeviceBuffer<'_>,
output: &mut DeviceBuffer<'_>,
) -> Result<()> {
if self.poisoned.get() {
return Err(Error::ContextPoisoned);
}
if !std::ptr::eq(self, a.context)
|| !std::ptr::eq(self, b.context)
|| !std::ptr::eq(self, output.context)
{
return Err(Error::ContextMismatch);
}
let (count, grid) = vector_shape(a.bytes)?;
if a.bytes != b.bytes || a.bytes != output.bytes {
return Err(Error::InvalidVectorShape);
}
let a_handle = a.handle.ok_or(Error::ContextPoisoned)?;
let b_handle = b.handle.ok_or(Error::ContextPoisoned)?;
let out_handle = output.handle.ok_or(Error::ContextPoisoned)?;
if a_handle == out_handle || b_handle == out_handle {
return Err(Error::OutputAliasesInput);
}
// Establish the owned parameter addresses after their stable heap
// placement, before any native mutation. No caller host data is used.
let mut arguments = ffi::LaunchArguments::new(a_handle, b_handle, out_handle, count);
let guard = self.enter()?;
let kernel = match self.fixed_kernel() {
Ok(kernel) => kernel,
Err(error) => return combine(Err(error), guard.finish()),
};
let launch = self
.driver
.api
.launch(kernel.function, grid, &mut arguments);
// A launch error can describe earlier asynchronous work. Synchronize
// after EVERY attempted launch; preserve launch/sync/pop error order.
let sync = self.driver.api.synchronize();
if sync.is_err() {
self.poisoned.set(true);
// Both boxed scalars and their pointer table may still be read.
// One poisoned context admits no further launch or explicit frees.
std::mem::forget(arguments);
}
combine(combine(launch, sync), guard.finish())
}
fn fixed_kernel(&self) -> Result<FixedKernel> {
if let Some(kernel) = self.kernel.get() {
return Ok(kernel);
}
let module = self.driver.api.load_fixed_module()?;
match self.driver.api.fixed_function(module) {
Ok(function) => {
let kernel = FixedKernel { module, function };
self.kernel.set(Some(kernel));
Ok(kernel)
}
Err(error) => {
// Local usable handle consumed by this single unload attempt;
// no cache publishes a partial module or retries failed unload.
let cleanup = self.driver.api.unload(module);
if cleanup.is_err() {
self.poisoned.set(true);
}
combine(Err(error), cleanup)
}
}
}
fn unload_kernel(&self) -> Result<()> {
// Consume BEFORE attempting unload; even an error can invalidate it.
let Some(kernel) = self.kernel.take() else {
return Ok(());
};
if self.poisoned.get() {
return Ok(());
}
let guard = match self.enter() {
Ok(guard) => guard,
Err(error) => {
self.poisoned.set(true);
return Err(error);
}
};
let unload = self.driver.api.unload(kernel.module);
if unload.is_err() {
self.poisoned.set(true);
}
combine(unload, guard.finish())
}
/// Consume the context and report destruction failure. Borrows prevent
/// closing a context while a device buffer can still be used.
pub fn close(mut self) -> Result<()> {
self.destroy()
}
fn destroy(&mut self) -> Result<()> {
let unload = self.unload_kernel();
if let Some(handle) = self.handle.take() {
// cuCtxDestroy accepts an owned non-current context. Pushing here
// would add a stack entry for a handle invalidated by destruction.
let result = self.driver.api.destroy(handle);
if result.is_err() {
std::mem::forget(Rc::clone(&self.driver.api));
}
if result.is_ok() {
self.allocated.set(0);
}
combine(unload, result)
} else {
unload
}
}
}
impl Drop for Context<'_> {
fn drop(&mut self) {
let _ = self.destroy();
}
}
/// Push/pop balance with fallible explicit finish and nonpanicking fallback.
struct CurrentGuard<'context, 'driver> {
context: &'context Context<'driver>,
active: bool,
}
impl CurrentGuard<'_, '_> {
fn finish(mut self) -> Result<()> {
self.restore()
}
fn restore(&mut self) -> Result<()> {
if !self.active {
return Ok(());
}
self.active = false;
let result = self.context.driver.api.pop().and_then(|popped| {
if Some(popped) == self.context.handle {
Ok(())
} else {
Err(Error::UnexpectedContext)
}
});
if result.is_err() {
self.context.poisoned.set(true);
}
result
}
}
impl Drop for CurrentGuard<'_, '_> {
fn drop(&mut self) {
let _ = self.restore();
}
}
/// An exact nonempty byte allocation borrowing its owning context.
pub struct DeviceBuffer<'context> {
context: &'context Context<'context>,
handle: Option<ffi::BufferHandle>,
bytes: usize,
_thread: PhantomData<Rc<()>>,
}
impl DeviceBuffer<'_> {
pub fn len(&self) -> usize {
self.bytes
}
pub fn is_empty(&self) -> bool {
false
}
fn staging(&self, actual: usize) -> Result<Vec<u8>> {
if actual != self.bytes {
return Err(Error::ShapeMismatch {
expected: self.bytes,
actual,
});
}
if self.context.poisoned.get() {
return Err(Error::ContextPoisoned);
}
let mut staging = Vec::new();
staging
.try_reserve_exact(self.bytes)
.map_err(|_| Error::HostAllocation)?;
staging.resize(self.bytes, 0);
Ok(staging)
}
pub fn copy_from(&mut self, input: &[u8]) -> Result<()> {
let mut staging = self.staging(input.len())?;
staging.copy_from_slice(input);
self.copy_staged(staging, false).map(|_| ())
}
pub fn copy_to(&self, output: &mut [u8]) -> Result<()> {
let staging = self.staging(output.len())?;
let staging = self.copy_staged(staging, true)?;
output.copy_from_slice(&staging);
Ok(())
}
fn copy_staged(&self, mut staging: Vec<u8>, to_host: bool) -> Result<Vec<u8>> {
let handle = self.handle.ok_or(Error::ContextPoisoned)?;
let guard = self.context.enter()?;
let copy = if to_host {
self.context.driver.api.copy_to(handle, &mut staging)
} else {
self.context.driver.api.copy_from(handle, &staging)
};
// Even copy errors can report earlier asynchronous work. Synchronize
// on every attempted copy before considering the staging reclaimable.
let sync = self.context.driver.api.synchronize();
if sync.is_err() {
self.context.poisoned.set(true);
// CUDA may still reference these owned host bytes. A poisoned
// context admits no further copy, limiting this leak to one buffer
// (at most its context budget), regardless of caller lifetimes.
std::mem::forget(staging);
return combine(combine(copy, sync), guard.finish()).map(|()| Vec::new());
}
combine(copy, guard.finish())?;
Ok(staging)
}
pub fn release(mut self) -> Result<()> {
self.free()
}
fn free(&mut self) -> Result<()> {
let Some(handle) = self.handle.take() else {
return Ok(());
};
let guard = self.context.enter()?;
let free = self.context.driver.api.free(handle);
if free.is_ok() {
self.context
.allocated
.set(self.context.allocated.get() - self.bytes);
}
combine(free, guard.finish())
}
}
impl Drop for DeviceBuffer<'_> {
fn drop(&mut self) {
let _ = self.free();
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn sizes_and_error_composition() {
assert_eq!(valid_size(0), Err(Error::InvalidSize));
assert_eq!(valid_size(usize::MAX), Err(Error::InvalidSize));
assert_eq!(valid_size(1), Ok(()));
assert_eq!(
combine::<()>(Err(Error::InvalidSize), Err(Error::UnexpectedContext)),
Err(Error::Multiple {
primary: Box::new(Error::InvalidSize),
secondary: Box::new(Error::UnexpectedContext)
})
);
}
#[test]
fn vector_count_geometry_boundaries() {
for bytes in [0, 1, 3, 5, usize::MAX] {
assert!(vector_shape(bytes).is_err());
}
for n in [1u32, 127, 128, 129, 1025, u32::MAX] {
let bytes = usize::try_from(u64::from(n) * 4).unwrap();
assert_eq!(
vector_shape(bytes),
Ok((n, u32::try_from(u64::from(n).div_ceil(128)).unwrap()))
);
}
assert!(vector_shape((u32::MAX as usize + 1) * 4).is_err());
}
#[cfg(not(feature = "cuda-driver"))]
#[test]
fn default_load_rejects_before_driver_use() {
assert!(matches!(Driver::load(), Err(Error::Disabled)));
}
#[cfg(all(
feature = "cuda-driver",
not(all(target_os = "linux", target_pointer_width = "64"))
))]
#[test]
fn unsupported_load_rejects_before_driver_use() {
assert!(matches!(Driver::load(), Err(Error::UnsupportedPlatform)));
}
}
+41
View File
@@ -0,0 +1,41 @@
// Trusted fixed operation; byte image is embedded with a final NUL by ffi.rs.
.version 7.0
.target sm_75
.address_size 64
.visible .entry leleka_vector_add_f32(
.param .u64 input_a,
.param .u64 input_b,
.param .u64 output,
.param .u32 count
)
{
.reg .pred %p;
.reg .b32 %r<3>;
.reg .b64 %rd<8>;
.reg .f32 %f<3>;
ld.param.u64 %rd0, [input_a];
ld.param.u64 %rd1, [input_b];
ld.param.u64 %rd2, [output];
ld.param.u32 %r2, [count];
mov.u32 %r0, %ctaid.x;
mov.u32 %r1, %tid.x;
mul.wide.u32 %rd3, %r0, 128;
cvt.u64.u32 %rd4, %r1;
add.u64 %rd3, %rd3, %rd4;
cvt.u64.u32 %rd4, %r2;
setp.ge.u64 %p, %rd3, %rd4;
@%p bra DONE;
shl.b64 %rd4, %rd3, 2;
add.u64 %rd5, %rd0, %rd4;
add.u64 %rd6, %rd1, %rd4;
add.u64 %rd7, %rd2, %rd4;
ld.global.f32 %f0, [%rd5];
ld.global.f32 %f1, [%rd6];
add.rn.f32 %f2, %f0, %f1;
st.global.f32 [%rd7], %f2;
DONE:
ret;
}
+178
View File
@@ -0,0 +1,178 @@
/* Synthetic CPU-only CUDA Driver ABI fixture. No NVIDIA headers/devices/library. */
#include <stdint.h>
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef void *CUcontext;
typedef uint64_t CUdeviceptr;
typedef int CUresult;
static CUcontext current=(void *)(uintptr_t)0x11;
static CUcontext stack[64];
static size_t depth;
static CUcontext contexts[16];
static size_t next_context;
static int context_live(CUcontext ctx){for(size_t i=0;i<16;i++)if(contexts[i]==ctx&&ctx)return 1;return 0;}
static int live_context;
static unsigned failed_mask;
static struct {void *raw,*ptr;size_t size;CUcontext owner;} buffers[16];
static struct {void *handle,*function;CUcontext owner;} modules[16];
static size_t next_module;
static void **pending_args;
static uint64_t pending_values[3];
static uint32_t pending_n;
static CUcontext pending_owner;
static const void *pending_host;
static void *pending_device;
static size_t pending_bytes;
static void *pending_destination;
static unsigned calls[16];
static const char *names[]={"init","version","device","create","destroy","push","pop","sync","alloc","free","htod","dtoh","load","lookup","unload","launch"};
static size_t charged(void) {size_t result=0;for(size_t i=0;i<16;i++)result+=buffers[i].size;return result;}
static void trace(const char *stage,int code,size_t bytes) {
const char *path=getenv("MOCK_CUDA_TRACE");if(!path)abort();
FILE *f=fopen(path,"a");if(!f)abort();
fprintf(f,"%s %d %lu %zu %d %zu %zu\n",stage,code,(unsigned long)(uintptr_t)current,depth,live_context,charged(),bytes);
fclose(f);
}
static int fault(int op) {
calls[op]++;
const char *value=getenv("MOCK_CUDA_FAIL");
if(!value||(failed_mask&(1u<<op)))return 0;
char requested[128],expected[64];snprintf(requested,sizeof(requested),"%s",value);
snprintf(expected,sizeof(expected),"%s:%u",names[op],calls[op]);
for(char *token=strtok(requested,",");token;token=strtok(NULL,",")) {
if(strcmp(token,names[op])==0||strcmp(token,expected)==0) {
failed_mask|=1u<<op;trace(names[op],700,0);return 700;
}
}
return 0;
}
static void check_canary(size_t i) {
unsigned char *raw=buffers[i].raw;
if(!raw)return;
for(size_t j=0;j<8;j++)if(raw[j]!=0xa5||raw[8+buffers[i].size+j]!=0xa5){trace("canary",1,i);abort();}
}
static void complete_pending(void) {
if(pending_args){
for(size_t i=0;i<3;i++)if(*(uint64_t *)pending_args[i]!=pending_values[i])abort();
if(*(uint32_t *)pending_args[3]!=pending_n)abort();
float *a=(float *)(uintptr_t)pending_values[0],*b=(float *)(uintptr_t)pending_values[1],*out=(float *)(uintptr_t)pending_values[2];
for(uint32_t i=0;i<pending_n;i++)out[i]=a[i]+b[i];
trace("pending_launch",0,pending_n);
pending_args=NULL;pending_n=0;
}
for(size_t i=0;i<16;i++)check_canary(i);
if(pending_host&&pending_device){
size_t sum=0;for(size_t i=0;i<pending_bytes;i++)sum+=((const unsigned char *)pending_host)[i];
const unsigned char expected[8]={0,1,2,3,255,128,85,170};
int exact=pending_bytes==sizeof(expected)&&memcmp(pending_host,expected,sizeof(expected))==0;
trace("pending_htod",exact||getenv("MOCK_CUDA_VECTOR")?0:1,sum);memcpy(pending_device,pending_host,pending_bytes);
}
if(pending_destination&&pending_device){trace("pending_dtoh",0,pending_bytes);memcpy(pending_destination,pending_device,pending_bytes);}
pending_host=NULL;pending_device=NULL;pending_destination=NULL;pending_bytes=0;
}
static int require_context(void) {return context_live(current)?0:201;}
static void *lookup(CUdeviceptr ptr,size_t count) {
for(size_t i=0;i<16;i++)if((CUdeviceptr)(uintptr_t)buffers[i].ptr==ptr&&count==buffers[i].size&&buffers[i].owner==current)return buffers[i].ptr;
return NULL;
}
CUresult cuInit(unsigned flags) {if(flags)return 1;if(fault(0))return 700;trace("init",0,0);return 0;}
CUresult cuDriverGetVersion(int *version) {if(fault(1))return 700;*version=13000;trace("version",0,0);return 0;}
CUresult cuDeviceGet(int *device,int ordinal) {if(fault(2))return 700;if(ordinal!=0)return 101;*device=0;trace("device",0,0);return 0;}
CUresult cuCtxCreate_v2(CUcontext *result,unsigned flags,int device) {
if(flags||device)return 1;if(fault(3))return 700;
if(next_context>=16)return 2;
CUcontext owned=(void *)(uintptr_t)(0x22+next_context);contexts[next_context++]=owned;
stack[depth++]=current;current=owned;live_context++;*result=owned;trace("create",0,0);return 0;
}
CUresult cuCtxDestroy_v2(CUcontext ctx) {
if(fault(4))return 700;if(!context_live(ctx))return 201;
/* Read retained pending source before disposing it: a delayed HtoD host borrow. */
if(pending_args&&pending_owner!=ctx)abort();complete_pending();
for(size_t i=0;i<16;i++)if(buffers[i].owner==ctx){free(buffers[i].raw);memset(&buffers[i],0,sizeof(buffers[i]));}
for(size_t i=0;i<16;i++)if(modules[i].owner==ctx)memset(&modules[i],0,sizeof(modules[i]));
for(size_t i=0;i<16;i++)if(contexts[i]==ctx)contexts[i]=NULL;
live_context--;if(current==ctx)current=depth?stack[--depth]:(void *)(uintptr_t)0x11;
trace("destroy",0,0);return 0;
}
CUresult cuCtxPushCurrent_v2(CUcontext ctx) {
if(fault(5))return 700;if(!context_live(ctx)||depth>=64)return 201;
stack[depth++]=current;current=ctx;trace("push",0,0);return 0;
}
CUresult cuCtxPopCurrent_v2(CUcontext *result) {
if(fault(6))return 700;if(!depth)return 201;
*result=current;current=stack[--depth];
const char *wrong=getenv("MOCK_CUDA_WRONG_POP");
if(wrong&&calls[6]==(unsigned)strtoul(wrong,NULL,10))*result=(void *)(uintptr_t)0x99;
trace("pop",0,0);return 0;
}
CUresult cuCtxSynchronize(void) {
if(fault(7))return 700;if(require_context())return 201;
complete_pending();trace("sync",0,0);return 0;
}
CUresult cuMemAlloc_v2(CUdeviceptr *ptr,size_t bytes) {
if(fault(8))return 700;if(require_context()||!bytes||bytes>16384)return 201;
for(size_t i=0;i<16;i++)if(!buffers[i].ptr){buffers[i].raw=calloc(1,bytes+16);if(!buffers[i].raw)return 2;memset(buffers[i].raw,0xa5,8);memset((unsigned char*)buffers[i].raw+8+bytes,0xa5,8);buffers[i].ptr=(unsigned char*)buffers[i].raw+8;buffers[i].size=bytes;buffers[i].owner=current;*ptr=(CUdeviceptr)(uintptr_t)buffers[i].ptr;trace("alloc",0,bytes);return 0;}
return 2;
}
CUresult cuMemFree_v2(CUdeviceptr ptr) {
if(fault(9))return 700;if(require_context())return 201;
for(size_t i=0;i<16;i++)if((CUdeviceptr)(uintptr_t)buffers[i].ptr==ptr){if(pending_args){trace("unsafe_pending_free",0,0);abort();}check_canary(i);if(pending_device==buffers[i].ptr){trace("unsafe_pending_free",0,0);pending_device=NULL;pending_host=NULL;pending_destination=NULL;pending_bytes=0;}free(buffers[i].raw);memset(&buffers[i],0,sizeof(buffers[i]));trace("free",0,0);return 0;}
return 1;
}
CUresult cuMemcpyHtoD_v2(CUdeviceptr ptr,const void *host,size_t bytes) {
if(fault(10))return 700;if(require_context()||!lookup(ptr,bytes))return 201;
/* Copy is deliberately delayed to explicit synchronization. */
pending_host=host;pending_device=lookup(ptr,bytes);pending_bytes=bytes;trace("htod",0,bytes);return 0;
}
#ifndef MOCK_MISSING_DTOH
CUresult cuMemcpyDtoH_v2(void *host,CUdeviceptr ptr,size_t bytes) {
if(fault(11))return 700;if(require_context()||!lookup(ptr,bytes))return 201;
pending_destination=host;pending_device=lookup(ptr,bytes);pending_bytes=bytes;trace("dtoh",0,bytes);return 0;
}
#endif
/* Independent fixed vector ABI fixture. Arithmetic here is a CPU reference;
it neither interprets nor executes PTX. */
CUresult cuModuleLoadData(void **result,const void *image) {
if(fault(12))return 700;if(require_context())return 201;
const char *ptx=image;
if(!ptx||!strstr(ptx,".version 7.0")||!strstr(ptx,".target sm_75")||!strstr(ptx,".address_size 64")||!strstr(ptx,".entry leleka_vector_add_f32")||!strstr(ptx,"add.rn.f32"))return 218;
if(getenv("MOCK_CUDA_NULL_LOAD")){*result=NULL;trace("load_null",0,0);return 0;}
if(next_module>=16)return 2;
size_t slot=next_module++;modules[slot].handle=(void *)(uintptr_t)(0x100+slot);
modules[slot].function=(void *)(uintptr_t)(0x200+slot);modules[slot].owner=current;
*result=modules[slot].handle;trace("load",0,0);return 0;
}
CUresult cuModuleGetFunction(void **result,void *module,const char *name) {
if(fault(13))return 700;if(require_context()||strcmp(name,"leleka_vector_add_f32"))return 201;
if(getenv("MOCK_CUDA_NULL_FUNCTION")){*result=NULL;trace("lookup_null",0,0);return 0;}
for(size_t i=0;i<16;i++)if(modules[i].handle==module&&modules[i].owner==current){*result=modules[i].function;trace("lookup",0,0);return 0;}
return 201;
}
CUresult cuModuleUnload(void *module) {
if(pending_args){trace("unsafe_pending_unload",0,0);abort();}
if(fault(14))return 700;if(require_context())return 201;
for(size_t i=0;i<16;i++)if(modules[i].handle==module&&modules[i].owner==current){memset(&modules[i],0,sizeof(modules[i]));trace("unload",0,0);return 0;}
return 201;
}
CUresult cuLaunchKernel(void *function,unsigned gx,unsigned gy,unsigned gz,unsigned bx,unsigned by,unsigned bz,unsigned shared,void *stream,void **params,void **extra) {
if(require_context()||!params||extra||stream||shared||gy!=1||gz!=1||bx!=128||by!=1||bz!=1)return 201;
int found=0;for(size_t i=0;i<16;i++)if(modules[i].function==function&&modules[i].owner==current)found=1;
if(!found)return 201;
uintptr_t stack_address=(uintptr_t)&found;
uintptr_t table_address=(uintptr_t)params;
if(table_address>stack_address-1048576&&table_address<stack_address+1048576){trace("stack_arguments",1,0);return 1;}
uint32_t n=*(uint32_t *)params[3];
if(!n||gx!=(n+127ull)/128)return 1;
for(size_t i=0;i<3;i++){
uintptr_t arg=(uintptr_t)params[i];if(arg>stack_address-1048576&&arg<stack_address+1048576)return 1;
uint64_t value=*(uint64_t *)params[i];if(!lookup(value,(size_t)n*4))return 1;pending_values[i]=value;
}
if(pending_values[2]==pending_values[0]||pending_values[2]==pending_values[1])return 1;
pending_args=params;pending_n=n;pending_owner=current;
trace("geometry",0,gx);trace("arguments",0,n);
if(fault(15))return 700;trace("launch",0,n);return 0;
}
+717
View File
@@ -0,0 +1,717 @@
#![cfg(all(target_os = "linux", target_pointer_width = "64"))]
use leleka_cuda_driver::Driver;
use std::{fs, path::PathBuf, process::Command};
#[derive(Debug)]
struct Row {
stage: String,
code: i32,
current: usize,
depth: usize,
live: usize,
charged: usize,
bytes: usize,
}
fn trace() -> Vec<Row> {
let path = std::env::var("MOCK_CUDA_TRACE").unwrap();
fs::read_to_string(path)
.unwrap_or_default()
.lines()
.map(|line| {
let v: Vec<_> = line.split_whitespace().collect();
assert_eq!(v.len(), 7);
Row {
stage: v[0].into(),
code: v[1].parse().unwrap(),
current: v[2].parse().unwrap(),
depth: v[3].parse().unwrap(),
live: v[4].parse().unwrap(),
charged: v[5].parse().unwrap(),
bytes: v[6].parse().unwrap(),
}
})
.collect()
}
fn valid_context_trace(rows: &[Row]) {
for row in rows.iter().filter(|row| row.code == 0) {
if ["alloc", "htod", "dtoh", "sync", "free"].contains(&row.stage.as_str()) {
assert_eq!(row.current, 0x22, "{row:?}");
assert_eq!(row.depth, 1, "{row:?}");
assert_eq!(row.live, 1);
}
if row.stage == "pop" {
assert_eq!(row.current, 0x11, "{row:?}");
assert_eq!(row.depth, 0);
}
}
}
fn cuda_errors(error: &leleka_cuda_driver::Error) -> Vec<(&'static str, i32)> {
match error {
leleka_cuda_driver::Error::Driver { operation, code } => vec![(*operation, *code)],
leleka_cuda_driver::Error::Multiple { primary, secondary } => {
let mut errors = cuda_errors(primary);
errors.extend(cuda_errors(secondary));
errors
}
_ => Vec::new(),
}
}
#[test]
#[ignore = "requires isolated CPU-only fake libcuda harness"]
fn isolated_cpu_elf_matrix() {
assert_eq!(
std::env::var("LELEKA_CUDA_MOCK_HARNESS").as_deref(),
Ok("1"),
"run only the isolated synthetic ELF harness"
);
let root = PathBuf::from(std::env::var("LELEKA_CUDA_MOCK_ROOT").unwrap());
assert!(root.is_absolute());
let scenarios = [
"success",
"bounds",
"missing",
"missing_cuInit",
"missing_cuDriverGetVersion",
"missing_cuDeviceGet",
"missing_cuCtxCreate_v2",
"missing_cuCtxDestroy_v2",
"missing_cuCtxPushCurrent_v2",
"missing_cuCtxPopCurrent_v2",
"missing_cuCtxSynchronize",
"missing_cuMemAlloc_v2",
"missing_cuMemFree_v2",
"missing_cuMemcpyHtoD_v2",
"init",
"version",
"device",
"create",
"create_pop",
"push",
"pop",
"wrong_pop",
"operation_wrong_pop",
"context_sync",
"alloc",
"htod",
"dtoh",
"sync_htod",
"sync_dtoh",
"htod_sync",
"dtoh_sync",
"free",
"destroy",
"missing_cuModuleLoadData",
"missing_cuModuleGetFunction",
"missing_cuModuleUnload",
"missing_cuLaunchKernel",
"vector_1",
"vector_127",
"vector_128",
"vector_129",
"vector_1025",
"vector_cache",
"vector_contexts",
"vector_bounds",
"vector_same_input",
"vector_load",
"vector_lookup",
"vector_null_load",
"vector_null_function",
"vector_launch",
"vector_sync",
"vector_launch_sync",
"vector_launch_sync_pop",
"vector_pop",
"vector_wrong_pop",
"vector_unload",
"vector_lookup_unload",
"vector_close_pop",
"vector_close_destroy",
"vector_push",
];
for scenario in scenarios {
let path = root.join(format!("trace-{scenario}"));
let mut command = Command::new(std::env::current_exe().unwrap());
command
.args(["--exact", "fixture_child", "--ignored", "--nocapture"])
.env("LELEKA_CUDA_CASE", scenario)
.env("MOCK_CUDA_TRACE", &path)
.env_remove("MOCK_CUDA_FAIL")
.env_remove("MOCK_CUDA_WRONG_POP")
.env_remove("MOCK_CUDA_NULL_LOAD")
.env_remove("MOCK_CUDA_NULL_FUNCTION")
.env_remove("MOCK_CUDA_VECTOR");
if scenario.starts_with("vector_") {
command.env("MOCK_CUDA_VECTOR", "1");
}
command.env(
"LD_LIBRARY_PATH",
root.join(if scenario.starts_with("missing") {
scenario
} else {
"complete"
}),
);
let failure = match scenario {
"vector_load" => Some("load"),
"vector_lookup" => Some("lookup"),
"vector_launch" => Some("launch"),
"vector_sync" => Some("sync:3"),
"vector_launch_sync" => Some("launch,sync:3"),
"vector_launch_sync_pop" => Some("launch,sync:3,pop:7"),
"vector_pop" => Some("pop:7"),
"vector_unload" => Some("unload"),
"vector_lookup_unload" => Some("lookup,unload"),
"vector_close_pop" => Some("pop:14"),
"vector_close_destroy" => Some("destroy"),
"vector_push" => Some("push:6"),
other if other.starts_with("vector_") => None,
"create_pop" => Some("pop"),
"pop" => Some("pop:2"),
"sync_htod" => Some("sync"),
"sync_dtoh" => Some("sync:2"),
"htod_sync" => Some("htod,sync"),
"dtoh_sync" => Some("dtoh,sync:2"),
"success" | "bounds" | "missing" | "wrong_pop" | "operation_wrong_pop" => None,
"context_sync" => Some("sync"),
other => Some(other),
};
if let Some(failure) = failure {
command.env("MOCK_CUDA_FAIL", failure);
}
if ["wrong_pop", "operation_wrong_pop"].contains(&scenario) {
command.env(
"MOCK_CUDA_WRONG_POP",
if scenario == "wrong_pop" { "1" } else { "2" },
);
}
if scenario == "vector_wrong_pop" {
command.env("MOCK_CUDA_WRONG_POP", "7");
}
if scenario == "vector_null_load" {
command.env("MOCK_CUDA_NULL_LOAD", "1");
}
if scenario == "vector_null_function" {
command.env("MOCK_CUDA_NULL_FUNCTION", "1");
}
let output = command.output().unwrap();
assert!(
output.status.success(),
"scenario {scenario}\n{}\n{}",
String::from_utf8_lossy(&output.stdout),
String::from_utf8_lossy(&output.stderr)
);
println!("synthetic CPU ELF scenario {scenario}: PASS");
}
}
#[test]
#[ignore = "invoked only by isolated_cpu_elf_matrix with synthetic library"]
fn fixture_child() {
assert_eq!(std::env::var("LELEKA_CUDA_MOCK_HARNESS").unwrap(), "1");
let case = std::env::var("LELEKA_CUDA_CASE").unwrap();
if case.starts_with("vector_") {
vector_child(&case);
return;
}
if case.starts_with("missing") || ["init", "version"].contains(&case.as_str()) {
let error = Driver::load()
.err()
.expect("missing ABI/init/version must fail");
if case.starts_with("missing") {
let symbol = case.strip_prefix("missing_").unwrap_or("cuMemcpyDtoH_v2");
assert!(
matches!(error,leleka_cuda_driver::Error::MissingSymbol(actual) if actual==symbol)
);
}
let rows = trace();
if case.starts_with("missing") {
assert!(rows.is_empty(), "symbol resolution must precede init");
} else {
assert!(rows.iter().any(|row| row.stage == case && row.code == 700));
}
return;
}
let driver = Driver::load().unwrap();
assert_eq!(driver.version(), 13000);
if case == "device" {
assert!(driver.device(0).is_err());
return;
}
assert!(driver.device(-1).is_err());
let device = driver.device(0).unwrap();
if case == "bounds" {
let before = trace().len();
assert!(device.create_context(0).is_err());
assert!(device.create_context(usize::MAX).is_err());
assert_eq!(trace().len(), before);
}
if ["create", "create_pop", "wrong_pop"].contains(&case.as_str()) {
assert!(device.create_context(16).is_err());
let rows = trace();
if case == "create" {
assert!(!rows.iter().any(|row| row.stage == "destroy"));
} else {
assert!(
rows.iter()
.any(|row| row.stage == "destroy" && row.code == 0)
);
}
return;
}
let context = device.create_context(16).unwrap();
assert_eq!(context.budget_bytes(), 16);
assert_eq!(context.allocated_bytes(), 0);
assert_eq!(trace().last().unwrap().current, 0x11);
if ["alloc", "push", "pop", "operation_wrong_pop"].contains(&case.as_str()) {
assert!(context.allocate(8).is_err());
if ["pop", "operation_wrong_pop"].contains(&case.as_str()) {
let before = trace().len();
assert!(context.allocate(8).is_err());
assert!(context.synchronize().is_err());
assert_eq!(trace().len(), before, "poison must reject native work");
} else {
assert_eq!(context.allocated_bytes(), 0);
}
drop(context);
valid_context_trace(&trace());
return;
}
if case == "context_sync" {
assert!(context.synchronize().is_err());
drop(context);
valid_context_trace(&trace());
return;
}
if case == "bounds" {
let before = trace().len();
assert!(context.allocate(0).is_err());
assert!(context.allocate(17).is_err());
assert!(context.allocate(usize::MAX).is_err());
assert_eq!(trace().len(), before);
}
let mut buffer = context.allocate(8).unwrap();
assert_eq!(buffer.len(), 8);
assert_eq!(context.allocated_bytes(), 8);
if case == "bounds" {
let before = trace().len();
assert!(context.allocate(9).is_err());
assert!(buffer.copy_from(&[1; 7]).is_err());
assert!(buffer.copy_from(&[1; 9]).is_err());
let mut short = [0x99; 7];
assert!(buffer.copy_to(&mut short).is_err());
assert_eq!(short, [0x99; 7]);
assert_eq!(
trace().len(),
before,
"bounds reject before driver mutation"
);
}
let mut input = [0, 1, 2, 3, 0xff, 0x80, 0x55, 0xaa];
let mut output = [0x99; 8];
if ["htod", "sync_htod", "htod_sync"].contains(&case.as_str()) {
let error = buffer.copy_from(&input).unwrap_err();
let expected = match case.as_str() {
"htod" => vec![("cuMemcpyHtoD_v2", 700)],
"sync_htod" => vec![("cuCtxSynchronize", 700)],
_ => vec![("cuMemcpyHtoD_v2", 700), ("cuCtxSynchronize", 700)],
};
assert_eq!(
cuda_errors(&error),
expected,
"copy/completion errors retained in order"
);
input.fill(0);
std::hint::black_box(input);
if ["sync_htod", "htod_sync"].contains(&case.as_str()) {
let before = trace().len();
assert!(context.allocate(1).is_err());
assert_eq!(trace().len(), before);
}
} else {
buffer.copy_from(&input).unwrap();
if ["dtoh", "sync_dtoh", "dtoh_sync"].contains(&case.as_str()) {
let error = buffer.copy_to(&mut output).unwrap_err();
let expected = match case.as_str() {
"dtoh" => vec![("cuMemcpyDtoH_v2", 700)],
"sync_dtoh" => vec![("cuCtxSynchronize", 700)],
_ => vec![("cuMemcpyDtoH_v2", 700), ("cuCtxSynchronize", 700)],
};
assert_eq!(
cuda_errors(&error),
expected,
"copy/completion errors retained in order"
);
assert_eq!(output, [0x99; 8], "failed copy must not publish staging");
if ["sync_dtoh", "dtoh_sync"].contains(&case.as_str()) {
let before = trace().len();
assert!(context.synchronize().is_err());
assert_eq!(trace().len(), before);
}
} else {
buffer.copy_to(&mut output).unwrap();
assert_eq!(output, input);
}
}
if case == "free" {
let error = buffer.release().unwrap_err();
assert_eq!(cuda_errors(&error), vec![("cuMemFree_v2", 700)]);
assert_eq!(context.allocated_bytes(), 8);
} else if ["sync_htod", "sync_dtoh", "htod_sync", "dtoh_sync"].contains(&case.as_str()) {
drop(buffer);
} else {
buffer.release().unwrap();
assert_eq!(context.allocated_bytes(), 0);
}
if case == "destroy" {
let error = context.close().unwrap_err();
assert_eq!(cuda_errors(&error), vec![("cuCtxDestroy_v2", 700)]);
} else if ["sync_htod", "sync_dtoh", "htod_sync", "dtoh_sync"].contains(&case.as_str()) {
drop(context);
} else {
context.close().unwrap();
}
let rows = trace();
if case == "sync_htod" {
assert!(
rows.iter()
.any(|row| row.stage == "pending_htod" && row.code == 0 && row.bytes == 644),
"delayed source retained original owned bytes after caller input changed"
);
}
if case == "sync_dtoh" {
assert!(
rows.iter()
.any(|row| row.stage == "pending_dtoh" && row.bytes == 8)
);
assert_eq!(
output, [0x99; 8],
"completion after failed sync must target retained staging, never caller output"
);
}
if ["htod", "dtoh", "htod_sync", "dtoh_sync"].contains(&case.as_str()) {
let copy = if case.starts_with("htod") {
"htod"
} else {
"dtoh"
};
let index = rows
.iter()
.position(|row| row.stage == copy && row.code == 700)
.unwrap();
assert_eq!(
rows[index + 1].stage,
"sync",
"sync must be attempted after copy failure"
);
assert_eq!(
rows[index + 1].code,
if case.ends_with("_sync") { 700 } else { 0 }
);
}
valid_context_trace(&rows);
assert!(
rows.iter().any(|row| row.stage == "destroy"),
"owned context cleanup attempted"
);
assert!(
!rows.iter().any(|row| row.stage == "unsafe_pending_free"),
"pending copy device freed early"
);
for row in rows
.iter()
.filter(|row| row.stage == "alloc" && row.code == 0)
{
assert_eq!(row.bytes, 8);
assert_eq!(row.charged, 8);
}
if !["destroy"].contains(&case.as_str()) {
let destroyed = rows
.iter()
.rev()
.find(|row| row.stage == "destroy" && row.code == 0)
.unwrap();
assert_eq!(destroyed.live, 0);
assert_eq!(destroyed.charged, 0);
assert_eq!(destroyed.current, 0x11);
}
}
// Expected values and geometry are derived from FR-VADD-1..5 and the NVIDIA
// launch ABI, independent of the wrapper/PTX implementation. CPU mock results
// are host dataflow/ownership evidence only.
fn vector_child(case: &str) {
use leleka_cuda_driver::Error;
let driver = Driver::load().unwrap();
let device = driver.device(0).unwrap();
let count = case
.strip_prefix("vector_")
.unwrap()
.parse::<usize>()
.unwrap_or(129);
let bytes = count * 4;
let context = device.create_context(bytes * 4 + 16).unwrap();
let mut a = context.allocate(bytes).unwrap();
let mut b = context.allocate(bytes).unwrap();
let mut out = context.allocate(bytes).unwrap();
let av: Vec<f32> = (0..count)
.map(|i| (i as i32 % 31 - 15) as f32 * 0.5)
.collect();
let bv: Vec<f32> = (0..count)
.map(|i| (i as i32 % 23 - 11) as f32 * 0.25)
.collect();
let encode = |v: &[f32]| {
v.iter()
.flat_map(|value| value.to_ne_bytes())
.collect::<Vec<u8>>()
};
a.copy_from(&encode(&av)).unwrap();
b.copy_from(&encode(&bv)).unwrap();
if case == "vector_bounds" {
let foreign = device.create_context(bytes * 3).unwrap();
let foreign_input = foreign.allocate(bytes).unwrap();
let short = context.allocate(4).unwrap();
let odd = context.allocate(3).unwrap();
let mut odd_out = context.allocate(3).unwrap();
let before = trace().len();
assert!(matches!(
context.vector_add_f32(&foreign_input, &b, &mut out),
Err(Error::ContextMismatch)
));
assert!(context.vector_add_f32(&a, &short, &mut out).is_err());
assert!(context.vector_add_f32(&odd, &odd, &mut odd_out).is_err());
assert_eq!(trace().len(), before, "validation before ABI mutation");
drop((foreign_input, short, odd, odd_out));
foreign.close().unwrap();
}
let result = if case == "vector_same_input" {
context.vector_add_f32(&a, &a, &mut out)
} else {
context.vector_add_f32(&a, &b, &mut out)
};
let execution_failure = [
"vector_load",
"vector_lookup",
"vector_null_load",
"vector_null_function",
"vector_launch",
"vector_sync",
"vector_launch_sync",
"vector_launch_sync_pop",
"vector_pop",
"vector_wrong_pop",
"vector_lookup_unload",
"vector_push",
]
.contains(&case);
if execution_failure {
let error = result.unwrap_err();
let expected = match case {
"vector_load" => vec![("cuModuleLoadData", 700)],
"vector_lookup" => vec![("cuModuleGetFunction", 700)],
"vector_lookup_unload" => vec![("cuModuleGetFunction", 700), ("cuModuleUnload", 700)],
"vector_launch" => vec![("cuLaunchKernel", 700)],
"vector_sync" => vec![("cuCtxSynchronize", 700)],
"vector_launch_sync" => vec![("cuLaunchKernel", 700), ("cuCtxSynchronize", 700)],
"vector_launch_sync_pop" => vec![
("cuLaunchKernel", 700),
("cuCtxSynchronize", 700),
("cuCtxPopCurrent_v2", 700),
],
"vector_pop" => vec![("cuCtxPopCurrent_v2", 700)],
"vector_push" => vec![("cuCtxPushCurrent_v2", 700)],
_ => vec![],
};
assert_eq!(cuda_errors(&error), expected);
if case == "vector_null_load" {
assert!(matches!(
error,
Error::InvalidDriverValue("cuModuleLoadData")
));
}
if case == "vector_null_function" {
assert!(matches!(
error,
Error::InvalidDriverValue("cuModuleGetFunction")
));
}
if case == "vector_wrong_pop" {
assert_eq!(error, Error::UnexpectedContext);
}
if [
"vector_sync",
"vector_launch_sync",
"vector_launch_sync_pop",
"vector_pop",
"vector_wrong_pop",
"vector_lookup_unload",
]
.contains(&case)
{
let before = trace().len();
assert!(context.vector_add_f32(&a, &b, &mut out).is_err());
assert!(context.allocate(4).is_err());
assert!(a.copy_from(&encode(&av)).is_err());
assert!(context.synchronize().is_err());
assert_eq!(trace().len(), before, "poison admits zero native work");
// Encourage allocator reuse before containment reads pending args.
let churn: Vec<_> = (0..1024).map(|_| Box::new([0xdeadbeefu64; 8])).collect();
std::hint::black_box(churn);
}
} else {
result.unwrap();
if case == "vector_cache" {
context.vector_add_f32(&a, &b, &mut out).unwrap();
}
let mut output = vec![0; bytes];
out.copy_to(&mut output).unwrap();
let expected: Vec<_> = av
.iter()
.zip(if case == "vector_same_input" {
&av
} else {
&bv
})
.map(|(a, b)| (a + b).to_bits())
.collect();
let actual: Vec<_> = output
.as_chunks::<4>()
.0
.iter()
.map(|v| u32::from_ne_bytes(*v))
.collect();
assert_eq!(actual, expected, "independent exact finite f32 reference");
let mut unchanged = vec![0; bytes];
a.copy_to(&mut unchanged).unwrap();
assert_eq!(unchanged, encode(&av));
b.copy_to(&mut unchanged).unwrap();
assert_eq!(unchanged, encode(&bv));
if case == "vector_contexts" {
let second = device.create_context(bytes * 3).unwrap();
let mut x = second.allocate(bytes).unwrap();
let mut y = second.allocate(bytes).unwrap();
let mut z = second.allocate(bytes).unwrap();
x.copy_from(&encode(&av)).unwrap();
y.copy_from(&encode(&bv)).unwrap();
second.vector_add_f32(&x, &y, &mut z).unwrap();
z.copy_to(&mut output).unwrap();
assert_eq!(
output,
encode(&av.iter().zip(&bv).map(|(a, b)| a + b).collect::<Vec<_>>())
);
drop((x, y, z));
second.close().unwrap();
}
}
drop((a, b, out));
let closed = context.close();
match case {
"vector_unload" => assert_eq!(
cuda_errors(&closed.unwrap_err()),
vec![("cuModuleUnload", 700)]
),
"vector_close_pop" => assert_eq!(
cuda_errors(&closed.unwrap_err()),
vec![("cuCtxPopCurrent_v2", 700)]
),
"vector_close_destroy" => assert_eq!(
cuda_errors(&closed.unwrap_err()),
vec![("cuCtxDestroy_v2", 700)]
),
_ => closed.unwrap(),
}
let rows = trace();
assert!(!rows.iter().any(|r| {
[
"unsafe_pending_free",
"unsafe_pending_unload",
"stack_arguments",
]
.contains(&r.stage.as_str())
}));
let expected_modules = if case == "vector_contexts" { 2 } else { 1 };
if !["vector_load", "vector_null_load", "vector_push"].contains(&case) {
assert_eq!(
rows.iter()
.filter(|r| r.stage == "load" && r.code == 0)
.count(),
expected_modules
);
}
if !execution_failure {
assert_eq!(
rows.iter()
.filter(|r| r.stage == "lookup" && r.code == 0)
.count(),
expected_modules
);
let launches = if ["vector_cache", "vector_contexts"].contains(&case) {
2
} else {
1
};
assert_eq!(
rows.iter().filter(|r| r.stage == "launch").count(),
launches
);
assert!(
rows.iter()
.filter(|r| r.stage == "geometry")
.all(|r| r.bytes == count.div_ceil(128))
);
assert!(
rows.iter()
.filter(|r| r.stage == "arguments")
.all(|r| r.bytes == count)
);
}
for (i, row) in rows.iter().enumerate().filter(|(_, r)| r.stage == "launch") {
assert!(
rows[i + 1..]
.iter()
.take_while(|r| r.stage != "pop")
.any(|r| r.stage == "sync"),
"mandatory sync after any launch attempt"
);
assert!([0, 700].contains(&row.code));
}
if [
"vector_sync",
"vector_launch_sync",
"vector_launch_sync_pop",
]
.contains(&case)
{
assert_eq!(rows.iter().filter(|r| r.stage == "unload").count(), 0);
assert!(
rows.iter()
.any(|r| r.stage == "pending_launch" && r.bytes == count)
);
}
if ["vector_unload", "vector_lookup_unload"].contains(&case) {
assert_eq!(
rows.iter().filter(|r| r.stage == "unload").count(),
1,
"failed handle consumed once"
);
}
for stage in ["load", "lookup", "unload", "launch"] {
for row in rows.iter().filter(|r| r.stage == stage && r.code == 0) {
assert!([0x22, 0x23].contains(&row.current));
assert_eq!(row.depth, 1);
}
}
if case != "vector_close_destroy" {
let last = rows
.iter()
.rev()
.find(|r| r.stage == "destroy" && r.code == 0)
.unwrap();
assert_eq!(last.current, 0x11);
assert_eq!(last.live, 0);
assert_eq!(last.charged, 0);
}
}
+13
View File
@@ -0,0 +1,13 @@
[package]
name = "leleka-model-format"
version = "0.1.0"
description = "Bounded native GGUF metadata and tensor indexing for Leleka"
edition.workspace = true
license.workspace = true
rust-version.workspace = true
[dependencies]
sha2 = "0.11"
[lints]
workspace = true
+76
View File
@@ -0,0 +1,76 @@
# Leleka model format foundation
`leleka-model-format` exposes the existing bounded GGUF v3 parser as an
independent Rust crate. It depends directly on `sha2` and the standard library;
it has no build script, C/FFI shim, GGML, Strata process/source link, CUDA or
Python dependency. The existing control plane reexports its `gguf` module, so
preparation, inspection, tokenizer extraction and tensor-export consumers keep
their public paths.
The original parser geometry and its three tests were moved unchanged from `control-plane/src/gguf.rs`.
Tensor block geometry and the legacy Flash-Next metadata guard retain their
upstream references; see [the provenance record](../../docs/upstream.md).
Those helpers inspect metadata and byte layout, not tensor values or inference.
Recognizing a quantization block size is not support for decoding or serving it.
## Contract and limits
- `inspect` validates GGUF v3 header structure and reports metadata/layout.
- `tensor_index` additionally requires known block geometry, checked dimensions,
alignment, bounded nonoverlapping tensor spans and consistent file bounds.
- `tensor_sha256` hashes one indexed tensor through a fixed 1 MiB buffer.
- `tokenizer_metadata` extracts the existing Qwen35 tokenizer fields after
header inspection; the separate tokenizer crate implements tokenization.
- `check_flash_next_profile` is the existing specialized metadata admission
check. It does not validate a complete model, tokenizer or numerical output.
All preexisting bounds/rejections remain unchanged. Path-based functions reopen
the source; callers must keep the verified file stable between inspection and
reading. File length checks do not detect same-size replacement or mutation.
`VerifiedGgufFile::open` is a separate owned-file API: it accepts a
`sha256:<64 hex digits>` artifact digest, opens one regular file, hashes the full
file with a buffer of at most 64 KiB, and parses the strict tensor index through
that same handle. The private file/index pair is retained; `index()` offers only
an immutable borrow. `stream_tensor` validates a requested tensor number and
byte range before delivering at most 64 KiB per callback, and `tensor_sha256`
hashes the indexed payload through that stream. Neither tensor operation reopens
the pathname or allocates the full tensor. A consumer may explicitly collect
chunks or return an I/O error to abort. Empty ranges at the tensor end are valid.
Renaming or replacing the original pathname after opening does not redirect this
handle to a different file. The preliminary path metadata check rejects ordinary
nonregular paths; the opened-file metadata check determines whether the accepted
handle is regular. This does not make pathname lookup atomic against a malicious
concurrent substitution during opening. The caller must supply a stable regular
source for opening and prevent **in-place writes for the entire verification,
indexing and read lifetime**. Keeping a file descriptor does not make its bytes
immutable: even same-size writes to the same file remain visible and are not
caught by file length checks. The stored artifact digest records verification at
open, not a later content attestation. Size changes are refused before/after
streaming, and short reads propagate errors; callbacks already delivered before
an I/O failure cannot be retracted.
The existing path APIs and tensor geometry remain unchanged. Descriptor, tensor
and tokenizer semantics, memory admission, GPU allocation, readiness and
real-model parity remain separate work.
The current `strata-control` still has its legacy GGML/build dependencies;
extracting this crate does not remove them from that package or its runtime.
## Standalone checks
```sh
cargo test --locked -p leleka-model-format
cargo clippy --locked -p leleka-model-format --all-targets -- -D warnings
cargo tree --locked -p leleka-model-format
```
These are container/parser checks with sanitized synthetic bytes. They do not
establish inference, model quality, GPU operation or performance.
Owned-file tests use generated synthetic GGUF bytes: full-digest and tensor-byte
oracles, multi-chunk and partial streaming, malformed digest, nonregular source,
tamper, truncate, unsupported version/type and overlapping geometry rejection,
range/overflow checks before callbacks, callback abort/recovery, Unix pathname
replacement retaining the original file, and an explicit same-size in-place
mutation counterexample. These tests do not qualify an immutable artifact store
or a complete model loader.
@@ -52,6 +52,164 @@ pub struct TokenizerMetadata {
pub chat_template: String,
}
/// An owned GGUF file whose complete bytes matched the declared digest at open.
///
/// The private file and index stay paired across pathname replacements. This is
/// not an immutable snapshot: callers must prevent in-place writes for the whole
/// verification, indexing and reading lifetime. Size checks cannot prove that.
#[derive(Debug)]
pub struct VerifiedGgufFile {
file: File,
index: TensorIndex,
artifact_sha256: [u8; 32],
}
const STREAM_BUFFER_BYTES: usize = 64 * 1024;
impl VerifiedGgufFile {
/// Verify `sha256:<64 hex digits>` and strictly index the same opened file.
/// The opened file's contents must remain stable until this handle is dropped.
pub fn open(path: &Path, expected_digest: &str) -> Result<Self> {
let expected = parse_artifact_digest(expected_digest)?;
// Refuse an ordinary nonregular path before opening it (notably FIFOs).
// The opened-file check below is authoritative for the accepted source.
if !std::fs::metadata(path)?.is_file() {
return Err("GGUF source must be a regular file".into());
}
let mut file = File::open(path)?;
let metadata = file.metadata()?;
if !metadata.is_file() {
return Err("GGUF source must be a regular file".into());
}
let size = metadata.len();
let mut digest = Sha256::new();
stream_file_span(&mut file, 0, size, |chunk| {
digest.update(chunk);
Ok(())
})?;
let actual: [u8; 32] = digest.finalize().into();
if actual != expected {
return Err("GGUF artifact SHA256 mismatch".into());
}
if file.metadata()?.len() != size {
return Err("GGUF source size changed during verification".into());
}
let index = read_index_file(&mut file, size, true)?;
if file.metadata()?.len() != size {
return Err("GGUF source size changed during indexing".into());
}
Ok(Self {
file,
index,
artifact_sha256: actual,
})
}
pub fn index(&self) -> &TensorIndex {
&self.index
}
/// Digest verified when opening, not a promise of later source immutability.
pub fn artifact_sha256(&self) -> [u8; 32] {
self.artifact_sha256
}
/// Stream an exact byte range within an indexed tensor through a buffer of
/// at most 64 KiB. The consumer may return an I/O error to abort the stream.
/// No pathname is reopened; all range checks precede the first callback.
pub fn stream_tensor(
&mut self,
tensor_number: usize,
offset: u64,
bytes: u64,
consume: impl FnMut(&[u8]) -> std::io::Result<()>,
) -> Result<()> {
let tensor = self
.index
.tensors
.get(tensor_number)
.ok_or("GGUF tensor index is out of bounds")?;
if tensor.bytes == 0
|| offset
.checked_add(bytes)
.is_none_or(|end| end > tensor.bytes)
{
return Err("GGUF tensor byte range is out of bounds".into());
}
let absolute = self
.index
.summary
.data_start
.checked_add(tensor.offset)
.and_then(|start| start.checked_add(offset))
.ok_or("GGUF tensor offset overflow")?;
if absolute
.checked_add(bytes)
.is_none_or(|end| end > self.index.summary.file_size)
{
return Err("GGUF tensor exceeds indexed file".into());
}
self.check_size()?;
stream_file_span(&mut self.file, absolute, bytes, consume)?;
self.check_size()
}
/// Hash the complete indexed tensor without allocating its full payload.
pub fn tensor_sha256(&mut self, tensor_number: usize) -> Result<[u8; 32]> {
let bytes = self
.index
.tensors
.get(tensor_number)
.ok_or("GGUF tensor index is out of bounds")?
.bytes;
let mut digest = Sha256::new();
self.stream_tensor(tensor_number, 0, bytes, |chunk| {
digest.update(chunk);
Ok(())
})?;
Ok(digest.finalize().into())
}
fn check_size(&self) -> Result<()> {
if self.file.metadata()?.len() != self.index.summary.file_size {
return Err("GGUF source size changed after verification".into());
}
Ok(())
}
}
fn parse_artifact_digest(value: &str) -> Result<[u8; 32]> {
let hex = value
.strip_prefix("sha256:")
.ok_or("invalid GGUF artifact digest")?;
if hex.len() != 64 || !hex.bytes().all(|byte| byte.is_ascii_hexdigit()) {
return Err("invalid GGUF artifact digest".into());
}
let mut digest = [0u8; 32];
for (index, byte) in digest.iter_mut().enumerate() {
*byte = u8::from_str_radix(&hex[index * 2..index * 2 + 2], 16)?;
}
Ok(digest)
}
fn stream_file_span(
file: &mut File,
absolute: u64,
bytes: u64,
mut consume: impl FnMut(&[u8]) -> std::io::Result<()>,
) -> Result<()> {
file.seek(SeekFrom::Start(absolute))?;
let mut buffer = vec![0u8; bytes.min(STREAM_BUFFER_BYTES as u64) as usize];
let mut remaining = bytes;
while remaining > 0 {
let count = remaining.min(buffer.len() as u64) as usize;
file.read_exact(&mut buffer[..count])?;
consume(&buffer[..count])?;
remaining -= count as u64;
}
Ok(())
}
/// Metadata admission for the specialised engine, before expensive preparation.
/// Mirrors artifact/gguf_reader.hpp::Qwen4ExpGuard; this does not inspect tensor values.
pub fn check_flash_next_profile(path: &Path) -> Result<()> {
@@ -240,8 +398,13 @@ pub fn tensor_sha256(path: &Path, index: &TensorIndex, tensor_number: usize) ->
}
fn read_index(path: &Path, strict: bool) -> Result<TensorIndex> {
let file = File::open(path)?;
let mut file = File::open(path)?;
let size = file.metadata()?.len();
read_index_file(&mut file, size, strict)
}
fn read_index_file(file: &mut File, size: u64, strict: bool) -> Result<TensorIndex> {
file.seek(SeekFrom::Start(0))?;
let mut cursor = Cursor { file, size };
if cursor.take(4)? != b"GGUF" {
return Err("not a GGUF file".into());
@@ -431,12 +594,12 @@ pub fn block_geometry(kind: u32) -> Option<(u64, u64)> {
})
}
struct Cursor {
file: File,
struct Cursor<R> {
file: R,
size: u64,
}
impl Cursor {
impl<R: Read + Seek> Cursor<R> {
fn position(&mut self) -> Result<u64> {
Ok(self.file.stream_position()?)
}
@@ -784,4 +947,274 @@ mod tests {
assert!(tensor_index(&path).is_err());
std::fs::remove_file(path).unwrap();
}
struct OwnedFixture {
directory: std::path::PathBuf,
path: std::path::PathBuf,
bytes: Vec<u8>,
small: Vec<u8>,
large: Vec<u8>,
kind_at: usize,
offset_at: usize,
}
impl OwnedFixture {
fn new() -> Self {
use std::sync::atomic::{AtomicU64, Ordering};
static NEXT: AtomicU64 = AtomicU64::new(0);
let directory = std::env::temp_dir().join(format!(
"leleka-owned-gguf-{}-{}",
std::process::id(),
NEXT.fetch_add(1, Ordering::Relaxed)
));
std::fs::create_dir(&directory).unwrap();
let path = directory.join("fixture.gguf");
let small = (0..16).collect::<Vec<u8>>();
let large = (0..STREAM_BUFFER_BYTES * 3 + 11)
.map(|at| (at % 251) as u8)
.collect::<Vec<_>>();
let mut bytes = b"GGUF".to_vec();
bytes.extend(3u32.to_le_bytes());
bytes.extend(2u64.to_le_bytes());
bytes.extend(0u64.to_le_bytes());
string(&mut bytes, "fixture.small");
bytes.extend(1u32.to_le_bytes());
bytes.extend(4u64.to_le_bytes());
bytes.extend(0u32.to_le_bytes());
bytes.extend(0u64.to_le_bytes());
string(&mut bytes, "fixture.large");
bytes.extend(1u32.to_le_bytes());
bytes.extend((large.len() as u64).to_le_bytes());
let kind_at = bytes.len();
bytes.extend(24u32.to_le_bytes());
let offset_at = bytes.len();
bytes.extend(32u64.to_le_bytes());
bytes.resize(bytes.len().div_ceil(32) * 32, 0);
bytes.extend(&small);
bytes.extend([0u8; 16]);
bytes.extend(&large);
std::fs::write(&path, &bytes).unwrap();
Self {
directory,
path,
bytes,
small,
large,
kind_at,
offset_at,
}
}
fn digest(&self) -> String {
let hex = Sha256::digest(&self.bytes)
.iter()
.map(|byte| format!("{byte:02x}"))
.collect::<String>();
format!("sha256:{hex}")
}
}
impl Drop for OwnedFixture {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.directory);
}
}
#[test]
fn owned_handle_verifies_artifact_and_streams_exact_tensor_bytes_with_bounded_chunks() {
let fixture = OwnedFixture::new();
let mut source = VerifiedGgufFile::open(&fixture.path, &fixture.digest()).unwrap();
assert_eq!(
source.artifact_sha256(),
<[u8; 32]>::from(Sha256::digest(&fixture.bytes))
);
assert_eq!(source.index().tensors.len(), 2);
assert_eq!(source.index().tensors[1].bytes, fixture.large.len() as u64);
for (number, expected) in [(0, &fixture.small), (1, &fixture.large)] {
assert_eq!(
source.tensor_sha256(number).unwrap(),
<[u8; 32]>::from(Sha256::digest(expected))
);
}
let mut seen = 0;
let mut callbacks = 0;
source
.stream_tensor(1, 0, fixture.large.len() as u64, |chunk| {
assert!(!chunk.is_empty() && chunk.len() <= STREAM_BUFFER_BYTES);
assert_eq!(chunk, &fixture.large[seen..seen + chunk.len()]);
seen += chunk.len();
callbacks += 1;
Ok(())
})
.unwrap();
assert_eq!(seen, fixture.large.len());
assert_eq!(callbacks, 4);
let mut partial = Vec::new();
source
.stream_tensor(1, 7, 13, |chunk| {
partial.extend_from_slice(chunk);
Ok(())
})
.unwrap();
assert_eq!(partial, fixture.large[7..20]);
}
#[test]
fn owned_handle_rejects_bad_digest_nonregular_sources_and_tampering() {
let fixture = OwnedFixture::new();
for digest in [
"",
"abc",
"sha256:abc",
&format!("sha256:{}", "g".repeat(64)),
&format!("SHA256:{}", "a".repeat(64)),
] {
assert!(
VerifiedGgufFile::open(&fixture.path, digest)
.unwrap_err()
.to_string()
.contains("invalid GGUF artifact digest")
);
}
assert!(
VerifiedGgufFile::open(&fixture.directory, &fixture.digest())
.unwrap_err()
.to_string()
.contains("regular file")
);
let mut tampered = fixture.bytes.clone();
*tampered.last_mut().unwrap() ^= 1;
std::fs::write(&fixture.path, tampered).unwrap();
assert!(
VerifiedGgufFile::open(&fixture.path, &fixture.digest())
.unwrap_err()
.to_string()
.contains("SHA256 mismatch")
);
}
#[test]
fn owned_handle_rejects_truncated_unsupported_and_bad_geometry_even_with_matching_digest() {
let mut fixture = OwnedFixture::new();
let original = fixture.bytes.clone();
for fault in 0..4 {
fixture.bytes = original.clone();
match fault {
0 => {
fixture.bytes.pop();
}
1 => fixture.bytes[fixture.kind_at..fixture.kind_at + 4]
.copy_from_slice(&u32::MAX.to_le_bytes()),
2 => fixture.bytes[fixture.offset_at..fixture.offset_at + 8]
.copy_from_slice(&0u64.to_le_bytes()),
3 => fixture.bytes[4..8].copy_from_slice(&2u32.to_le_bytes()),
_ => unreachable!(),
}
std::fs::write(&fixture.path, &fixture.bytes).unwrap();
assert!(
VerifiedGgufFile::open(&fixture.path, &fixture.digest()).is_err(),
"fault {fault}"
);
}
}
#[test]
fn owned_tensor_bounds_are_checked_before_any_callback_and_stream_can_recover() {
let fixture = OwnedFixture::new();
let mut source = VerifiedGgufFile::open(&fixture.path, &fixture.digest()).unwrap();
for (number, offset, bytes) in [
(2, 0, 1),
(0, 0, 17),
(0, 17, 0),
(0, u64::MAX, 1),
(0, 1, u64::MAX),
] {
let mut called = false;
assert!(
source
.stream_tensor(number, offset, bytes, |_| {
called = true;
Ok(())
})
.is_err()
);
assert!(!called);
}
source
.stream_tensor(0, 16, 0, |_| panic!("empty range invoked consumer"))
.unwrap();
assert!(
source
.stream_tensor(1, 0, 10, |_| Err(std::io::Error::other(
"synthetic consumer failure"
)))
.unwrap_err()
.to_string()
.contains("synthetic consumer failure")
);
assert_eq!(
source.tensor_sha256(0).unwrap(),
<[u8; 32]>::from(Sha256::digest(&fixture.small))
);
}
#[cfg(unix)]
#[test]
fn pathname_replacement_keeps_original_verified_file_and_index() {
let fixture = OwnedFixture::new();
let mut source = VerifiedGgufFile::open(&fixture.path, &fixture.digest()).unwrap();
std::fs::rename(&fixture.path, fixture.directory.join("original.gguf")).unwrap();
std::fs::write(&fixture.path, b"replacement is not a GGUF file").unwrap();
assert!(tensor_index(&fixture.path).is_err());
assert_eq!(
source.tensor_sha256(1).unwrap(),
<[u8; 32]>::from(Sha256::digest(&fixture.large))
);
let mut small = Vec::new();
source
.stream_tensor(0, 0, 16, |chunk| {
small.extend_from_slice(chunk);
Ok(())
})
.unwrap();
assert_eq!(small, fixture.small);
assert_eq!(
source.artifact_sha256(),
<[u8; 32]>::from(Sha256::digest(&fixture.bytes))
);
}
#[test]
fn opened_file_size_changes_are_refused_and_same_size_mutation_is_not_immutability() {
let fixture = OwnedFixture::new();
let mut source = VerifiedGgufFile::open(&fixture.path, &fixture.digest()).unwrap();
let mut mutated = fixture.bytes.clone();
*mutated.last_mut().unwrap() ^= 1;
std::fs::write(&fixture.path, &mutated).unwrap();
// Explicit counterexample: retaining the descriptor does not freeze bytes.
assert_ne!(
source.tensor_sha256(1).unwrap(),
<[u8; 32]>::from(Sha256::digest(&fixture.large))
);
assert_eq!(
source.artifact_sha256(),
<[u8; 32]>::from(Sha256::digest(&fixture.bytes))
);
std::fs::OpenOptions::new()
.write(true)
.open(&fixture.path)
.unwrap()
.set_len(0)
.unwrap();
let mut called = false;
assert!(
source
.stream_tensor(0, 0, 16, |_| {
called = true;
Ok(())
})
.is_err()
);
assert!(!called);
}
}
+9
View File
@@ -0,0 +1,9 @@
//! Backend-independent model-container inspection and indexing.
//!
//! This foundation exposes bounded GGUF metadata and byte geometry. It does
//! not implement dequantization, complete model loading, device allocation or inference.
//! The owned GGUF reader binds digest verification and indexing to one open file;
//! callers must keep that file's contents stable throughout its lifetime.
//! Its only direct dependency is the Rust SHA-256 implementation in `sha2`.
pub mod gguf;
+14
View File
@@ -0,0 +1,14 @@
[package]
name = "leleka-quant-core"
version = "0.1.0"
description = "Pure Rust bounded IQ3_S CPU decoding and binary16 conversion"
edition.workspace = true
license = "Apache-2.0 AND MIT"
rust-version.workspace = true
[dev-dependencies]
sha2 = "0.11"
hex = "0.4"
[lints]
workspace = true
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2023-2026 The ggml authors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+182
View File
@@ -0,0 +1,182 @@
# Leleka quantization foundation
`leleka-quant-core` provides IQ2_S, IQ3_S, IQ3_XXS, IQ4_NL, IQ4_XS, Q2_0, Q4_K,
Q5_K, Q6_K and Q8_0
CPU decoding and binary16-to-binary32
conversion in an independent Rust crate. Production code uses only the standard
library: no build script, C/FFI, GGML, Strata source/process, Python or CUDA dependency.
`sha2` and `hex` are test-only dependencies for the existing golden checks.
The control plane reexports `iq3_s` and `kar_codec::f16_bits_to_f32`, preserving
all existing preparation and KAR consumer paths. Its separate legacy GGML/build
dependencies remain; this extraction does not make the control plane autonomous.
## Contract and provenance
IQ3_S decoding accepts 110-byte blocks with 256 output elements. It retains the
existing layout, finite-scale rejection, checked output geometry, arithmetic,
pinned grid and golden hashes. `decode_into` processes blocks in order; if a later
block is invalid, earlier output blocks may already have been written. Callers
must handle the error and must not consume a partial result as successful output.
Binary16 conversion preserves the existing signed-zero, subnormal, infinity and
NaN payload bit behavior. Encoding and its rounding helpers remain in KAR.
The grid was imported from `ggml-common.h` at upstream Strata commit
`d9ab8435f654c368c586340d490915f6addf56a3`. Its ggml MIT notice is copied unchanged
in [LICENSE-GGML](LICENSE-GGML); the table's source provenance remains in its
header. The Rust extraction retains the original decoder and helper arithmetic.
No engine file is included or read to build or use this crate.
IQ4_NL decoding accepts 18-byte blocks with 32 output elements, using the pinned
16-value nonlinear codebook. Packed low nibbles produce elements 0–15 and high
nibbles produce elements 16–31. The arithmetic and table follow
`dequantize_row_iq4_nl` / `kvalues_iq4nl` at the same llama.cpp GGML commit
`3cf03257f219afbe7334045ff7c6a06ac68c627d`; the existing MIT notice in
[LICENSE-GGML](LICENSE-GGML) covers that table. `decode_into` validates complete
input blocks and exact output length before writing, accepts a zero-block
operation, and uses no heap buffer or input alignment requirement.
IQ4_NL deliberately propagates infinity and NaN scales to preserve its former C
preparation behavior. Existing consumers retain their own nonfinite-value policy;
the IQ3_S finite-scale rejection is unchanged. Finite-scale output is qualified
against the pinned C oracle with zero bit tolerance. For NaN scales, classification
and successful admission are checked, without claiming portable NaN payload/sign
bits; infinity output signs and bits are checked. See
[IQ4_NL reference parity](../../docs/iq4-reference-parity.md) for test scope and
actual CPU results. This port removes IQ4_NL's computational C dependency in the
preparation visitor; other legacy control-plane C paths and builds remain.
IQ4_XS accepts 136-byte blocks with 256 output elements. It shares IQ4_NL's
codebook through a crate-private constant; the public IQ4_NL API and table bytes
are unchanged. Each block stores a little-endian FP16 scale, little-endian 16-bit
packed scale highs, four packed scale-low bytes and 128 packed codepoint bytes.
Each of eight 32-element subblocks reconstructs a six-bit scale, subtracts 32,
then performs `base * multiplier` followed by `subblock_scale * codepoint`.
Low and high codepoint nibbles produce separate 16-element halves. This follows
the pinned `dequantize_row_iq4_xs` function and preserves its intermediate,
including signed zero and infinity times zero producing NaN.
Q8_0 accepts 34-byte blocks with 32 output elements: a little-endian FP16 scale
and 32 signed bytes, decoded by scale multiplication as in the pinned
`dequantize_row_q8_0` function. IQ4_XS and Q8_0 admit every FP16 scale encoding;
existing consumers retain their nonfinite-value policy. Their bulk APIs reject
malformed shapes before writes, accept empty input/output, require no source
alignment, and use no heap decoding buffer. The separate pinned C-oracle gates
record exact finite bits and explicit nonfinite classification/infinity signs
without implying portable NaN payload/sign bits, GPU behavior or complete model
support. See [combined reference parity](../../docs/q8-iq4xs-reference-parity.md)
for actual corpus, compiler and results.
Q4_K accepts 144-byte blocks; Q5_K accepts 176-byte blocks. Both produce 256
values from a little-endian FP16 scale and minimum, a shared 12-byte packed
six-bit scale/minimum header, and eight 32-element subblocks. The crate-private
header helper follows pinned `get_scale_min_k4`: the upper two bits for subblocks
4–7 share the first eight header bytes, and the remaining four bytes store their
low nibbles. Q4_K's quant bytes start at offset 16 and split each byte into two
32-element halves. Q5_K's 32 high-bit bytes start at offset 16 and low-nibble
bytes at offset 48; every high-bit lane is reused across four pairs, with masks
1/2, 4/8, 16/32 and 64/128 selecting the corresponding half.
The arithmetic follows pinned `dequantize_row_q4_K` / `dequantize_row_q5_K`:
first form `d * scale` and `dmin * minimum`, then compute
`subblock_scale * quant - subblock_minimum`. These steps are kept separate, with
no `mul_add` or reassociation. Both formats admit all FP16 encodings, preserving
signed zero, infinity times zero and infinity-minus-infinity NaN behavior;
consumer value policies remain unchanged. Like the other bulk APIs, invalid
shapes fail before output writes, empty input/output is valid, and decoding uses
no heap allocation or source alignment requirement. Synthetic standalone tests
check independently specified wire bytes/expected values, both scale-header
branches, all Q5 high masks, bulk/shape handling and nonfinite/signed-zero cases.
See [Q4_K/Q5_K reference parity](../../docs/q4-q5-k-reference-parity.md) for the
separate pinned C-oracle scope and actual results. These CPU preparation ports
do not remove all control-plane C builds or qualify serving/model/GPU behavior.
Q2_0 accepts 18-byte blocks producing 64 values. Its little-endian FP16 scale
occupies bytes 0–1; each following byte contains four consecutive two-bit
elements, read from least to most significant bits. Codes 0, 1, 2 and 3 map to
quant values −1, 0, 1 and 2, then multiply `quant * scale`, following pinned
`dequantize_row_q2_0`. This format is GGUF kind 42, distinct from Q2_K.
Q6_K accepts 210-byte blocks producing 256 values. Its low quant bytes occupy
0–127, high quant bytes 128–191, signed int8 subscales 192–207 and little-endian
FP16 base scale 208–209. Two 128-value halves each contain four 32-value
quadrants. High-bit shifts 0/2/4/6 combine with the low/high nibbles, giving a
six-bit code minus 32; the subscale index uses a 16-element lane group within
each quadrant. Arithmetic follows pinned `dequantize_row_q6_K`, preserving
`(base * signed_subscale) * signed_quant` rather than reassociating products.
The −128 subscale remains signed. No codebook or K scale/minimum helper is used.
Both formats propagate all FP16 encodings, including NaN and infinity. Infinity
times zero quant, and Q6_K infinity times zero subscale, produce NaN; existing
consumer value policies stay unchanged. Shape errors fail before output writes,
empty bulk input/output is valid, and decoding requires neither a heap buffer
nor source alignment. Standalone synthetic tests check independent expected
wire values, every Q6_K packed lane/quadrant mapping, bulk/bounds behavior,
signed zero and nonfinite zero-factor cases. Separate pinned C oracles qualify
finite output bits and explicit nonfinite classification/sign behavior; they
do not imply portable NaN payloads, model/GPU support or performance results.
See [Q6_K/Q2_0 reference parity](../../docs/q6-k-q2-0-reference-parity.md) for
the recorded corpus, compiler and actual test results.
IQ2_S accepts 82-byte blocks producing 256 values. After the little-endian FP16
scale, bytes 2–33 hold eight-bit grid index lows, bytes 34–65 hold raw eight-bit
sign masks, bytes 66–73 hold two-bit index highs and bytes 74–81 hold scale
nibbles. Each 32-value subblock contains four eight-value grids; the low scale
nibble applies to the first two, the high nibble to the last two. Its 1024-entry
grid uses explicit little-endian u64 bytes. Arithmetic preserves
`((base * (0.5 + nibble)) * 0.25) * magnitude * sign` in the pinned C order.
IQ2_S uses all 256 raw sign masks, with no seven-bit sign-code lookup.
IQ3_XXS accepts 98-byte blocks producing 256 values. Grid indices occupy bytes
2–65; bytes 66–97 contain eight little-endian u32 words, each storing four
seven-bit sign codes plus a top scale nibble. Each eight-value group uses two
four-value grids from the 256-entry u32 table, read as explicit little-endian
bytes, and the pinned 128-entry sign lookup. Arithmetic preserves
`((base * (0.5 + nibble)) * 0.5) * magnitude * sign`. Both ports use the same
F16 helper and admit every FP16 encoding; signed zero, infinity signs and NaN
classification retain the prior consumer policy. Grid magnitudes and valid
scale factors are nonzero; there is no packed zero factor for infinity in these
two formats. Bulk shapes fail before writes, empty input/output is valid, and
decoding has no heap allocation or input alignment requirement.
The exact lookup entries were independently imported from the pinned
`ggml-common.h` (SHA-256
`0061131b615c5721fc88a78feeb22c1f8c450f1c2646a317d80796a653bf595c`),
after checking its tracked source manifest. Import provenance and the ggml MIT
notice are retained in the table files and [LICENSE-GGML](LICENSE-GGML).
Canonical byte SHA-256 values checked by standalone tests are:
| Table | Canonical bytes | SHA-256 |
| --- | --- | --- |
| IQ2_S grid | 1024 little-endian u64 entries | `e1aa1473412b0552c2174c30ef22ab4073f6a181b85a17056e8249bd2932fd88` |
| IQ3_XXS grid | 256 little-endian u32 entries | `46e35f5a997efdee6c99ce57854c8a0d4f0ff8ca57e5e8a60c0793ea580acf5d` |
| IQ3_XXS sign lookup | 128 u8 entries | `a76742a603f8beca5212ecce0f1f02f11a4887fd2f7c8b15aca0ea3eb3380c31` |
Standalone tests additionally check independent expected wire values, index
highs, nibble halves, word/grid byte order, raw/codebook sign domains, signed
zero/nonfinite admission and bulk/shape boundaries. See
[IQ2_S/IQ3_XXS reference parity](../../docs/iq2-s-iq3-xxs-reference-parity.md)
for the separate pinned C-oracle corpus and actual results. No imported engine
source is changed. CPU tensor-format coverage does not qualify complete model
loading, readiness, GPU execution, quality or performance, and the existing
control-plane C build dependency remains until separately removed.
The existing tests preserve the SHA-256 of the little-endian grid bytes
(`bd1af4945a1717c65610b0284e4628b9a1ba3b306fae3a06f6e5f597356e349f`)
and the mixed-block decoded f32 bytes
(`cfee2753d1b389fe4ee30994ff3387d4400745b8432aeb32cb4d7fced39949ec`).
Independent IEEE 754 boundary encodings additionally check the shared conversion.
## Standalone checks and limits
```sh
cargo fmt --manifest-path crates/quant-core/Cargo.toml --check
cargo clippy --locked -p leleka-quant-core --all-targets -- -D warnings
cargo test --locked -p leleka-quant-core
cargo tree --locked -p leleka-quant-core --edges normal
```
These are bounded CPU preparation primitives and synthetic numerical checks.
They do not implement compute shaders, GPU dispatch, complete model loading,
inference, model quality or performance qualification. Independent C-oracle
checks in the control plane are separate offline tests; they do not add a native
dependency to this crate.
+168
View File
@@ -0,0 +1,168 @@
//! Allocation-free IQ2_S CPU decoding (82 bytes / 256 values).
//! Pinned to llama.cpp 3cf03257f219afbe7334045ff7c6a06ac68c627d
//! `dequantize_row_iq2_s` and `block_iq2_s`; MIT, ggml authors (LICENSE-GGML).
//! All FP16 encodings are admitted; consumers retain their value policy.
use crate::{f16_bits_to_f32, iq2s_grid::IQ2S_GRID};
pub const BLOCK_BYTES: usize = 82;
pub const BLOCK_ELEMENTS: usize = 256;
pub fn decode_block(block: &[u8; BLOCK_BYTES]) -> Result<[f32; BLOCK_ELEMENTS], String> {
let base = f16_bits_to_f32(u16::from_le_bytes([block[0], block[1]]));
let mut output = [0.0; BLOCK_ELEMENTS];
for subblock in 0..8 {
let packed_scale = block[74 + subblock];
let scales = [
base * (0.5 + f32::from(packed_scale & 15)) * 0.25,
base * (0.5 + f32::from(packed_scale >> 4)) * 0.25,
];
for group in 0..4 {
let low = usize::from(block[2 + 4 * subblock + group]);
let high = usize::from((block[66 + subblock] >> (2 * group)) & 3) << 8;
let grid = IQ2S_GRID[low | high].to_le_bytes();
let signs = block[34 + 4 * subblock + group];
for (lane, magnitude) in grid.into_iter().enumerate() {
let sign = if signs & (1 << lane) != 0 { -1.0 } else { 1.0 };
output[32 * subblock + 8 * group + lane] =
scales[group / 2] * f32::from(magnitude) * sign;
}
}
}
Ok(output)
}
/// Invalid shapes fail before writes. Empty input/output is a zero-block
/// operation; no alignment requirement or heap decoding buffer is used.
pub fn decode_into(blocks: &[u8], output: &mut [f32]) -> Result<(), String> {
if !blocks.len().is_multiple_of(BLOCK_BYTES)
|| (blocks.len() / BLOCK_BYTES)
.checked_mul(BLOCK_ELEMENTS)
.is_none_or(|expected| expected != output.len())
{
return Err("IQ2_S block and output lengths do not match".into());
}
for (block, values) in blocks
.as_chunks::<BLOCK_BYTES>()
.0
.iter()
.zip(output.as_chunks_mut::<BLOCK_ELEMENTS>().0.iter_mut())
{
values.copy_from_slice(&decode_block(block)?);
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use sha2::{Digest, Sha256};
#[test]
fn pinned_grid_little_endian_bytes_match_source_digest() {
let mut digest = Sha256::new();
for entry in IQ2S_GRID {
digest.update(entry.to_le_bytes());
}
assert_eq!(
hex::encode(digest.finalize()),
"e1aa1473412b0552c2174c30ef22ab4073f6a181b85a17056e8249bd2932fd88"
);
}
#[test]
fn known_wire_values_cover_high_grid_bits_signs_and_scale_halves() {
let mut block = [0u8; BLOCK_BYTES];
block[..2].copy_from_slice(&0x3c00u16.to_le_bytes());
block[34..38].copy_from_slice(&[1, 128, 0x55, 0xaa]);
block[66] = 0xe4; // Grid indices 0,256,512,768.
block[74] = 0x20; // Scale .125 for first16, .625 for second16.
block[81] = 0x0f; // Last subblock first16 scale3.875.
let output = decode_block(&block).unwrap();
let expected = [
-1.0f32, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 3.125, 3.125, 3.125, 3.125, 3.125, 1.0,
3.125, -1.0, -15.625, 15.625, -26.875, 5.0, -15.625, 5.0, -5.0, 15.625, 5.0, -26.875,
5.0, -15.625, 5.0, -5.0, 26.875, -15.625,
];
assert_eq!(&output[..32], &expected);
assert_eq!(&output[32..224], &[1.0; 192]);
assert_eq!(&output[224..240], &[31.0; 16]);
assert_eq!(&output[240..], &[1.0; 16]);
block[2..34].fill(255);
block[34..66].fill(0);
block[66..74].fill(255);
block[74..].fill(0);
assert_eq!(decode_block(&block).unwrap(), [5.375; BLOCK_ELEMENTS]);
}
#[test]
fn raw_eight_bit_signs_signed_zero_and_nonfinite_scales_are_admitted() {
let mut block = [0u8; BLOCK_BYTES];
block[..2].copy_from_slice(&0x3c00u16.to_le_bytes());
for signs in 0..=u8::MAX {
block[34..66].fill(signs);
for (element, value) in decode_block(&block).unwrap().into_iter().enumerate() {
assert_eq!(
value,
if signs & (1 << (element % 8)) != 0 {
-1.0
} else {
1.0
}
);
}
}
block[34..66].fill(0x81);
for scale in [
0x0000u16, 0x8000, 0x7c00, 0xfc00, 0x7c01, 0xfc01, 0x7e00, 0xfe00,
] {
block[..2].copy_from_slice(&scale.to_le_bytes());
let mut output = [0.0; BLOCK_ELEMENTS];
decode_into(&block, &mut output).unwrap();
for (element, value) in output.into_iter().enumerate() {
let negative = (scale & 0x8000 != 0) ^ matches!(element % 8, 0 | 7);
if scale & 0x7c00 == 0x7c00 {
if scale & 0x03ff != 0 {
assert!(value.is_nan());
} else {
assert!(value.is_infinite());
assert_eq!(value.is_sign_negative(), negative);
}
} else {
assert_eq!(value.to_bits(), if negative { 0x8000_0000 } else { 0 });
}
}
}
}
#[test]
fn unaligned_bulk_and_bad_shapes_preserve_output_contract() {
let mut block = [0u8; BLOCK_BYTES];
block[..2].copy_from_slice(&0x3c00u16.to_le_bytes());
let mut storage = [0u8; BLOCK_BYTES * 2 + 16];
let start = storage.as_ptr().align_offset(16) + 1;
let source = &mut storage[start..start + BLOCK_BYTES * 2];
assert_eq!(source.as_ptr().align_offset(16), 15);
source[..BLOCK_BYTES].copy_from_slice(&block);
source[BLOCK_BYTES..].copy_from_slice(&block);
let mut output = [123.0; BLOCK_ELEMENTS * 2];
decode_into(source, &mut output).unwrap();
assert_eq!(output, [1.0; BLOCK_ELEMENTS * 2]);
for len in [0, 1, BLOCK_BYTES - 1, BLOCK_BYTES + 1, source.len() - 1] {
output.fill(123.0);
assert!(decode_into(&source[..len], &mut output).is_err());
assert_eq!(output, [123.0; BLOCK_ELEMENTS * 2]);
}
for len in [
0,
BLOCK_ELEMENTS - 1,
BLOCK_ELEMENTS + 1,
BLOCK_ELEMENTS * 2,
] {
output.fill(123.0);
assert!(decode_into(&source[..BLOCK_BYTES], &mut output[..len]).is_err());
assert_eq!(output, [123.0; BLOCK_ELEMENTS * 2]);
}
decode_into(&[], &mut []).unwrap();
}
}
File diff suppressed because it is too large Load Diff
@@ -2,7 +2,7 @@
//! Layout and grid are pinned to Strata upstream d9ab8435. This is preparation
//! code, not a serving kernel; numerical parity with a real model is pending.
use crate::{iq3s_grid::IQ3S_GRID, kar_codec::f16_bits_to_f32};
use crate::{f16_bits_to_f32, iq3s_grid::IQ3S_GRID};
pub const BLOCK_BYTES: usize = 110;
pub const BLOCK_ELEMENTS: usize = 256;
+189
View File
@@ -0,0 +1,189 @@
//! Allocation-free IQ3_XXS CPU decoding (98 bytes / 256 values).
//! Pinned to llama.cpp 3cf03257f219afbe7334045ff7c6a06ac68c627d
//! `dequantize_row_iq3_xxs` and `block_iq3_xxs`; MIT, ggml authors (LICENSE-GGML).
//! Explicit LE words/table bytes match the pinned C baseline on LE hosts.
//! All FP16 encodings are admitted; consumers retain their value policy.
use crate::{
f16_bits_to_f32,
iq3xxs_grid::{IQ3XXS_GRID, KSIGNS_IQ2XS},
};
pub const BLOCK_BYTES: usize = 98;
pub const BLOCK_ELEMENTS: usize = 256;
pub fn decode_block(block: &[u8; BLOCK_BYTES]) -> Result<[f32; BLOCK_ELEMENTS], String> {
let base = f16_bits_to_f32(u16::from_le_bytes([block[0], block[1]]));
let mut output = [0.0; BLOCK_ELEMENTS];
for subblock in 0..8 {
let at = 66 + 4 * subblock;
let packed = u32::from_le_bytes([block[at], block[at + 1], block[at + 2], block[at + 3]]);
let scale = base * (0.5 + (packed >> 28) as f32) * 0.5;
for group in 0..4 {
let signs = KSIGNS_IQ2XS[((packed >> (7 * group)) & 127) as usize];
for half in 0..2 {
let index = usize::from(block[2 + 8 * subblock + 2 * group + half]);
let grid = IQ3XXS_GRID[index].to_le_bytes();
for (lane, magnitude) in grid.into_iter().enumerate() {
let local = 4 * half + lane;
let sign = if signs & (1 << local) != 0 { -1.0 } else { 1.0 };
output[32 * subblock + 8 * group + local] = scale * f32::from(magnitude) * sign;
}
}
}
}
Ok(output)
}
/// Invalid shapes fail before writes. Empty input/output is a zero-block
/// operation; no alignment requirement or heap decoding buffer is used.
pub fn decode_into(blocks: &[u8], output: &mut [f32]) -> Result<(), String> {
if !blocks.len().is_multiple_of(BLOCK_BYTES)
|| (blocks.len() / BLOCK_BYTES)
.checked_mul(BLOCK_ELEMENTS)
.is_none_or(|expected| expected != output.len())
{
return Err("IQ3_XXS block and output lengths do not match".into());
}
for (block, values) in blocks
.as_chunks::<BLOCK_BYTES>()
.0
.iter()
.zip(output.as_chunks_mut::<BLOCK_ELEMENTS>().0.iter_mut())
{
values.copy_from_slice(&decode_block(block)?);
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use sha2::{Digest, Sha256};
#[test]
fn pinned_grid_and_sign_bytes_match_source_digests() {
let mut digest = Sha256::new();
for entry in IQ3XXS_GRID {
digest.update(entry.to_le_bytes());
}
assert_eq!(
hex::encode(digest.finalize()),
"46e35f5a997efdee6c99ce57854c8a0d4f0ff8ca57e5e8a60c0793ea580acf5d"
);
assert_eq!(
hex::encode(Sha256::digest(KSIGNS_IQ2XS)),
"a76742a603f8beca5212ecce0f1f02f11a4887fd2f7c8b15aca0ea3eb3380c31"
);
for code in 0..128u8 {
assert_eq!(
KSIGNS_IQ2XS[usize::from(code)],
code | (((code.count_ones() & 1) as u8) << 7)
);
}
}
#[test]
fn known_words_grid_byte_order_and_sign_fields_match_expected_values() {
let mut block = [0u8; BLOCK_BYTES];
block[..2].copy_from_slice(&0x3c00u16.to_le_bytes());
for pair in block[2..66].as_chunks_mut::<2>().0 {
pair[1] = 1;
}
block[66..70].copy_from_slice(&[1, 1, 1, 0x11]); // Codes1/2/4/8, scale nibble1.
block[94..98].fill(255); // Four signcodes127, scale nibble15.
block[64] = 255;
block[65] = 0;
let output = decode_block(&block).unwrap();
let expected = [
-3.0f32, 3.0, 3.0, 3.0, 15.0, 3.0, 3.0, -3.0, 3.0, -3.0, 3.0, 3.0, 15.0, 3.0, 3.0,
-3.0, 3.0, 3.0, -3.0, 3.0, 15.0, 3.0, 3.0, -3.0, 3.0, 3.0, 3.0, -3.0, 15.0, 3.0, 3.0,
-3.0,
];
assert_eq!(&output[..32], &expected);
for group in output[32..224].as_chunks::<8>().0 {
assert_eq!(group, &[1.0, 1.0, 1.0, 1.0, 5.0, 1.0, 1.0, 1.0]);
}
assert_eq!(
&output[248..],
&[-31.0, -217.0, -403.0, -480.5, -31.0, -31.0, -31.0, -31.0]
);
}
#[test]
fn sign_codes_signed_zero_and_nonfinite_scales_are_admitted() {
let mut block = [0u8; BLOCK_BYTES];
for code in 0..128u32 {
let word = code | (code << 7) | (code << 14) | (code << 21);
for chunk in block[66..].as_chunks_mut::<4>().0 {
chunk.copy_from_slice(&word.to_le_bytes());
}
block[..2].copy_from_slice(&0x3c00u16.to_le_bytes());
let expected_signs = code as u8 | (((code.count_ones() & 1) as u8) << 7);
for (element, value) in decode_block(&block).unwrap().into_iter().enumerate() {
assert_eq!(
value,
if expected_signs & (1 << (element % 8)) != 0 {
-1.0
} else {
1.0
}
);
}
}
for chunk in block[66..].as_chunks_mut::<4>().0 {
chunk.copy_from_slice(&(1u32 | (1 << 7) | (1 << 14) | (1 << 21)).to_le_bytes());
}
for scale in [
0x0000u16, 0x8000, 0x7c00, 0xfc00, 0x7c01, 0xfc01, 0x7e00, 0xfe00,
] {
block[..2].copy_from_slice(&scale.to_le_bytes());
let mut output = [0.0; BLOCK_ELEMENTS];
decode_into(&block, &mut output).unwrap();
for (element, value) in output.into_iter().enumerate() {
let negative = (scale & 0x8000 != 0) ^ matches!(element % 8, 0 | 7);
if scale & 0x7c00 == 0x7c00 {
if scale & 0x03ff != 0 {
assert!(value.is_nan());
} else {
assert!(value.is_infinite());
assert_eq!(value.is_sign_negative(), negative);
}
} else {
assert_eq!(value.to_bits(), if negative { 0x8000_0000 } else { 0 });
}
}
}
}
#[test]
fn unaligned_bulk_and_bad_shapes_preserve_output_contract() {
let mut block = [0u8; BLOCK_BYTES];
block[..2].copy_from_slice(&0x3c00u16.to_le_bytes());
let mut storage = vec![0u8; BLOCK_BYTES * 2 + 16];
let start = storage.as_ptr().align_offset(16) + 1;
let source = &mut storage[start..start + BLOCK_BYTES * 2];
assert_eq!(source.as_ptr().align_offset(16), 15);
source[..BLOCK_BYTES].copy_from_slice(&block);
source[BLOCK_BYTES..].copy_from_slice(&block);
let mut output = [123.0; BLOCK_ELEMENTS * 2];
decode_into(source, &mut output).unwrap();
assert_eq!(output, [1.0; BLOCK_ELEMENTS * 2]);
for len in [0, 1, BLOCK_BYTES - 1, BLOCK_BYTES + 1, source.len() - 1] {
output.fill(123.0);
assert!(decode_into(&source[..len], &mut output).is_err());
assert_eq!(output, [123.0; BLOCK_ELEMENTS * 2]);
}
for len in [
0,
BLOCK_ELEMENTS - 1,
BLOCK_ELEMENTS + 1,
BLOCK_ELEMENTS * 2,
] {
output.fill(123.0);
assert!(decode_into(&source[..BLOCK_BYTES], &mut output[..len]).is_err());
assert_eq!(output, [123.0; BLOCK_ELEMENTS * 2]);
}
decode_into(&[], &mut []).unwrap();
}
}
@@ -1,6 +1,6 @@
// iq3s_grid from ggml-common.h at Strata upstream d9ab8435f654c368c586340d490915f6addf56a3.
// Copyright (c) 2023-2026 The ggml authors. MIT License.
// See engine/strata/third_party/ggml/LICENSE for the full license text.
// See LICENSE-GGML in this crate for the full license text.
// This table is pinned to the imported upstream revision; do not regenerate silently.
pub const IQ3S_GRID: [u32; 512] = [
+57
View File
@@ -0,0 +1,57 @@
// iq3xxs_grid from llama.cpp 3cf03257f219afbe7334045ff7c6a06ac68c627d ggml-common.h.
// Copyright (c) 2023-2026 The ggml authors. MIT License.
// See LICENSE-GGML in this crate for the full notice.
// SHA256 of exact little-endian entry bytes: 46e35f5a997efdee6c99ce57854c8a0d4f0ff8ca57e5e8a60c0793ea580acf5d.
// Pinned source import; do not regenerate or replace silently.
pub(crate) const IQ3XXS_GRID: [u32; 256] = [
0x04040404, 0x04040414, 0x04040424, 0x04040c0c, 0x04040c1c, 0x04040c3e, 0x04041404, 0x04041414,
0x04041c0c, 0x04042414, 0x04043e1c, 0x04043e2c, 0x040c040c, 0x040c041c, 0x040c0c04, 0x040c0c14,
0x040c140c, 0x040c142c, 0x040c1c04, 0x040c1c14, 0x040c240c, 0x040c2c24, 0x040c3e04, 0x04140404,
0x04140414, 0x04140424, 0x04140c0c, 0x04141404, 0x04141414, 0x04141c0c, 0x04141c1c, 0x04141c3e,
0x04142c0c, 0x04142c3e, 0x04143e2c, 0x041c040c, 0x041c043e, 0x041c0c04, 0x041c0c14, 0x041c142c,
0x041c3e04, 0x04240c1c, 0x04241c3e, 0x04242424, 0x04242c3e, 0x04243e1c, 0x04243e2c, 0x042c040c,
0x042c043e, 0x042c1c14, 0x042c2c14, 0x04341c2c, 0x04343424, 0x043e0c04, 0x043e0c24, 0x043e0c34,
0x043e241c, 0x043e340c, 0x0c04040c, 0x0c04041c, 0x0c040c04, 0x0c040c14, 0x0c04140c, 0x0c04141c,
0x0c041c04, 0x0c041c14, 0x0c041c24, 0x0c04243e, 0x0c042c04, 0x0c0c0404, 0x0c0c0414, 0x0c0c0c0c,
0x0c0c1404, 0x0c0c1414, 0x0c14040c, 0x0c14041c, 0x0c140c04, 0x0c140c14, 0x0c14140c, 0x0c141c04,
0x0c143e14, 0x0c1c0404, 0x0c1c0414, 0x0c1c1404, 0x0c1c1c0c, 0x0c1c2434, 0x0c1c3434, 0x0c24040c,
0x0c24042c, 0x0c242c04, 0x0c2c1404, 0x0c2c1424, 0x0c2c2434, 0x0c2c3e0c, 0x0c34042c, 0x0c3e1414,
0x0c3e2404, 0x14040404, 0x14040414, 0x14040c0c, 0x14040c1c, 0x14041404, 0x14041414, 0x14041434,
0x14041c0c, 0x14042414, 0x140c040c, 0x140c041c, 0x140c042c, 0x140c0c04, 0x140c0c14, 0x140c140c,
0x140c1c04, 0x140c341c, 0x140c343e, 0x140c3e04, 0x14140404, 0x14140414, 0x14140c0c, 0x14140c3e,
0x14141404, 0x14141414, 0x14141c3e, 0x14142404, 0x14142c2c, 0x141c040c, 0x141c0c04, 0x141c0c24,
0x141c3e04, 0x141c3e24, 0x14241c2c, 0x14242c1c, 0x142c041c, 0x142c143e, 0x142c240c, 0x142c3e24,
0x143e040c, 0x143e041c, 0x143e0c34, 0x143e242c, 0x1c04040c, 0x1c040c04, 0x1c040c14, 0x1c04140c,
0x1c04141c, 0x1c042c04, 0x1c04342c, 0x1c043e14, 0x1c0c0404, 0x1c0c0414, 0x1c0c1404, 0x1c0c1c0c,
0x1c0c2424, 0x1c0c2434, 0x1c14040c, 0x1c14041c, 0x1c140c04, 0x1c14142c, 0x1c142c14, 0x1c143e14,
0x1c1c0c0c, 0x1c1c1c1c, 0x1c241c04, 0x1c24243e, 0x1c243e14, 0x1c2c0404, 0x1c2c0434, 0x1c2c1414,
0x1c2c2c2c, 0x1c340c24, 0x1c341c34, 0x1c34341c, 0x1c3e1c1c, 0x1c3e3404, 0x24040424, 0x24040c3e,
0x24041c2c, 0x24041c3e, 0x24042c1c, 0x24042c3e, 0x240c3e24, 0x24141404, 0x24141c3e, 0x24142404,
0x24143404, 0x24143434, 0x241c043e, 0x241c242c, 0x24240424, 0x24242c0c, 0x24243424, 0x242c142c,
0x242c241c, 0x242c3e04, 0x243e042c, 0x243e0c04, 0x243e0c14, 0x243e1c04, 0x2c040c14, 0x2c04240c,
0x2c043e04, 0x2c0c0404, 0x2c0c0434, 0x2c0c1434, 0x2c0c2c2c, 0x2c140c24, 0x2c141c14, 0x2c143e14,
0x2c1c0414, 0x2c1c2c1c, 0x2c240c04, 0x2c24141c, 0x2c24143e, 0x2c243e14, 0x2c2c0414, 0x2c2c1c0c,
0x2c342c04, 0x2c3e1424, 0x2c3e2414, 0x34041424, 0x34042424, 0x34042434, 0x34043424, 0x340c140c,
0x340c340c, 0x34140c3e, 0x34143424, 0x341c1c04, 0x341c1c34, 0x34242424, 0x342c042c, 0x342c2c14,
0x34341c1c, 0x343e041c, 0x343e140c, 0x3e04041c, 0x3e04042c, 0x3e04043e, 0x3e040c04, 0x3e041c14,
0x3e042c14, 0x3e0c1434, 0x3e0c2404, 0x3e140c14, 0x3e14242c, 0x3e142c14, 0x3e1c0404, 0x3e1c0c2c,
0x3e1c1c1c, 0x3e1c3404, 0x3e24140c, 0x3e24240c, 0x3e2c0404, 0x3e2c0414, 0x3e2c1424, 0x3e341c04,
];
// ksigns_iq2xs from llama.cpp 3cf03257f219afbe7334045ff7c6a06ac68c627d ggml-common.h.
// Copyright (c) 2023-2026 The ggml authors. MIT License.
// See LICENSE-GGML in this crate for the full notice.
// SHA256 of exact entry bytes: a76742a603f8beca5212ecce0f1f02f11a4887fd2f7c8b15aca0ea3eb3380c31.
// Pinned source import; do not regenerate or replace silently.
pub(crate) const KSIGNS_IQ2XS: [u8; 128] = [
0x00, 0x81, 0x82, 0x03, 0x84, 0x05, 0x06, 0x87, 0x88, 0x09, 0x0a, 0x8b, 0x0c, 0x8d, 0x8e, 0x0f,
0x90, 0x11, 0x12, 0x93, 0x14, 0x95, 0x96, 0x17, 0x18, 0x99, 0x9a, 0x1b, 0x9c, 0x1d, 0x1e, 0x9f,
0xa0, 0x21, 0x22, 0xa3, 0x24, 0xa5, 0xa6, 0x27, 0x28, 0xa9, 0xaa, 0x2b, 0xac, 0x2d, 0x2e, 0xaf,
0x30, 0xb1, 0xb2, 0x33, 0xb4, 0x35, 0x36, 0xb7, 0xb8, 0x39, 0x3a, 0xbb, 0x3c, 0xbd, 0xbe, 0x3f,
0xc0, 0x41, 0x42, 0xc3, 0x44, 0xc5, 0xc6, 0x47, 0x48, 0xc9, 0xca, 0x4b, 0xcc, 0x4d, 0x4e, 0xcf,
0x50, 0xd1, 0xd2, 0x53, 0xd4, 0x55, 0x56, 0xd7, 0xd8, 0x59, 0x5a, 0xdb, 0x5c, 0xdd, 0xde, 0x5f,
0x60, 0xe1, 0xe2, 0x63, 0xe4, 0x65, 0x66, 0xe7, 0xe8, 0x69, 0x6a, 0xeb, 0x6c, 0xed, 0xee, 0x6f,
0xf0, 0x71, 0x72, 0xf3, 0x74, 0xf5, 0xf6, 0x77, 0x78, 0xf9, 0xfa, 0x7b, 0xfc, 0x7d, 0x7e, 0xff,
];
+122
View File
@@ -0,0 +1,122 @@
//! Bounded CPU decoding of GGML IQ4_NL blocks (32 values / 18 bytes).
//! Layout and codebook follow llama.cpp 3cf03257f219afbe7334045ff7c6a06ac68c627d
//! `ggml-quants.c::dequantize_row_iq4_nl` and `ggml-common.h::kvalues_iq4nl`.
//! The table is MIT licensed by the ggml authors; see ../LICENSE-GGML.
//! Nonfinite scales are propagated, matching this preparation format's C path.
use crate::f16_bits_to_f32;
pub const BLOCK_BYTES: usize = 18;
pub const BLOCK_ELEMENTS: usize = 32;
pub(crate) const VALUES: [i8; 16] = [
-127, -104, -83, -65, -49, -35, -22, -10, 1, 13, 25, 38, 53, 69, 89, 113,
];
/// Decode one complete block. Every FP16 scale encoding is admitted, including
/// NaN and infinity; consumers retain responsibility for their value policy.
pub fn decode_block(block: &[u8; BLOCK_BYTES]) -> Result<[f32; BLOCK_ELEMENTS], String> {
let scale = f16_bits_to_f32(u16::from_le_bytes([block[0], block[1]]));
let mut output = [0.0; BLOCK_ELEMENTS];
for (index, packed) in block[2..].iter().enumerate() {
output[index] = scale * f32::from(VALUES[usize::from(packed & 15)]);
output[index + BLOCK_ELEMENTS / 2] = scale * f32::from(VALUES[usize::from(packed >> 4)]);
}
Ok(output)
}
/// Decode complete blocks into an exactly sized caller-owned output slice.
/// Shape errors are rejected before any output is written. Empty slices form a
/// valid zero-block operation. No alignment requirement or heap buffer is used.
pub fn decode_into(blocks: &[u8], output: &mut [f32]) -> Result<(), String> {
if !blocks.len().is_multiple_of(BLOCK_BYTES)
|| (blocks.len() / BLOCK_BYTES)
.checked_mul(BLOCK_ELEMENTS)
.is_none_or(|expected| expected != output.len())
{
return Err("IQ4_NL block and output lengths do not match".into());
}
for (block, values) in blocks
.as_chunks::<BLOCK_BYTES>()
.0
.iter()
.zip(output.as_chunks_mut::<BLOCK_ELEMENTS>().0.iter_mut())
{
values.copy_from_slice(&decode_block(block)?);
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn split_half_order_matches_independent_codebook_values() {
let mut block = [0u8; BLOCK_BYTES];
block[..2].copy_from_slice(&0x3800u16.to_le_bytes());
for (index, packed) in block[2..].iter_mut().enumerate() {
*packed = index as u8 | ((15 - index as u8) << 4);
}
let expected = [
-63.5, -52.0, -41.5, -32.5, -24.5, -17.5, -11.0, -5.0, 0.5, 6.5, 12.5, 19.0, 26.5,
34.5, 44.5, 56.5, 56.5, 44.5, 34.5, 26.5, 19.0, 12.5, 6.5, 0.5, -5.0, -11.0, -17.5,
-24.5, -32.5, -41.5, -52.0, -63.5,
];
let actual = decode_block(&block).unwrap();
assert_eq!(actual, expected);
let blocks = block.repeat(2);
let mut output = [0.0; BLOCK_ELEMENTS * 2];
decode_into(&blocks, &mut output).unwrap();
assert_eq!(&output[..BLOCK_ELEMENTS], &expected);
assert_eq!(&output[BLOCK_ELEMENTS..], &expected);
}
#[test]
fn malformed_shapes_leave_output_untouched() {
let blocks = [0u8; BLOCK_BYTES * 2];
for source_len in [1, BLOCK_BYTES - 1, BLOCK_BYTES + 1, blocks.len() - 1] {
let mut output = [123.0; BLOCK_ELEMENTS * 2];
assert!(decode_into(&blocks[..source_len], &mut output).is_err());
assert_eq!(output, [123.0; BLOCK_ELEMENTS * 2]);
}
for output_len in [
0,
BLOCK_ELEMENTS - 1,
BLOCK_ELEMENTS + 1,
BLOCK_ELEMENTS * 2,
] {
let mut output = [123.0; BLOCK_ELEMENTS * 2];
assert!(decode_into(&blocks[..BLOCK_BYTES], &mut output[..output_len]).is_err());
assert_eq!(output, [123.0; BLOCK_ELEMENTS * 2]);
}
let mut output = [123.0; BLOCK_ELEMENTS];
assert!(decode_into(&[], &mut output).is_err());
assert_eq!(output, [123.0; BLOCK_ELEMENTS]);
decode_into(&[], &mut []).unwrap();
}
#[test]
fn signed_zero_and_nonfinite_scales_are_admitted() {
let mut block = [0u8; BLOCK_BYTES];
block[2..].fill(0x80); // Negative low codepoint; positive high codepoint.
for (scale, low, high) in [(0x0000u16, 0x8000_0000, 0), (0x8000, 0, 0x8000_0000)] {
block[..2].copy_from_slice(&scale.to_le_bytes());
let output = decode_block(&block).unwrap();
assert_eq!(output[0].to_bits(), low);
assert_eq!(output[16].to_bits(), high);
}
for scale in [0x7c00u16, 0xfc00, 0x7c01, 0xfc01, 0x7e00, 0xfe00] {
block[..2].copy_from_slice(&scale.to_le_bytes());
let mut output = [0.0; BLOCK_ELEMENTS];
decode_into(&block, &mut output).unwrap();
if scale & 0x03ff == 0 {
assert!(output.iter().all(|value| value.is_infinite()));
assert_eq!(output[0].is_sign_negative(), scale & 0x8000 == 0);
assert_eq!(output[16].is_sign_negative(), scale & 0x8000 != 0);
} else {
assert!(output.iter().all(|value| value.is_nan()));
}
}
}
}
+188
View File
@@ -0,0 +1,188 @@
//! Bounded CPU decoding of GGML IQ4_XS blocks (256 values / 136 bytes).
//! Layout and arithmetic follow llama.cpp
//! 3cf03257f219afbe7334045ff7c6a06ac68c627d, `dequantize_row_iq4_xs`.
//! Uses the pinned IQ4_NL codebook (MIT, ggml authors; see ../LICENSE-GGML).
//! All FP16 scale encodings are admitted, including infinity and NaN.
use crate::{f16_bits_to_f32, iq4_nl::VALUES};
pub const BLOCK_BYTES: usize = 136;
pub const BLOCK_ELEMENTS: usize = 256;
/// Decode one complete block. Consumer nonfinite-value policy is unchanged:
/// infinity times a zero subblock multiplier produces NaN, as in pinned C.
pub fn decode_block(block: &[u8; BLOCK_BYTES]) -> Result<[f32; BLOCK_ELEMENTS], String> {
let base = f16_bits_to_f32(u16::from_le_bytes([block[0], block[1]]));
let high = u16::from_le_bytes([block[2], block[3]]);
let mut output = [0.0; BLOCK_ELEMENTS];
for subblock in 0..8 {
let low = (block[4 + subblock / 2] >> (4 * (subblock % 2))) & 15;
let upper = ((high >> (2 * subblock)) & 3) as u8;
let multiplier = i32::from(low | (upper << 4)) - 32;
// Retain the C intermediate and multiplication order, including zero
// signs and infinity * zero. Do not combine these two multiplications.
let scale = base * multiplier as f32;
for index in 0..16 {
let packed = block[8 + 16 * subblock + index];
output[32 * subblock + index] = scale * f32::from(VALUES[usize::from(packed & 15)]);
output[32 * subblock + index + 16] =
scale * f32::from(VALUES[usize::from(packed >> 4)]);
}
}
Ok(output)
}
/// Decode into caller-owned storage without heap buffers or alignment needs.
/// Invalid shapes are rejected before any write; empty slices are a valid
/// zero-block operation. Each source block must have exactly 256 output values.
pub fn decode_into(blocks: &[u8], output: &mut [f32]) -> Result<(), String> {
if !blocks.len().is_multiple_of(BLOCK_BYTES)
|| (blocks.len() / BLOCK_BYTES)
.checked_mul(BLOCK_ELEMENTS)
.is_none_or(|expected| expected != output.len())
{
return Err("IQ4_XS block and output lengths do not match".into());
}
for (block, values) in blocks
.as_chunks::<BLOCK_BYTES>()
.0
.iter()
.zip(output.as_chunks_mut::<BLOCK_ELEMENTS>().0.iter_mut())
{
values.copy_from_slice(&decode_block(block)?);
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
fn known_block(scale_bits: u16) -> [u8; BLOCK_BYTES] {
let mut block = [0u8; BLOCK_BYTES];
block[..2].copy_from_slice(&scale_bits.to_le_bytes());
// Explicit wire bytes: six-bit scales [0,15,16,31,32,33,48,63], hence
// multipliers [-32,-17,-16,-1,0,1,16,31]. High bits are LE 0xfa50.
block[2..8].copy_from_slice(&[0x50, 0xfa, 0xf0, 0xf0, 0x10, 0xf0]);
for subblock in 0..8 {
for index in 0..16 {
block[8 + 16 * subblock + index] = index as u8 | ((15 - index as u8) << 4);
}
}
block
}
#[test]
fn known_scale_bytes_and_split_half_values_match() {
let block = known_block(0x3800); // 0.5
let actual = decode_block(&block).unwrap();
// Expected scales and codebook values independently spelled out, not
// unpacked with the decoder's shifts or shared table.
let scales = [-16.0f32, -8.5, -8.0, -0.5, 0.0, 0.5, 8.0, 15.5];
let codepoints = [
-127.0f32, -104.0, -83.0, -65.0, -49.0, -35.0, -22.0, -10.0, 1.0, 13.0, 25.0, 38.0,
53.0, 69.0, 89.0, 113.0,
];
for (subblock, scale) in scales.into_iter().enumerate() {
for (index, codepoint) in codepoints.into_iter().enumerate() {
assert_eq!(
actual[32 * subblock + index].to_bits(),
(scale * codepoint).to_bits()
);
assert_eq!(
actual[32 * subblock + 31 - index].to_bits(),
(scale * codepoint).to_bits()
);
}
}
assert_eq!(actual[0], 2032.0);
assert_eq!(actual[32], 1079.5);
assert_eq!(actual[224], -1968.5);
assert_eq!(actual[240], 1751.5);
}
#[test]
fn bulk_handles_unaligned_blocks_and_rejects_shapes_before_writes() {
let blocks = [known_block(0x3800), known_block(0xbc00)];
let mut storage = vec![0u8; BLOCK_BYTES * 2 + 16];
let start = storage.as_ptr().align_offset(16) + 1;
let source = &mut storage[start..start + BLOCK_BYTES * 2];
assert_eq!(source.as_ptr().align_offset(16), 15);
source[..BLOCK_BYTES].copy_from_slice(&blocks[0]);
source[BLOCK_BYTES..].copy_from_slice(&blocks[1]);
let mut output = [123.0; BLOCK_ELEMENTS * 2];
decode_into(source, &mut output).unwrap();
for (number, block) in blocks.iter().enumerate() {
let single = decode_block(block).unwrap();
for (index, value) in single.into_iter().enumerate() {
assert_eq!(
output[number * BLOCK_ELEMENTS + index].to_bits(),
value.to_bits()
);
}
}
for source_len in [0, 1, BLOCK_BYTES - 1, BLOCK_BYTES + 1, source.len() - 1] {
output.fill(123.0);
assert!(decode_into(&source[..source_len], &mut output).is_err());
assert_eq!(output, [123.0; BLOCK_ELEMENTS * 2]);
}
for output_len in [
0,
BLOCK_ELEMENTS - 1,
BLOCK_ELEMENTS + 1,
BLOCK_ELEMENTS * 2,
] {
output.fill(123.0);
assert!(decode_into(&source[..BLOCK_BYTES], &mut output[..output_len]).is_err());
assert_eq!(output, [123.0; BLOCK_ELEMENTS * 2]);
}
decode_into(&[], &mut []).unwrap();
}
#[test]
fn signed_zero_keeps_both_multiplication_signs() {
for scale_bits in [0x0000u16, 0x8000] {
let actual = decode_block(&known_block(scale_bits)).unwrap();
for (subblock, multiplier_negative) in
[true, true, true, true, false, false, false, false]
.into_iter()
.enumerate()
{
let negative_scale = (scale_bits == 0x8000) ^ multiplier_negative;
assert_eq!(
actual[32 * subblock].to_bits(),
if negative_scale { 0 } else { 0x8000_0000 }
);
assert_eq!(
actual[32 * subblock + 16].to_bits(),
if negative_scale { 0x8000_0000 } else { 0 }
);
}
}
}
#[test]
fn nonfinite_scales_propagate_including_infinity_times_zero() {
for scale_bits in [0x7c00u16, 0xfc00, 0x7c01, 0xfc01, 0x7e00, 0xfe00] {
let block = known_block(scale_bits);
let mut output = [0.0; BLOCK_ELEMENTS];
decode_into(&block, &mut output).unwrap();
let single = decode_block(&block).unwrap();
for subblock in 0..8 {
for element in 0..32 {
let index = 32 * subblock + element;
if scale_bits & 0x03ff != 0 || subblock == 4 {
assert!(output[index].is_nan() && single[index].is_nan());
} else {
assert!(output[index].is_infinite() && single[index].is_infinite());
let negative = (scale_bits & 0x8000 != 0)
^ (subblock < 4)
^ !(8..24).contains(&element);
assert_eq!(output[index].is_sign_negative(), negative);
assert_eq!(single[index].is_sign_negative(), negative);
}
}
}
}
}
}
+44
View File
@@ -0,0 +1,44 @@
//! Crate-private Q4_K/Q5_K six-bit scale/minimum unpacking. Mirrors
//! `get_scale_min_k4` at llama.cpp 3cf03257f219afbe7334045ff7c6a06ac68c627d.
//! Original GGML source is MIT licensed; see ../LICENSE-GGML.
/// `subblock` is one of the eight 32-element subblocks in a complete K block.
pub(crate) fn scale_min(scales: &[u8; 12], subblock: usize) -> (u8, u8) {
if subblock < 4 {
(scales[subblock] & 63, scales[subblock + 4] & 63)
} else {
(
(scales[subblock + 4] & 15) | ((scales[subblock - 4] >> 6) << 4),
(scales[subblock + 4] >> 4) | ((scales[subblock] >> 6) << 4),
)
}
}
#[cfg(test)]
mod tests {
use super::scale_min;
#[test]
fn independent_packed_bytes_cover_both_scale_minimum_branches() {
let packed = [
0x41, 0x82, 0xc3, 0x04, 0x45, 0x86, 0xc7, 0x08, 0x21, 0x43, 0x65, 0x87,
];
let expected = [
(1, 5),
(2, 6),
(3, 7),
(4, 8),
(17, 18),
(35, 36),
(53, 54),
(7, 8),
];
for (subblock, pair) in expected.into_iter().enumerate() {
assert_eq!(scale_min(&packed, subblock), pair);
}
for subblock in 0..8 {
assert_eq!(scale_min(&[0; 12], subblock), (0, 0));
assert_eq!(scale_min(&[255; 12], subblock), (63, 63));
}
}
}
+60
View File
@@ -0,0 +1,60 @@
//! Pure Rust CPU quantization primitives for Leleka preparation tools.
//! No inference, GPU operation or complete model support is implied.
pub mod iq2_s;
mod iq2s_grid;
pub mod iq3_s;
pub mod iq3_xxs;
mod iq3s_grid;
mod iq3xxs_grid;
pub mod iq4_nl;
pub mod iq4_xs;
mod k_scale_min;
pub mod q2_0;
pub mod q4_k;
pub mod q5_k;
pub mod q6_k;
pub mod q8_0;
pub fn f16_bits_to_f32(bits: u16) -> f32 {
let sign = (u32::from(bits & 0x8000)) << 16;
let exponent = (bits >> 10) & 0x1f;
let mantissa = u32::from(bits & 0x03ff);
let result = match exponent {
0 if mantissa == 0 => sign,
0 => {
let leading = mantissa.leading_zeros() - 21;
let normalized = mantissa << leading;
sign | ((113 - leading) << 23) | ((normalized & 0x03ff) << 13)
}
31 => sign | 0x7f80_0000 | (mantissa << 13),
_ => sign | ((u32::from(exponent) + 112) << 23) | (mantissa << 13),
};
f32::from_bits(result)
}
#[cfg(test)]
mod tests {
use super::f16_bits_to_f32;
#[test]
fn binary16_boundaries_preserve_exact_binary32_bits() {
// Independent IEEE 754 encodings, including signed zero and NaN payloads.
for (half, single) in [
(0x0000, 0x0000_0000),
(0x8000, 0x8000_0000),
(0x0001, 0x3380_0000),
(0x03ff, 0x387f_c000),
(0x0400, 0x3880_0000),
(0x3c00, 0x3f80_0000),
(0xc000, 0xc000_0000),
(0x7bff, 0x477f_e000),
(0x7c00, 0x7f80_0000),
(0xfc00, 0xff80_0000),
(0x7c01, 0x7f80_2000),
(0xfe00, 0xffc0_0000),
] {
assert_eq!(f16_bits_to_f32(half).to_bits(), single);
}
}
}
+131
View File
@@ -0,0 +1,131 @@
//! Allocation-free CPU decoding of GGML Q2_0 blocks (64 values / 18 bytes).
//! Layout/arithmetic follow llama.cpp 3cf03257f219afbe7334045ff7c6a06ac68c627d
//! `dequantize_row_q2_0` / `block_q2_0` (MIT, ggml authors; ../LICENSE-GGML).
//! Every FP16 encoding is admitted, preserving consumer nonfinite policies.
use crate::f16_bits_to_f32;
pub const BLOCK_BYTES: usize = 18;
pub const BLOCK_ELEMENTS: usize = 64;
pub fn decode_block(block: &[u8; BLOCK_BYTES]) -> Result<[f32; BLOCK_ELEMENTS], String> {
let scale = f16_bits_to_f32(u16::from_le_bytes([block[0], block[1]]));
let mut output = [0.0; BLOCK_ELEMENTS];
for (element, value) in output.iter_mut().enumerate() {
let code = (block[2 + element / 4] >> (2 * (element % 4))) & 3;
let quant = i32::from(code) - 1;
*value = quant as f32 * scale;
}
Ok(output)
}
/// Invalid shapes fail before output writes. Empty slices form a zero-block
/// operation; decoding needs no alignment or heap buffer.
pub fn decode_into(blocks: &[u8], output: &mut [f32]) -> Result<(), String> {
if !blocks.len().is_multiple_of(BLOCK_BYTES)
|| (blocks.len() / BLOCK_BYTES)
.checked_mul(BLOCK_ELEMENTS)
.is_none_or(|expected| expected != output.len())
{
return Err("Q2_0 block and output lengths do not match".into());
}
for (block, values) in blocks
.as_chunks::<BLOCK_BYTES>()
.0
.iter()
.zip(output.as_chunks_mut::<BLOCK_ELEMENTS>().0.iter_mut())
{
values.copy_from_slice(&decode_block(block)?);
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn independent_wire_values_are_sequential_two_bit_fields() {
let mut block = [0u8; BLOCK_BYTES];
block[..2].copy_from_slice(&[0x00, 0x38]); // 0.5
block[2..].fill(0xe4); // 00,01,10,11 -> -1,0,1,2.
block[3] = 0x1b; // Reverse order.
block[17] = 0xff; // Last byte, all +2.
let output = decode_block(&block).unwrap();
assert_eq!(&output[..8], &[-0.5, 0.0, 0.5, 1.0, 1.0, 0.5, 0.0, -0.5]);
for quartet in output[8..60].as_chunks::<4>().0 {
assert_eq!(quartet, &[-0.5, 0.0, 0.5, 1.0]);
}
assert_eq!(&output[60..], &[1.0; 4]);
}
#[test]
fn unaligned_bulk_and_invalid_shapes_preserve_contract() {
let mut block = [0u8; BLOCK_BYTES];
block[..2].copy_from_slice(&0x3c00u16.to_le_bytes());
block[2..].fill(0xe4);
let mut storage = [0u8; 2 * BLOCK_BYTES + 16];
let start = storage.as_ptr().align_offset(16) + 1;
let source = &mut storage[start..start + 2 * BLOCK_BYTES];
assert_eq!(source.as_ptr().align_offset(16), 15);
source[..BLOCK_BYTES].copy_from_slice(&block);
source[BLOCK_BYTES..].copy_from_slice(&block);
let mut output = [123.0; 2 * BLOCK_ELEMENTS];
decode_into(source, &mut output).unwrap();
for quartet in output.as_chunks::<4>().0 {
assert_eq!(quartet, &[-1.0, 0.0, 1.0, 2.0]);
}
for length in [0, 1, BLOCK_BYTES - 1, BLOCK_BYTES + 1, source.len() - 1] {
output.fill(123.0);
assert!(decode_into(&source[..length], &mut output).is_err());
assert_eq!(output, [123.0; 2 * BLOCK_ELEMENTS]);
}
for length in [
0,
BLOCK_ELEMENTS - 1,
BLOCK_ELEMENTS + 1,
2 * BLOCK_ELEMENTS,
] {
output.fill(123.0);
assert!(decode_into(&source[..BLOCK_BYTES], &mut output[..length]).is_err());
assert_eq!(output, [123.0; 2 * BLOCK_ELEMENTS]);
}
decode_into(&[], &mut []).unwrap();
}
#[test]
fn signed_zero_and_nonfinite_scales_are_admitted() {
let mut block = [0u8; BLOCK_BYTES];
block[2..].fill(0xe4);
for (scale, expected) in [
(0x0000u16, [0x8000_0000u32, 0, 0, 0]),
(0x8000, [0, 0x8000_0000, 0x8000_0000, 0x8000_0000]),
] {
block[..2].copy_from_slice(&scale.to_le_bytes());
for quartet in decode_block(&block).unwrap().as_chunks::<4>().0 {
for (value, bits) in quartet.iter().zip(expected) {
assert_eq!(value.to_bits(), bits);
}
}
}
for scale in [0x7c00u16, 0xfc00, 0x7c01, 0xfc01, 0x7e00, 0xfe00] {
block[..2].copy_from_slice(&scale.to_le_bytes());
let mut output = [0.0; BLOCK_ELEMENTS];
decode_into(&block, &mut output).unwrap();
for quartet in output.as_chunks::<4>().0 {
if scale & 0x03ff != 0 {
assert!(quartet.iter().all(|v| v.is_nan()));
} else {
assert!(quartet[1].is_nan()); // Infinity times quant zero.
for index in [0, 2, 3] {
assert!(quartet[index].is_infinite());
assert_eq!(
quartet[index].is_sign_negative(),
(scale & 0x8000 != 0) ^ (index == 0)
);
}
}
}
}
}
}
+185
View File
@@ -0,0 +1,185 @@
//! Allocation-free CPU decoding of GGML Q4_K blocks (256 values / 144 bytes).
//! Layout and arithmetic follow llama.cpp 3cf03257f219afbe7334045ff7c6a06ac68c627d
//! `dequantize_row_q4_K` / `block_q4_K` (MIT, ggml authors; ../LICENSE-GGML).
//! All FP16 encodings are admitted; consumers retain their nonfinite policy.
use crate::{f16_bits_to_f32, k_scale_min::scale_min};
pub const BLOCK_BYTES: usize = 144;
pub const BLOCK_ELEMENTS: usize = 256;
pub fn decode_block(block: &[u8; BLOCK_BYTES]) -> Result<[f32; BLOCK_ELEMENTS], String> {
let base = f16_bits_to_f32(u16::from_le_bytes([block[0], block[1]]));
let minimum = f16_bits_to_f32(u16::from_le_bytes([block[2], block[3]]));
let scales: &[u8; 12] = block[4..16].try_into().expect("fixed Q4_K scale header");
let mut output = [0.0; BLOCK_ELEMENTS];
for pair in 0..4 {
let (s1, m1) = scale_min(scales, 2 * pair);
let (s2, m2) = scale_min(scales, 2 * pair + 1);
let d1 = base * f32::from(s1);
let min1 = minimum * f32::from(m1);
let d2 = base * f32::from(s2);
let min2 = minimum * f32::from(m2);
for lane in 0..32 {
let packed = block[16 + 32 * pair + lane];
// Preserve the C intermediate products and final subtraction.
output[64 * pair + lane] = d1 * f32::from(packed & 15) - min1;
output[64 * pair + lane + 32] = d2 * f32::from(packed >> 4) - min2;
}
}
Ok(output)
}
/// Shape errors leave all output untouched. Empty slices form a zero-block
/// operation; arbitrary source alignment is supported without a heap buffer.
pub fn decode_into(blocks: &[u8], output: &mut [f32]) -> Result<(), String> {
if !blocks.len().is_multiple_of(BLOCK_BYTES)
|| (blocks.len() / BLOCK_BYTES)
.checked_mul(BLOCK_ELEMENTS)
.is_none_or(|expected| expected != output.len())
{
return Err("Q4_K block and output lengths do not match".into());
}
for (block, values) in blocks
.as_chunks::<BLOCK_BYTES>()
.0
.iter()
.zip(output.as_chunks_mut::<BLOCK_ELEMENTS>().0.iter_mut())
{
values.copy_from_slice(&decode_block(block)?);
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
fn known_block() -> [u8; BLOCK_BYTES] {
let mut block = [0u8; BLOCK_BYTES];
block[..4].copy_from_slice(&[0x00, 0x38, 0x00, 0x34]); // d=0.5, dmin=0.25
block[4..16].copy_from_slice(&[
0x41, 0x82, 0xc3, 0x04, 0x45, 0x86, 0xc7, 0x08, 0x21, 0x43, 0x65, 0x87,
]);
for pair in 0..4 {
for lane in 0..32 {
block[16 + 32 * pair + lane] = (lane % 16) as u8 | (((15 - lane % 16) as u8) << 4);
}
}
block
}
#[test]
fn independent_wire_values_cover_scale_minimum_and_split_halves() {
let actual = decode_block(&known_block()).unwrap();
let scale = [0.5f32, 1.0, 1.5, 2.0, 8.5, 17.5, 26.5, 3.5];
let minimum = [1.25f32, 1.5, 1.75, 2.0, 4.5, 9.0, 13.5, 2.0];
for subblock in 0..8 {
for lane in 0..32 {
let quant = if subblock % 2 == 0 {
lane % 16
} else {
15 - lane % 16
} as f32;
assert_eq!(
actual[32 * subblock + lane].to_bits(),
(scale[subblock] * quant - minimum[subblock]).to_bits()
);
}
}
assert_eq!(actual[0], -1.25);
assert_eq!(actual[32], 13.5);
assert_eq!(actual[160], 253.5);
assert_eq!(actual[224], 50.5);
}
#[test]
fn bulk_unaligned_and_bad_shapes_preserve_output_contract() {
let block = known_block();
let mut storage = vec![0u8; 2 * BLOCK_BYTES + 16];
let start = storage.as_ptr().align_offset(16) + 1;
let source = &mut storage[start..start + 2 * BLOCK_BYTES];
assert_eq!(source.as_ptr().align_offset(16), 15);
source[..BLOCK_BYTES].copy_from_slice(&block);
source[BLOCK_BYTES..].copy_from_slice(&block);
let mut output = [123.0; 2 * BLOCK_ELEMENTS];
decode_into(source, &mut output).unwrap();
let expected = decode_block(&block).unwrap();
assert_eq!(&output[..BLOCK_ELEMENTS], &expected);
assert_eq!(&output[BLOCK_ELEMENTS..], &expected);
for length in [0, 1, BLOCK_BYTES - 1, BLOCK_BYTES + 1, source.len() - 1] {
output.fill(123.0);
assert!(decode_into(&source[..length], &mut output).is_err());
assert_eq!(output, [123.0; 2 * BLOCK_ELEMENTS]);
}
for length in [
0,
BLOCK_ELEMENTS - 1,
BLOCK_ELEMENTS + 1,
2 * BLOCK_ELEMENTS,
] {
output.fill(123.0);
assert!(decode_into(&source[..BLOCK_BYTES], &mut output[..length]).is_err());
assert_eq!(output, [123.0; 2 * BLOCK_ELEMENTS]);
}
decode_into(&[], &mut []).unwrap();
}
#[test]
fn signed_zero_and_nonfinite_arithmetic_is_admitted() {
let mut block = [0u8; BLOCK_BYTES];
block[4..16].copy_from_slice(&[1, 1, 1, 1, 1, 1, 1, 1, 0x11, 0x11, 0x11, 0x11]);
block[16..].fill(0x11);
for (d, min, expected) in [
(0u16, 0u16, 0u32),
(0x8000, 0, 0x8000_0000),
(0, 0x8000, 0),
(0x8000, 0x8000, 0),
] {
block[..2].copy_from_slice(&d.to_le_bytes());
block[2..4].copy_from_slice(&min.to_le_bytes());
assert!(
decode_block(&block)
.unwrap()
.iter()
.all(|v| v.to_bits() == expected)
);
}
for (d, min, expected_sign) in [
(0x7c00u16, 0x3c00u16, false),
(0xfc00, 0x3c00, true),
(0x3c00, 0x7c00, true),
(0x3c00, 0xfc00, false),
] {
block[..2].copy_from_slice(&d.to_le_bytes());
block[2..4].copy_from_slice(&min.to_le_bytes());
let mut output = [0.0; BLOCK_ELEMENTS];
decode_into(&block, &mut output).unwrap();
assert!(
output
.iter()
.all(|v| v.is_infinite() && v.is_sign_negative() == expected_sign)
);
}
for (d, min) in [
(0x7c00u16, 0x7c00u16),
(0xfc00, 0xfc00),
(0x7c01, 0x3c00),
(0x3c00, 0xfc01),
] {
block[..2].copy_from_slice(&d.to_le_bytes());
block[2..4].copy_from_slice(&min.to_le_bytes());
assert!(decode_block(&block).unwrap().iter().all(|v| v.is_nan()));
}
block[..2].copy_from_slice(&0x7c00u16.to_le_bytes());
block[2..4].fill(0);
block[16..].fill(0); // Infinity times quant zero.
assert!(decode_block(&block).unwrap().iter().all(|v| v.is_nan()));
block[16..].fill(0x11);
block[4..16].fill(0); // Infinity times scale zero.
assert!(decode_block(&block).unwrap().iter().all(|v| v.is_nan()));
block[..2].copy_from_slice(&0x3c00u16.to_le_bytes());
block[2..4].copy_from_slice(&0x7c00u16.to_le_bytes()); // Infinite minimum times zero.
assert!(decode_block(&block).unwrap().iter().all(|v| v.is_nan()));
}
}
+207
View File
@@ -0,0 +1,207 @@
//! Allocation-free CPU decoding of GGML Q5_K blocks (256 values / 176 bytes).
//! Layout and arithmetic follow llama.cpp 3cf03257f219afbe7334045ff7c6a06ac68c627d
//! `dequantize_row_q5_K` / `block_q5_K` (MIT, ggml authors; ../LICENSE-GGML).
//! All FP16 encodings are admitted; consumers retain their nonfinite policy.
use crate::{f16_bits_to_f32, k_scale_min::scale_min};
pub const BLOCK_BYTES: usize = 176;
pub const BLOCK_ELEMENTS: usize = 256;
pub fn decode_block(block: &[u8; BLOCK_BYTES]) -> Result<[f32; BLOCK_ELEMENTS], String> {
let base = f16_bits_to_f32(u16::from_le_bytes([block[0], block[1]]));
let minimum = f16_bits_to_f32(u16::from_le_bytes([block[2], block[3]]));
let scales: &[u8; 12] = block[4..16].try_into().expect("fixed Q5_K scale header");
let mut output = [0.0; BLOCK_ELEMENTS];
for pair in 0..4 {
let (s1, m1) = scale_min(scales, 2 * pair);
let (s2, m2) = scale_min(scales, 2 * pair + 1);
let d1 = base * f32::from(s1);
let min1 = minimum * f32::from(m1);
let d2 = base * f32::from(s2);
let min2 = minimum * f32::from(m2);
let low_mask = 1u8 << (2 * pair);
let high_mask = 2u8 << (2 * pair);
for lane in 0..32 {
let packed = block[48 + 32 * pair + lane];
// The same high-bit lane is reused across all four 64-value pairs;
// each pair selects a different bit for each 32-element half.
let high = block[16 + lane];
let low_quant = (packed & 15) + if high & low_mask != 0 { 16 } else { 0 };
let high_quant = (packed >> 4) + if high & high_mask != 0 { 16 } else { 0 };
output[64 * pair + lane] = d1 * f32::from(low_quant) - min1;
output[64 * pair + lane + 32] = d2 * f32::from(high_quant) - min2;
}
}
Ok(output)
}
/// Shape errors leave all output untouched. Empty slices form a zero-block
/// operation; arbitrary source alignment is supported without a heap buffer.
pub fn decode_into(blocks: &[u8], output: &mut [f32]) -> Result<(), String> {
if !blocks.len().is_multiple_of(BLOCK_BYTES)
|| (blocks.len() / BLOCK_BYTES)
.checked_mul(BLOCK_ELEMENTS)
.is_none_or(|expected| expected != output.len())
{
return Err("Q5_K block and output lengths do not match".into());
}
for (block, values) in blocks
.as_chunks::<BLOCK_BYTES>()
.0
.iter()
.zip(output.as_chunks_mut::<BLOCK_ELEMENTS>().0.iter_mut())
{
values.copy_from_slice(&decode_block(block)?);
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
fn known_block() -> [u8; BLOCK_BYTES] {
let mut block = [0u8; BLOCK_BYTES];
block[..4].copy_from_slice(&[0x00, 0x38, 0x00, 0x34]); // d=0.5, dmin=0.25
block[4..16].copy_from_slice(&[
0x41, 0x82, 0xc3, 0x04, 0x45, 0x86, 0xc7, 0x08, 0x21, 0x43, 0x65, 0x87,
]);
for lane in 0..32 {
block[16 + lane] = 1 << (lane % 8);
}
for pair in 0..4 {
for lane in 0..32 {
block[48 + 32 * pair + lane] = (lane % 16) as u8 | (((15 - lane % 16) as u8) << 4);
}
}
block
}
#[test]
fn independent_wire_values_cover_scale_minimum_nibbles_and_high_masks() {
let actual = decode_block(&known_block()).unwrap();
let scale = [0.5f32, 1.0, 1.5, 2.0, 8.5, 17.5, 26.5, 3.5];
let minimum = [1.25f32, 1.5, 1.75, 2.0, 4.5, 9.0, 13.5, 2.0];
for subblock in 0..8 {
for lane in 0..32 {
let nibble = if subblock % 2 == 0 {
lane % 16
} else {
15 - lane % 16
};
let high = if lane % 8 == subblock { 16 } else { 0 };
let expected = scale[subblock] * (nibble + high) as f32 - minimum[subblock];
assert_eq!(actual[32 * subblock + lane].to_bits(), expected.to_bits());
}
}
assert_eq!(actual[0], 6.75);
assert_eq!(actual[33], 28.5);
assert_eq!(actual[71], 8.75);
assert_eq!(actual[255], 54.0);
}
#[test]
fn each_high_bit_maps_only_to_its_32_element_subblock() {
let mut block = [0u8; BLOCK_BYTES];
block[..2].copy_from_slice(&0x3c00u16.to_le_bytes());
block[4..16].copy_from_slice(&[1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1]);
for bit in 0..8 {
block[16..48].fill(1 << bit);
let actual = decode_block(&block).unwrap();
for (element, value) in actual.into_iter().enumerate() {
assert_eq!(value, if element / 32 == bit { 16.0 } else { 0.0 });
}
}
}
#[test]
fn bulk_unaligned_and_bad_shapes_preserve_output_contract() {
let block = known_block();
let mut storage = vec![0u8; 2 * BLOCK_BYTES + 16];
let start = storage.as_ptr().align_offset(16) + 1;
let source = &mut storage[start..start + 2 * BLOCK_BYTES];
assert_eq!(source.as_ptr().align_offset(16), 15);
source[..BLOCK_BYTES].copy_from_slice(&block);
source[BLOCK_BYTES..].copy_from_slice(&block);
let mut output = [123.0; 2 * BLOCK_ELEMENTS];
decode_into(source, &mut output).unwrap();
let expected = decode_block(&block).unwrap();
assert_eq!(&output[..BLOCK_ELEMENTS], &expected);
assert_eq!(&output[BLOCK_ELEMENTS..], &expected);
for length in [0, 1, BLOCK_BYTES - 1, BLOCK_BYTES + 1, source.len() - 1] {
output.fill(123.0);
assert!(decode_into(&source[..length], &mut output).is_err());
assert_eq!(output, [123.0; 2 * BLOCK_ELEMENTS]);
}
for length in [
0,
BLOCK_ELEMENTS - 1,
BLOCK_ELEMENTS + 1,
2 * BLOCK_ELEMENTS,
] {
output.fill(123.0);
assert!(decode_into(&source[..BLOCK_BYTES], &mut output[..length]).is_err());
assert_eq!(output, [123.0; 2 * BLOCK_ELEMENTS]);
}
decode_into(&[], &mut []).unwrap();
}
#[test]
fn signed_zero_and_nonfinite_arithmetic_is_admitted() {
let mut block = [0u8; BLOCK_BYTES];
block[4..16].copy_from_slice(&[1, 1, 1, 1, 1, 1, 1, 1, 0x11, 0x11, 0x11, 0x11]);
block[48..].fill(0x11);
for (d, min, expected) in [
(0u16, 0u16, 0u32),
(0x8000, 0, 0x8000_0000),
(0, 0x8000, 0),
(0x8000, 0x8000, 0),
] {
block[..2].copy_from_slice(&d.to_le_bytes());
block[2..4].copy_from_slice(&min.to_le_bytes());
assert!(
decode_block(&block)
.unwrap()
.iter()
.all(|v| v.to_bits() == expected)
);
}
for (d, min, expected_sign) in [
(0x7c00u16, 0x3c00u16, false),
(0xfc00, 0x3c00, true),
(0x3c00, 0x7c00, true),
(0x3c00, 0xfc00, false),
] {
block[..2].copy_from_slice(&d.to_le_bytes());
block[2..4].copy_from_slice(&min.to_le_bytes());
let mut output = [0.0; BLOCK_ELEMENTS];
decode_into(&block, &mut output).unwrap();
assert!(
output
.iter()
.all(|v| v.is_infinite() && v.is_sign_negative() == expected_sign)
);
}
for (d, min) in [
(0x7c00u16, 0x7c00u16),
(0xfc00, 0xfc00),
(0x7c01, 0x3c00),
(0x3c00, 0xfc01),
] {
block[..2].copy_from_slice(&d.to_le_bytes());
block[2..4].copy_from_slice(&min.to_le_bytes());
assert!(decode_block(&block).unwrap().iter().all(|v| v.is_nan()));
}
block[..2].copy_from_slice(&0x7c00u16.to_le_bytes());
block[2..4].fill(0);
block[48..].fill(0); // Infinity times quant zero.
assert!(decode_block(&block).unwrap().iter().all(|v| v.is_nan()));
block[48..].fill(0x11);
block[4..16].fill(0); // Infinity times scale zero.
assert!(decode_block(&block).unwrap().iter().all(|v| v.is_nan()));
block[..2].copy_from_slice(&0x3c00u16.to_le_bytes());
block[2..4].copy_from_slice(&0x7c00u16.to_le_bytes()); // Infinite minimum times zero.
assert!(decode_block(&block).unwrap().iter().all(|v| v.is_nan()));
}
}
+223
View File
@@ -0,0 +1,223 @@
//! Allocation-free CPU decoding of GGML Q6_K blocks (256 values / 210 bytes).
//! Layout/arithmetic follow llama.cpp 3cf03257f219afbe7334045ff7c6a06ac68c627d
//! `dequantize_row_q6_K` / `block_q6_K` (MIT, ggml authors; ../LICENSE-GGML).
//! Every FP16 encoding is admitted, preserving consumer nonfinite policies.
use crate::f16_bits_to_f32;
pub const BLOCK_BYTES: usize = 210;
pub const BLOCK_ELEMENTS: usize = 256;
pub fn decode_block(block: &[u8; BLOCK_BYTES]) -> Result<[f32; BLOCK_ELEMENTS], String> {
let base = f16_bits_to_f32(u16::from_le_bytes([block[208], block[209]]));
let mut output = [0.0; BLOCK_ELEMENTS];
for half in 0..2 {
for lane in 0..32 {
let low1 = block[64 * half + lane];
let low2 = block[64 * half + lane + 32];
let high = block[128 + 32 * half + lane];
let quants = [
((low1 & 15) | ((high & 3) << 4)) as i8 - 32,
((low2 & 15) | (((high >> 2) & 3) << 4)) as i8 - 32,
((low1 >> 4) | (((high >> 4) & 3) << 4)) as i8 - 32,
((low2 >> 4) | (((high >> 6) & 3) << 4)) as i8 - 32,
];
for (quadrant, quant) in quants.into_iter().enumerate() {
let scale = block[192 + 8 * half + 2 * quadrant + lane / 16] as i8;
// Preserve the C intermediate multiplication before the quant
// multiply, including infinity times zero producing NaN.
let scaled = base * f32::from(scale);
output[128 * half + 32 * quadrant + lane] = scaled * f32::from(quant);
}
}
}
Ok(output)
}
/// Invalid shapes fail before output writes. Empty slices form a zero-block
/// operation; decoding needs no alignment or heap buffer.
pub fn decode_into(blocks: &[u8], output: &mut [f32]) -> Result<(), String> {
if !blocks.len().is_multiple_of(BLOCK_BYTES)
|| (blocks.len() / BLOCK_BYTES)
.checked_mul(BLOCK_ELEMENTS)
.is_none_or(|expected| expected != output.len())
{
return Err("Q6_K block and output lengths do not match".into());
}
for (block, values) in blocks
.as_chunks::<BLOCK_BYTES>()
.0
.iter()
.zip(output.as_chunks_mut::<BLOCK_ELEMENTS>().0.iter_mut())
{
values.copy_from_slice(&decode_block(block)?);
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
fn known_block(scale_bits: u16) -> [u8; BLOCK_BYTES] {
let mut block = [0u8; BLOCK_BYTES];
block[..64].fill(0xa1);
block[64..128].fill(0x4f);
block[128..160].fill(0xe4);
block[160..192].fill(0x1b);
let scales = [
-128i8, -3, -1, 0, 1, 2, 63, 127, -127, -64, -2, 1, 3, 4, 64, 126,
];
for (byte, scale) in block[192..208].iter_mut().zip(scales) {
*byte = scale as u8;
}
block[208..].copy_from_slice(&scale_bits.to_le_bytes());
block
}
#[test]
fn independent_expected_values_cover_signed_scales_halves_and_quadrants() {
let output = decode_block(&known_block(0x3800)).unwrap(); // d=0.5
// First-half quants [-31,-15,10,26]; second [31,15,-12,-28].
// Independently calculated values for each 16-element scale group.
let expected = [
1984.0f32, 46.5, 7.5, -0.0, 5.0, 10.0, 819.0, 1651.0, -1968.5, -992.0, -15.0, 7.5,
-18.0, -24.0, -896.0, -1764.0,
];
for (group, expected) in output.as_chunks::<16>().0.iter().zip(expected) {
assert!(
group
.iter()
.all(|value| value.to_bits() == expected.to_bits())
);
}
}
#[test]
fn single_packed_bits_map_to_exact_lanes_in_both_halves() {
let mut block = [0u8; BLOCK_BYTES];
block[192..208].fill(1);
block[208..].copy_from_slice(&0x3c00u16.to_le_bytes());
for position in 0..128 {
for (bit, quadrant_delta) in [(1u8, 0), (16, 2)] {
block[position] = bit;
let output = decode_block(&block).unwrap();
let half = position / 64;
let local = position % 64;
let quadrant = local / 32 + quadrant_delta;
let changed = 128 * half + 32 * quadrant + local % 32;
for (element, value) in output.into_iter().enumerate() {
assert_eq!(value, if element == changed { -31.0 } else { -32.0 });
}
block[position] = 0;
}
}
for position in 0..64 {
for quadrant in 0..4 {
block[128 + position] = 1 << (2 * quadrant);
let output = decode_block(&block).unwrap();
let changed = 128 * (position / 32) + 32 * quadrant + position % 32;
for (element, value) in output.into_iter().enumerate() {
assert_eq!(value, if element == changed { -16.0 } else { -32.0 });
}
block[128 + position] = 0;
}
}
}
#[test]
fn unaligned_bulk_and_invalid_shapes_preserve_contract() {
let block = known_block(0x3800);
let mut storage = vec![0u8; 2 * BLOCK_BYTES + 16];
let start = storage.as_ptr().align_offset(16) + 1;
let source = &mut storage[start..start + 2 * BLOCK_BYTES];
assert_eq!(source.as_ptr().align_offset(16), 15);
source[..BLOCK_BYTES].copy_from_slice(&block);
source[BLOCK_BYTES..].copy_from_slice(&block);
let mut output = [123.0; 2 * BLOCK_ELEMENTS];
decode_into(source, &mut output).unwrap();
let expected = decode_block(&block).unwrap();
for (value, expected) in output.iter().zip(expected.into_iter().cycle()) {
assert_eq!(value.to_bits(), expected.to_bits());
}
for length in [0, 1, BLOCK_BYTES - 1, BLOCK_BYTES + 1, source.len() - 1] {
output.fill(123.0);
assert!(decode_into(&source[..length], &mut output).is_err());
assert_eq!(output, [123.0; 2 * BLOCK_ELEMENTS]);
}
for length in [
0,
BLOCK_ELEMENTS - 1,
BLOCK_ELEMENTS + 1,
2 * BLOCK_ELEMENTS,
] {
output.fill(123.0);
assert!(decode_into(&source[..BLOCK_BYTES], &mut output[..length]).is_err());
assert_eq!(output, [123.0; 2 * BLOCK_ELEMENTS]);
}
decode_into(&[], &mut []).unwrap();
}
#[test]
fn signed_zero_preserves_signed_scale_and_quant_multiplications() {
let signs = [
false, false, false, true, false, false, false, false, true, true, true, false, true,
true, true, true,
];
for scale in [0x0000u16, 0x8000] {
let output = decode_block(&known_block(scale)).unwrap();
for (group, negative) in output.as_chunks::<16>().0.iter().zip(signs) {
let bits = if negative ^ (scale == 0x8000) {
0x8000_0000
} else {
0
};
assert!(group.iter().all(|value| value.to_bits() == bits));
}
}
}
#[test]
fn nonfinite_scales_zero_subscales_and_zero_quants_are_admitted() {
let signs = [
false, false, false, true, false, false, false, false, true, true, true, false, true,
true, true, true,
];
for scale in [0x7c00u16, 0xfc00, 0x7c01, 0xfc01, 0x7e00, 0xfe00] {
let block = known_block(scale);
let mut output = [0.0; BLOCK_ELEMENTS];
decode_into(&block, &mut output).unwrap();
for (index, (group, negative)) in
output.as_chunks::<16>().0.iter().zip(signs).enumerate()
{
if scale & 0x03ff != 0 || index == 3 {
assert!(group.iter().all(|value| value.is_nan()));
} else {
let sign = negative ^ (scale & 0x8000 != 0);
assert!(
group
.iter()
.all(|value| value.is_infinite() && value.is_sign_negative() == sign)
);
}
}
let mut zero_quant = block;
zero_quant[..128].fill(0);
zero_quant[128..192].fill(0xaa); // Every six-bit code is 32, hence quant zero.
assert!(
decode_block(&zero_quant)
.unwrap()
.iter()
.all(|value| value.is_nan())
);
let mut zero_subscale = block;
zero_subscale[192..208].fill(0);
assert!(
decode_block(&zero_subscale)
.unwrap()
.iter()
.all(|value| value.is_nan())
);
}
}
}
+124
View File
@@ -0,0 +1,124 @@
//! Bounded CPU decoding of GGML Q8_0 blocks (32 values / 34 bytes).
//! Layout/arithmetic follow llama.cpp 3cf03257f219afbe7334045ff7c6a06ac68c627d
//! `ggml-common.h::block_q8_0` and `ggml-quants.c::dequantize_row_q8_0`.
//! Original GGML code is MIT licensed; see ../LICENSE-GGML.
//! Nonfinite scales propagate, preserving the existing preparation C path.
use crate::f16_bits_to_f32;
pub const BLOCK_BYTES: usize = 34;
pub const BLOCK_ELEMENTS: usize = 32;
/// Decode one block, retaining signed int8 conversion and C multiplication order.
/// All binary16 scale encodings are admitted, including NaN and infinity.
pub fn decode_block(block: &[u8; BLOCK_BYTES]) -> Result<[f32; BLOCK_ELEMENTS], String> {
let scale = f16_bits_to_f32(u16::from_le_bytes([block[0], block[1]]));
let mut output = [0.0; BLOCK_ELEMENTS];
for (value, quant) in output.iter_mut().zip(&block[2..]) {
*value = f32::from(*quant as i8) * scale;
}
Ok(output)
}
/// Shape errors leave all output untouched. Empty input/output is a valid
/// zero-block operation; arbitrary input alignment is supported without allocation.
pub fn decode_into(blocks: &[u8], output: &mut [f32]) -> Result<(), String> {
if !blocks.len().is_multiple_of(BLOCK_BYTES)
|| (blocks.len() / BLOCK_BYTES)
.checked_mul(BLOCK_ELEMENTS)
.is_none_or(|expected| expected != output.len())
{
return Err("Q8_0 block and output lengths do not match".into());
}
for (block, values) in blocks
.as_chunks::<BLOCK_BYTES>()
.0
.iter()
.zip(output.as_chunks_mut::<BLOCK_ELEMENTS>().0.iter_mut())
{
values.copy_from_slice(&decode_block(block)?);
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn signed_int8_boundaries_and_lane_order_match_known_values() {
let mut block = [0u8; BLOCK_BYTES];
block[..2].copy_from_slice(&0x3800u16.to_le_bytes());
block[2..8].copy_from_slice(&[0, 1, 127, 128, 255, 129]);
block[33] = 42;
let output = decode_block(&block).unwrap();
assert_eq!(&output[..6], &[0.0, 0.5, 63.5, -64.0, -0.5, -63.5]);
assert!(output[6..31].iter().all(|value| value.to_bits() == 0));
assert_eq!(output[31], 21.0);
let mut batch = [0.0; BLOCK_ELEMENTS * 2];
decode_into(&block.repeat(2), &mut batch).unwrap();
assert_eq!(&batch[..BLOCK_ELEMENTS], &output);
assert_eq!(&batch[BLOCK_ELEMENTS..], &output);
}
#[test]
fn malformed_shapes_reject_without_modifying_output() {
let source = [0u8; BLOCK_BYTES * 2];
for source_len in [1, 33, 35, 67] {
let mut output = [123.0; BLOCK_ELEMENTS * 2];
assert!(decode_into(&source[..source_len], &mut output).is_err());
assert_eq!(output, [123.0; BLOCK_ELEMENTS * 2]);
}
for output_len in [0, 31, 33, 64] {
let mut output = [123.0; BLOCK_ELEMENTS * 2];
assert!(decode_into(&source[..BLOCK_BYTES], &mut output[..output_len]).is_err());
assert_eq!(output, [123.0; BLOCK_ELEMENTS * 2]);
}
let mut output = [123.0; BLOCK_ELEMENTS];
assert!(decode_into(&[], &mut output).is_err());
assert_eq!(output, [123.0; BLOCK_ELEMENTS]);
decode_into(&[], &mut []).unwrap();
}
#[test]
fn signed_zero_and_infinity_times_zero_preserve_value_policy() {
let mut block = [0u8; BLOCK_BYTES];
block[3] = 255;
block[4] = 1;
for (scale, zero, negative, positive) in [
(0x0000u16, 0, 0x8000_0000, 0),
(0x8000, 0x8000_0000, 0, 0x8000_0000),
] {
block[..2].copy_from_slice(&scale.to_le_bytes());
let output = decode_block(&block).unwrap();
assert_eq!(output[0].to_bits(), zero);
assert_eq!(output[1].to_bits(), negative);
assert_eq!(output[2].to_bits(), positive);
}
for scale in [0x7c00u16, 0xfc00, 0x7c01, 0xfc01] {
block[..2].copy_from_slice(&scale.to_le_bytes());
let output = decode_block(&block).unwrap();
assert!(output[0].is_nan());
if scale & 0x03ff == 0 {
assert_eq!(
output[1].to_bits(),
if scale == 0x7c00 {
0xff80_0000
} else {
0x7f80_0000
}
);
assert_eq!(
output[2].to_bits(),
if scale == 0x7c00 {
0x7f80_0000
} else {
0xff80_0000
}
);
} else {
assert!(output.iter().all(|value| value.is_nan()));
}
}
}
}
+16
View File
@@ -0,0 +1,16 @@
ARG BUILDER_BASE=ubuntu@sha256:f610ab94648195aa356059f5b41d6085c9d4d903c072430cdd1af7bdb646106b
FROM ${BUILDER_BASE}
# The caller supplies its verified runner CA bundle as build context. This
# lets later TLS fetches use the runner's complete trust store.
COPY runner-ca-bundle.crt /tmp/runner-ca-bundle.crt
ARG DEBIAN_FRONTEND=noninteractive
RUN apt-get update \
&& apt-get install -y --no-install-recommends \
binutils ca-certificates cmake gcc-13 g++-13 git make python3 \
&& cp /tmp/runner-ca-bundle.crt /etc/ssl/certs/ca-certificates.crt \
&& rm -f /tmp/runner-ca-bundle.crt \
&& rm -rf /var/lib/apt/lists/*
LABEL org.opencontainers.image.title="Leleka GPU-hidden CUDA build environment"
LABEL org.opencontainers.image.description="CPU-only container for compiling the pinned CUDA engine; no NVIDIA driver or device is installed"
+4 -1
View File
@@ -7,8 +7,11 @@ RUN apt-get update \
RUN rustup target add "${RUST_TARGET}"
WORKDIR /src
COPY rust-toolchain.toml ./
ENV CARGO_TARGET_DIR=/src/control-plane/target
COPY Cargo.toml Cargo.lock rust-toolchain.toml ./
COPY crates/ ./crates/
COPY manifests/ ./manifests/
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 \
+13
View File
@@ -0,0 +1,13 @@
FROM ubuntu@sha256:f610ab94648195aa356059f5b41d6085c9d4d903c072430cdd1af7bdb646106b
RUN apt-get update -qq && DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends \
systemd=255.4-1ubuntu8.17 dbus=1.14.10-4ubuntu4.1 \
dbus-user-session=1.14.10-4ubuntu4.1 python3=3.12.3-0ubuntu2.1 \
util-linux=2.39.3-9ubuntu6.6 ca-certificates=20260601~24.04.1 && rm -rf /var/lib/apt/lists/*
RUN useradd --create-home --uid 10001 fixture && \
mkdir -p /run/systemd/system /run/user/10001 /home/fixture/.config && \
chown fixture:fixture /run/user/10001 /home/fixture/.config && \
chmod 0700 /run/user/10001 /home/fixture /home/fixture/.config
# Empty disposable boot-context directory; the fixture starts a real user manager.
# No system manager, host bus, host unit directory, or host cgroup is mounted.
ENV XDG_RUNTIME_DIR=/run/user/10001
WORKDIR /work
+1
View File
@@ -977,6 +977,7 @@ engine="$PWD/artifacts/build-static-cuda/strata"
python3 scripts/build-linux-package.py \
--engine "$engine" --sha256 "$(sha256sum "$engine" | cut -d ' ' -f 1)" \
--revision "$(git rev-parse HEAD)" \
--build-features "$PWD/artifacts/build-static-cuda/BUILD-FEATURES.json" \
--cargo-target-dir "$PWD/artifacts/combined-build" \
--output "$PWD/artifacts/combined-v1"
```
+11
View File
@@ -0,0 +1,11 @@
# Backend capability admission
The `leleka-backend-api` contract at API version 2 describes supported models as explicit `SupportedModelTuple` entries in `BackendCapabilities.supported_models`. Each entry binds family, architecture and weight format together. Entries do not imply combinations assembled from different entries, and the default empty list supports no models.
`supports` first validates the descriptor: identifiers must be nonempty and contain no whitespace or control characters, and the artifact digest must use the existing `sha256:` prefix with exactly 64 hexadecimal characters. It then requires one exact declared tuple. Matching is case-sensitive for tuple identifiers, with no wildcard, alias or family inference.
The public capability layout replaces the version 1 independent lists. `BACKEND_API_VERSION` advances from 1 to 2, and `BackendIdentity::supports_current_api` rejects version 1 identities. A backend must migrate its declarations to explicit combinations; generating their Cartesian product would recreate the old admission bug. This is a Rust scaffold contract, not a stable dynamic plugin ABI or serialized protocol. The crate package version remains controlled separately by repository release policy; no backend consumer or production model declaration currently uses this scaffold.
Compatibility declaration is only one load prerequisite. `supports` does not read or hash model bytes, validate tensors or a tokenizer, check hardware, reserve memory/concurrency, qualify experimental modes, or publish readiness. Backend implementations must perform those checks before loading succeeds. A declared tuple is a backend assertion, not proof that a real model works.
Tests use two synthetic declared tuples and independently enumerate all eight combinations: only the two explicit entries are admitted. They also cover unknown formats, empty capabilities, malformed identifiers even when explicitly advertised, invalid digests, and refusal of obsolete/future API versions. No real family support, inference quality, numerical result or performance claim is introduced.
+49 -1
View File
@@ -1,5 +1,32 @@
# Build validation
## 2026-10-07 — Gitea Python 3.11 archive validation
- Exact-head Gitea run `2700` (`8ec9ab5bce6442acf3629b3b03967cdc42311918`) ran in
`node:24-bookworm` / Debian 12 with Python `3.11.2`. `verify` exposed that
`tarfile.extractall(filter="data")` requires Python 3.12; the CUDA bootstrap
now validates member paths, link containment, topology, types, and modes before
using the Python 3.11-compatible standard-library extractor. No PyPI packages
are added for this script.
- The focused archive suite passed on the same `node:24-bookworm` image. It covers
valid file/symlink/hardlink trees, traversal and link-parent attacks, privileged
mode rejection, conflicting merges, download integrity, and lock validation.
- The manual keyless-GPU path is now preceded by a CPU-side input gate and depends
on `verify`; a false selection must be resolved as skipped before any GPU runner
is eligible. This gate does not execute GPU checks or imply GPU availability.
- Exact-head Gitea run `2703` (`712de0f6bc4f16686d52c3c98bed2643147178cc`)
passed `verify` and the CPU gate; both keyless GPU jobs were skipped. The hosted
PLE job exposed that the Docker daemon cannot bind-mount the runner container's
`$GITHUB_WORKSPACE`; the build now streams a tracked-source archive into a
private Docker volume and supplies the exact source SHA as provenance. The same
run found the static CLI target path mismatch and an incomplete scratch-image
workspace (missing the root lockfile and local tokenizer workspace crate); the
workflow and Dockerfile now use one explicit target directory and include the
complete Cargo workspace manifests/sources.
- Run `2703` produced no hosted package artifact. The new fixes require one fresh
exact-head Gitea run; no GPU inference, model-quality or rollback claim follows
from these CPU/build checks.
## 2026-10-03 — experimental PLE quality arm
The imported engine builds on Linux CUDA 13.2/sm_120 with the optional
@@ -834,8 +861,29 @@ 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.
PLE-only packaging is selected with Gitea input `hosted_cuda_ple=true`; its job
uses the CPU runner and hides all GPU devices inside the pinned build container.
The workflow reads Gitea's raw dispatch inputs as strings and explicitly
compares each opt-in to `true`, so a false string cannot enqueue GPU jobs.
The Rust installer is pinned separately from the compiler toolchain:
| Dependency | Pin |
| --- | --- |
| rustup-init | 1.29.0, SHA-256 `4acc9acc76d5079515b46346a485974457b5a79893cfb01112423c89aeb5aa10` |
| rustc / cargo | 1.99.0 from `rust-toolchain.toml` |
| CUDA toolkit | 13.0.1 manifest; NVCC 13.0.88, component hashes in `deploy/cuda-toolkit.lock.json` |
| CUDA build image | Ubuntu base digest `f610ab94648195aa356059f5b41d6085c9d4d903c072430cdd1af7bdb646106b`; GCC/G++ 13 |
The runner's `ubuntu-latest` label and job container image are runner
configuration, not immutable pins; actual OS and apt package versions are
recorded in artifact provenance. Trigger a private build on a committed branch
with the Gitea API (input values are strings):
```sh
gh workflow run linux.yml --ref COMMITTED_REF -f hosted_cuda_package=true
tea api --repo para/leleka --login git.vezha.io --method POST \
-d '{"ref":"refs/heads/BRANCH","inputs":{"hosted_cuda_ple":"true"}}' \
/repos/para/leleka/actions/workflows/linux.yml/dispatches
```
## Native per-user installation (STRA-72)
+19
View File
@@ -15,6 +15,25 @@ still checks payload CRCs. The feature is off in ordinary builds.
`strata_next_kar_ple_probe ARCHIVE 2 ROW...` prints FNV-1a checksums for
comparison with `strata-next model checksum-kar-row` on the matching part.
### Static CUDA PLE package profile
`scripts/build-static-cuda.sh` accepts only `STRATA_KAR_PLE=0|1`; it defaults
to `0`. The script always resets the cached PLE, expert-KAR, and PLE-trace
CMake options explicitly, so reusing a build directory cannot accidentally
retain those experimental arms. `STRATA_KAR_PLE=1` compiles the existing PLE
implementation from `gpu/kar`; it does not select a model, archive, PLE level,
or runtime profile. The private Gitea `hosted_cuda_package` workflow exposes
this build capability as a separate boolean, defaulting off, and binds the
selected flags and CUDA architecture into the checksummed package provenance.
The CUDA runtime and C++ runtime are statically linked for the engine build.
The NVIDIA driver and host glibc remain system dependencies; this is not a
fully static CUDA executable and does not eliminate driver compatibility.
The combined outer CLI is separately built for musl. Neither static linking
nor a PLE-enabled package proves GPU inference, model quality, or a speedup;
the serving profile must still explicitly select the model's PLE archive,
level, and cache budget after the separate GPU gates pass.
This arm measures whether PLE transcoding changes whole-model output and task
quality. It does not load the full compressed model, stage sparse PLE packets
to CUDA, or establish a model throughput gain. Use the same engine source,
+168
View File
@@ -0,0 +1,168 @@
# Independent CUDA driver bootstrap contract
Requirements of record for bounded STRA-102 plan
`d20f1568-5b7b-477d-8eab-a32219af7fd7`, before implementation.
This foundation does not implement inference, model loading or GPU kernels and
must not change production serving or advertise any supported model.
## Platform and ABI
- Explicit `cuda-driver` Cargo feature, disabled by default, plus an explicit
`Driver::load()` call; Linux with 64-bit pointers. Unsupported platforms or
disabled capability must return a clear error without touching a CUDA driver.
- Load only the installed NVIDIA Driver ABI soname `libcuda.so.1` at runtime.
No CUDA Toolkit, Strata, Python, C compiler or native build script is a
production build/runtime dependency of this Rust crate.
- Resolve the fixed documented legacy ABI symbols, with `_v2` context, device
allocation/free and synchronous copy symbols where required. Missing symbols
fail before CUDA initialization or resource mutation. No symbol-version
fallback or API reinterpretation.
- Isolate all unsafe FFI and dynamic loader code in the driver crate. Public
callers get owned typed resources and errors, never raw host/device pointers
or mutable CUDA context handles.
## Fixed ABI and source evidence
The exact symbol set is `cuInit`, `cuDriverGetVersion`, `cuDeviceGet`,
`cuCtxCreate_v2`, `cuCtxDestroy_v2`, `cuCtxPushCurrent_v2`,
`cuCtxPopCurrent_v2`, `cuCtxSynchronize`, `cuMemAlloc_v2`, `cuMemFree_v2`,
`cuMemcpyHtoD_v2`, `cuMemcpyDtoH_v2`. The legacy create binding has three
arguments: `CUcontext*`, `unsigned int`, `CUdevice`; the current unversioned
CUDA 13 header macro points to the four-argument v4 entry instead and must
not be rebound to this function type. Device pointers are 64-bit for this
64-bit-only surface; byte counts use `size_t`.
Independent TL verification read the official
[NVIDIA cudart 13.0.88 archive](https://developer.download.nvidia.com/compute/cuda/redist/cuda_cudart/linux-x86_64/cuda_cudart-linux-x86_64-13.0.88-archive.tar.xz)
in memory, without installing headers or a toolkit. Archive size 1,491,604 bytes,
SHA256 `bc44226f069402ab327bcf9e754660621aa6bc61fb7fc6afe03b794dfaaab658`;
`cuda.h` SHA256 `64025f81a9d6d2b10e9e11654f3523e5b046d01b883f0b9ca474e463274b80d4`.
Header lines 25633/90 prove the legacy declaration/current alias respectively;
line 274 defines the 64-bit device pointer. Runtime behavior still requires
separate installed-driver qualification. See NVIDIA's
[synchronization behavior](https://docs.nvidia.com/cuda/archive/13.0.1/cuda-driver-api/api-sync-behavior.html)
for why calling a synchronous-named copy alone does not prove completion of
all host memory references.
## Ownership and context discipline
- Driver, context and device-buffer lifetimes keep the dynamic library alive
until every dependent operation and cleanup finishes. Resources cannot be
sent or shared between threads (`!Send`, `!Sync`).
- Create a private context and pop it immediately, restoring the caller's
previous context. Do not use or mutate an external primary context.
- Push the owned context for every operation that needs it, and restore the
previous context on both success and failure. Pop failures must surface as
errors; never claim restoration after the driver rejects restoration.
- Buffers cannot outlive their owner context; allocation/copy operations are
bounded, checked before driver mutation and reject empty/oversized shapes.
- Copies use exact-sized byte slices with bounded owned staging memory and the
synchronous Driver API. DtoH publishes staging only after completion; ambiguous
completion errors retain staging and poison the context to prevent dangling
host DMA pointers. Synchronize
before returning host borrows. Failed copy/synchronization paths must preserve
context cleanup, while reporting the original driver failure accurately.
- Cleanup is best-effort on drop, does not panic and must not free resources in
an unrelated context. Explicit fallible cleanup should expose failure when
the API supports it; permanently failed driver cleanup cannot be guaranteed.
## Independent CPU qualification
Only synthetic owned fixtures may be used. The test library is compiled to an
ELF named `libcuda.so.1`, injected through a private subprocess loader environment
inside a disposable Linux CPU Docker container. No installed driver is called,
no NVIDIA device is exposed, and no GPU/model/request probe is performed.
The fake library records synthetic ABI operations, context stack, allocated bytes,
copy/sync actions and cleanup. Independent assertions cover missing symbols,
init/device/create/push/pop/alloc/copy/sync/free/destroy errors, bounds before
mutation, byte-copy round trips and prior-context restoration. Lifetime and
thread-safety compile-fail gates are required as well as runtime tests.
All existing local gates remain; focused checks add crate format/Clippy/unit and
the Linux ELF mock gate. Results below must report the actual environment,
counts and cleanup, never infer GPU success from a mock or compile pass.
## Qualification state
Actual local CPU result on 2026-10-07:
- Linux **aarch64**, native CPU Docker Desktop execution; Rust 1.99.0
(`b940084d7 2026-09-28`), GNU C compiler Debian 12.2.0-14+deb12u1.
- Pinned Rust base OCI index:
`sha256:114c7a4425406451c2866b6aafe69fe29b1b298832db1277d411ac73c82d04d6`.
Independently inspected index contains Linux amd64 manifest
`sha256:b36c246742b4d323472588f789601be34eb4af053255e2af53969078ee8dcec7`
and arm64 manifest
`sha256:e393e07b3c3c39f238de676b0eb60c03dc7aefe5d6e37be6d29c686bf4d7e256`.
The final owned fixture image after installing matching rustfmt/Clippy was
`sha256:a7fd4951f84b368826117e60c93f1e067ade2e39b2b69329108e70b052dd136d`.
- Actual test container: nonroot UID/GID 65532, default runc, network `none`,
all effective/permitted/bounding capabilities zero, no privileges, no host
binds or device requests/devices; raw NVIDIA/DRI device guard passed.
Build tools were provisioned in an earlier disposable setup container;
all tests and compilation then ran offline with network disabled.
- Minimal synthetic workspace contained only exact driver crate source/tests,
matching workspace package/lint declarations, and approved pinned libc
0.2.190. Engine, control-plane, CUDA Toolkit/headers/nvcc and installed
`libcuda` were physically absent. The existing registry archive SHA256
`ce5d3ddc6d3fa000eb1536d85e147bfe31aacaba692ed6a876f95cb7c855be78`
was checked before extraction, then Cargo verified every vendored source
checksum. Normal dependency tree was driver crate → libc only.
- Default denial/unit tests: **2 passed**. Actual enabled-FFI all-target,
all-feature Clippy with warnings denied and formatting passed.
- **33 isolated subprocess scenarios passed**: round trip, pre-mutation
shape/budget refusal, each of the twelve missing symbols, init/version/device,
create/pop cleanup, push/pop errors, mismatched popped context and poisoned
future work, allocation, both copy directions, explicit synchronization,
copy-plus-sync dual errors in original/cleanup order, free and destroy faults.
The fixture matrix is explicitly ignored by ordinary `cargo test`; the harness
selects it with `--ignored` and requires its marker, so an absent harness
cannot appear as a vacuous integration pass.
- Delayed synthetic HtoD at destruction read the exact original eight owned
staging bytes after the caller source was changed to zeros. Delayed DtoH at
destruction wrote retained staging while the still-live caller destination
remained unchanged after failed synchronization. These independently
witness the declared staging/completion behavior, alongside source review;
they are not a proof of all possible memory safety or vendor behavior.
- **10 independent compile refusals passed**: Send and Sync for Driver, Device,
Context and DeviceBuffer; context outliving Driver; buffer outliving Context.
Assertions checked the expected auto-trait/borrow compiler diagnostics.
- Final fake full/missing-DtoH ELF SHA256 values:
`551878f9b518b200f8ac3dbf3570ec7494f1a2226917530c84ea30b418c1d41f` /
`a95af6e51e678a5e3fc5f937b4232393493497161195391e256138a5d2009991`.
Source hashes inside the container matched the working-tree bytes.
- All owned setup/test containers, derived fixture images, private source
staging, synthetic libraries, trace files and target directories were
removed. The shared pinned base image and existing registry cache were retained.
Cleanup attempts each resource independently, preserves test failure, and
fails a successful test run if any cleanup fails.
Two initial fixture provisioning failures occurred before Rust integration:
missing optional rustfmt/Clippy, then Docker tmpfs execution denial for libc's
Rust build script. The final fixture installs verified toolchain components and
uses an explicitly executable owned `/tmp`; product behavior and assertions
were not weakened.
Production source receipts: `src/lib.rs`
`7ce58fcf033b5e9704b2d134fc4c16cd2d5c57c5c45a867d2399c310dec3c4d4`;
`src/ffi.rs` `5f00400fab73d98578ca53bfedcb86b4163133d2956a88ac3d2cd156455800c8`.
## Remaining integration limits
These outcomes qualify a GNU/Linux CPU mock contract. They do not execute an
installed NVIDIA driver, GPU allocation/copy or a kernel, and they do not prove
vendor cleanup succeeds after a driver failure. A sync fault deliberately
retains bounded staging and poisons that context; failed destruction can retain
the library/context instead of pretending release occurred. Repeated poisoned
contexts can accumulate retained resources; there is no process-wide recovery
or memory-bounded serving guarantee in this bootstrap.
The existing statically linked musl executable is also **unqualified** for this
loader. [musl's static dlopen stub](https://git.musl-libc.org/cgit/musl/plain/src/ldso/dlopen.c)
refuses dynamic loading; the GNU/Linux ELF mock pass does not make static musl
capable of loading `libcuda.so.1`. A separate executable/loader integration gate
is required. The OCI index admits amd64 builds, but this actual local mock run
was arm64; hosted amd64/compiler qualification is separately pending.
Installed-driver GPU allocation/copy, kernel execution, model inference,
model quality and paired performance remain separate unqualified gates.
+238
View File
@@ -0,0 +1,238 @@
# Fixed CUDA f32 vector-add requirements
Bounded STRA-102 requirements for plan
`05e21fde-510e-4d63-8aa1-442e67339961`, written before implementation on
base `0383253c6011ec795aa395b613405263f63378ee`.
This unit supplies one opt-in, typed operation over owned CUDA buffers:
`out[i] = add.rn.f32(a[i], b[i])`. A successful return must mean the attempted
launch completed and the caller's previous context was restored. Validation
errs toward refusal before native mutation; uncertain completion or restoration
errs toward poisoning and retaining resources. These properties can support
bounded wrapper/ABI claims after their respective gates; they cannot establish
model support or numerical execution merely from a mock or compilation.
The historical [bootstrap contract](cuda-driver-bootstrap.md) and its actual
12-symbol qualification receipts remain unchanged. This document owns only the
extension below. The charter remains the project goal and quality authority;
this unit advances the independent Rust NVIDIA execution foundation without
changing production serving or the imported Strata engine.
## Scope and caller outcome
An internal engine developer can explicitly enable the `cuda-driver` feature,
load the driver, create a private context, allocate/upload two input buffers and
an output buffer, invoke the fixed add operation and read the completed output.
The safe interface accepts owned buffer references and returns structured errors;
it accepts no PTX, module image, entry name, stream, launch geometry, raw pointer,
foreign context or callback from a caller.
The existing default feature remains off. No new HTTP endpoint, worker switch,
backend/model admission, scheduler, tensor loader, inference implementation or
production deployment integration is included. Deployment of this foundation
must continue to require only the installed NVIDIA driver rather than Strata,
Python, a C compiler or CUDA Toolkit; offline verification tools are separate.
## Requirements and acceptance conditions
### FR-VADD-1 — validate owned shapes before mutation
- Accept two immutable input buffers and one mutable output buffer belonging to
the exact same owned `Context` instance. Equal device ordinals or separate
contexts on the same GPU do not establish ownership equality.
- All three byte lengths must be equal, nonzero and divisible by four; interpret
them as f32 elements. The element count must fit `u32`, byte bounds must retain
the bootstrap's checked budget/`isize` constraints, and grid arithmetic must be
checked without truncation or overflow.
- Preserve safe aliasing: inputs may refer to the same immutable allocation;
output must not alias an input. The public borrow contract must enforce this,
with defensive identity refusal wherever implementation structure permits
otherwise. No unsafe bypass is exposed publicly.
- Reject invalid ownership, shape/count/geometry, unavailable capability and
poisoned contexts before push, module load, lookup or launch. Do not mutate
output or allocation accounting on validation refusal. Do not allocate new
device buffers implicitly for this operation.
### FR-VADD-2 — one trusted module and function
- Embed a bounded, NUL-terminated PTX byte sequence in the crate. It contains
exactly the fixed entry `leleka_vector_add_f32` with parameters in this order:
input A u64 device address, input B u64 device address, output u64 device
address, element count u32. Treat pointers as private ABI values, never public
Rust handles. Record the exact embedded bytes' SHA256 for verification.
- The entry checks `i < n` before any element access; address arithmetic must
not wrap. Every in-range thread reads the corresponding A/B elements and
writes exactly one output element. No input writes, external symbols,
indirect calls, atomics, shared-memory state or out-of-range writes.
- Use explicit `add.rn.f32` without `.ftz`, saturation, approximate arithmetic
or floating-point contraction. No `fma`/`mad` substitutes for the add. The
selected fixed image uses PTX 7.0, `sm_75`, and `.address_size 64`; unsupported
driver/target combinations fail explicitly, not by selecting another kernel.
- Cache at most one successfully loaded module/function per context, lazily
after validation. Repeated successful calls reuse it. Publish a cache entry
only after both load and function lookup succeeded with valid non-null
handles. Failed initialization must not create a usable partial cache.
The arithmetic spelling is grounded in NVIDIA's archived
[PTX floating-point add specification](https://docs.nvidia.com/cuda/archive/13.0.1/parallel-thread-execution/index.html#floating-point-instructions-add).
This is the required arithmetic, not evidence that real hardware has executed
it. Signed zeros, subnormal handling, overflow, infinities, NaNs and NaN payload
behavior still require explicit installed-driver numerical qualification.
### FR-VADD-3 — fixed 16-symbol loader and launch ABI
Extend the bootstrap's fixed twelve symbols by precisely these four:
| Symbol | Private C ABI parameters | Return |
| --- | --- | --- |
| `cuModuleLoadData` | `CUmodule*`, `const void*` | `CUresult` |
| `cuModuleGetFunction` | `CUfunction*`, `CUmodule`, `const char*` | `CUresult` |
| `cuModuleUnload` | `CUmodule` | `CUresult` |
| `cuLaunchKernel` | `CUfunction`, six `unsigned int` grid/block dimensions, `unsigned int` shared bytes, `CUstream`, `void** kernelParams`, `void** extra` | `CUresult` |
All sixteen resolve before `cuInit`; each missing extension symbol must fail
before initialization. Keep the legacy bootstrap `_v2` signatures, soname,
library lifetime and platform guards. Opaque module/function/stream pointers
remain inside audited private FFI. The ABI references are NVIDIA's archived
[module management](https://docs.nvidia.com/cuda/archive/13.0.1/cuda-driver-api/group__CUDA__MODULE.html)
and [execution control](https://docs.nvidia.com/cuda/archive/13.0.1/cuda-driver-api/group__CUDA__EXEC.html)
documentation. Independent advisory verification checked the official pinned
cudart 13.0.88 archive (1,491,604 bytes, SHA256
`bc44226f069402ab327bcf9e754660621aa6bc61fb7fc6afe03b794dfaaab658`)
and `cuda.h` SHA256
`64025f81a9d6d2b10e9e11654f3523e5b046d01b883f0b9ca474e463274b80d4`.
Header lines 7365/7476/7532 identify load/unload/function lookup; lines
17537–17547 identify launch with seven unsigned-int arguments including shared
bytes. This is header evidence, not an execution result.
Launch one dimension with fixed block size 128, `grid.x = ceil(n / 128)`;
grid/block y and z are one, shared memory is zero, stream is null, `extra` is
null. `kernelParams` is a private four-entry array of pointers to the typed
argument values above. Own the scalar/device-address parameter storage and
pointer table, keeping their addresses stable through launch and synchronization.
If the table references fields of its own storage object, establish those pointers
only after stable heap placement; moving an inline self-referential object must
not invalidate them. NVIDIA's documentation describes copying parameter values
from the supplied regions, but this contract does not infer a stronger
before-return timing guarantee from that wording;
if completion is uncertain, retain any storage the driver could still reference
and poison future work. No caller host pointer or arbitrary argument escapes
into this interface. Compute the grid in a wider
integer and require `grid.x <= i32::MAX`. Kernel index/address arithmetic must
cover the final partial block without u32 overflow or reading beyond `n`.
No caller can alter this launch shape. The driver may still reject this fixed
shape on unsupported hardware; that is a reported operation failure.
### FR-VADD-4 — completion and context restoration
- Push the owned context for module/launch operations and pop it on all paths
after a successful push, checking that the popped handle is the owned one.
Successful operations and handled failures restore the prior caller context;
a failed or mismatched pop reports the failure and poisons this context.
- After **every attempted `cuLaunchKernel`**, synchronize even when launch
returns an error. Retain the launch error and subsequent synchronization/pop
errors in their operation order; cleanup must not replace the original error.
A lookup/load failure before launch is not a launch attempt.
- Return success only after launch, synchronization and restoration all succeed.
Inputs stay immutable; output contents after a native execution failure are
unspecified and must not be reported as a successfully computed vector.
- Synchronization failure means completion is uncertain: poison the context,
reject future allocation/copy/sync/kernel work without further native work,
and keep possibly referenced buffers/module alive until safe context teardown.
Do not free or unload them merely because a failed launch was observed.
- Continue the bootstrap's staged-copy rule, including keeping ambiguous host
DMA staging alive. A fixed kernel must not weaken existing copy/borrow safety.
### FR-VADD-5 — module ownership and failure cleanup
- Module/function cache lifetime is inside its owner context and dynamic-library
lifetime. No public module or function can outlive that context or cross a
thread; retain the existing `!Send`/`!Sync` resource guarantees.
- On function lookup failure after module load, attempt unload in the owned
current context. Consume the module's usable-handle slot before calling unload,
regardless of its return value; unload at most once per handle. A failed
unload poisons the context. Retain only context-owned residual/accounting for
final destruction: never retry unload, reuse the handle or reinitialize a
healthy cache after that failure. If restoration is uncertain, likewise
report all relevant errors and forbid treating the module as a valid kernel.
- Healthy teardown unloads the cached module after completed work, in the owned
context, before destroying the context. Pending/uncertain work must not be
followed by explicit module unload or buffer free. Context destruction is the
final containment attempt; permanent driver failures cannot be called cleaned.
- Explicit fallible close reports unload/restoration/destruction failures;
destruction should still be attempted when safe. Drop remains best effort
and nonpanicking. Failed destroy retains the library as required by the
bootstrap rather than permitting calls through an unloaded library.
- No automatic retries of a failed launch. Repeated poisoned contexts can
retain resources; this unit supplies no process-wide recovery or cumulative
resource bound and must not advertise a leak-free serving guarantee.
## Security and non-functional contract
| Dimension | Metric / threshold | Planned verification |
| --- | --- | --- |
| Critical usability | One typed add action; structured errors, no raw pointer/module interface | Public API review and synthetic caller |
| Reliability | Success requires launch + completion + restoration; zero silent launch retries | Fault matrix and trace order |
| Performance | No speed/SLO assertion; one launch and one mandatory completion sync per valid call | ABI trace, separate future paired benchmark |
| Capacity | One cached module/context; fixed block128; checked count/grid and existing byte budget | Boundary/refusal and repeated-call tests |
| Security / isolation | Exact context ownership, private fixed PTX/entry, no safe arbitrary execution surface | Cross-context/alias/ABI review and compile refusals |
| Audit / retention | Only owned synthetic traces; no model/request/credentials in Git; private evidence outside source | Harness output and cleanup review |
| Observability | Fixed operation names, driver codes, ordered primary/cleanup errors; no pointers or PTX dumps in error text | Fault assertions and error-text inspection |
| Accessibility / i18n | No UI is introduced; existing user interfaces/locales remain unchanged | Changed-surface review |
| Rate / admission | One synchronous call on the creating thread; existing per-context memory budget; no new network/tenant admission | Thread/lifetime gates and budget refusals |
| Deploy / rollback | Default feature off, no serving consumer, no deployment-tool dependency added; disable opt-in to return to existing path | Feature/default/dependency/consumer review |
| Support | Load/lookup/launch/completion/cleanup failures remain diagnosable; no production support SLA is claimed | Error matrix and documented residuals |
| AI dependence | This fixed arithmetic operation performs no model call; no AI output or quality gate substituted by it | Consumer/source review |
| Integrity | Inputs unchanged; output published as success only for completed add; no hidden persistent state except bounded cache | Synthetic data/canaries and cache traces |
| Backup / recovery | No durable data introduced; failed driver teardown is reported/retained, not treated as recovery | Fault/ownership review |
| Privacy | Only sanitized synthetic vectors permitted in this unit's verification | Fixture and artifact review |
| Maintainability | Four additional exact symbols, one embedded module/entry, no new normal dependency | Source/ABI/dependency review |
| Compatibility | Linux 64-bit opt-in only; legacy12 bindings and existing33 mock/10 compile guards preserved | Default/platform and regression gates |
| Cost / efficiency | CPU mock/tooling work only for this delivery; no GPU/probe/model access, no duplicated CI | Recorded commands and container guards |
## Verification plan — outcomes not yet measured
The planned instruments derive from the requirements and official ABI, rather
than obtaining expected outputs from the wrapper implementation. A synthetic
mock can witness argument/context/cleanup behavior and expected fixture data;
it does not execute or establish correctness of the embedded PTX instructions.
| Gate | Required checks / predicted refusal | Claim licensed by a pass |
| --- | --- | --- |
| Existing regression | Retain all 33 bootstrap mock cases and 10 compile refusals, default-denial units, enabled FFI format/Clippy | Existing contract still holds against changed source |
| Missing extension symbols | Independently omit each of four new symbols; zero `cuInit` and resource mutation | Fixed16 pre-initialization admission |
| Typed validation | Different contexts on same device; unequal/nonmultiple4/empty shapes; count/grid overflow; invalid output alias; poisoned context. All refuse before push/load/launch | Bounded safe wrapper admission |
| ABI and synthetic data | Verify exact trusted PTX/entry identity, parameter order/width/value and live owned device allocations, fixed dimensions/null stream/null extra, context sentinel, input immutability/output/canaries | Mocked host ABI/dataflow only |
| Launch bounds | Counts 1,127,128,129 and a bounded larger nonmultiple128 vector; checked maximum/count-overflow tests without giant allocations | Shape/tail guard contract, not real GPU memory safety |
| Cache/lifetime | First valid call loads/looks up once; next call reuses; independent contexts own separate caches; zero unload with pending work; healthy unload before destroy | Bounded cache and resource ordering |
| Faults | Load/lookup/null-success handles/push/launch/sync/pop/wrong-pop/unload/destroy, plus launch+sync and lookup+unload errors; failed unload consumed once, no retry/reuse/cache reinitialization | Original errors retained, cleanup attempts, poison/refusal behavior |
| Delayed completion | Mock defers add completion to sync, including dereferencing retained parameter storage; failed sync leaves work pending until containment; no early argument release/buffer free/module unload; caller output never presented as successful after failure | Declared containment behavior alongside source review |
| Ownership compile gates | Existing driver/context/buffer borrow and thread refusals remain; no safe arbitrary module/function/pointer escape | Rust safe API lifetime/thread surface |
| Offline PTX assembly | GPU-hidden Linux CPU Docker with pinned `ptxas`; exact PTX SHA, tool/version/container target and flags; no devices, installed driver calls or user data | PTX assembler acceptance for the recorded target only |
| Installed-driver numerical execution | Separate authorized real-GPU gate: independent f32 reference; declare finite tolerance before execution (target exact finite bits), signed zeros/subnormal/overflow/Inf/NaN cases with NaN classification/payload limits | Only the executed hardware/driver numerical scope |
| Model / protocol / throughput | Separate Qwen and two named MoE integration, real quality/protocol gates, same-workload paired distributions/provenance | Whole-engine claims only after their own evidence |
Record actual argv, source/commit and embedded PTX hashes, toolchain, architecture,
image/ELF identity, environment/guards, exact test counts, failures and exit codes.
Keep generated evidence private outside Git, remove owned disposable resources,
and report cleanup failures. No number in the planned matrix is a measured pass.
## Remaining platform and qualification boundaries
GNU/Linux 64-bit CPU mock/assembly results do not qualify the existing static
musl executable for `dlopen(libcuda.so.1)`. Its loader integration remains open,
as described in the historical bootstrap contract. PTX loading may require the
installed driver to JIT the fixed image; driver/JIT compatibility is unqualified
until a separate real-driver gate. No Toolkit becomes a deployment prerequisite
merely because offline assembly is used for validation.
No real GPU allocation, kernel execution, model support, quality, protocol
completion, rollback or performance is established by this requirements unit.
The autonomous engine parent and its dependent intake/delivery items remain
open under root coordination. No admission/closure flags are changed here.
No active host-local `.leasevibe.yaml` pointer was supplied; it was absent in
the worktree and canonical repository. Task-relevant host settings are therefore
unavailable, not inferred. The explicit session restrictions remain binding:
Gitea only for future publication/CI, no merge, no active Qwen/runtime changes,
no GPU/model/user-data probes. This BA unit changes only this requirements file.
+33
View File
@@ -0,0 +1,33 @@
# Gitea preview publication
The Linux workflow publishes through `https://git.vezha.io/api/v1` with a repository-scoped `GITEA_TOKEN` secret. Python is used only for offline CI publication; serving is unchanged. The publisher and its API fixture tests derive from tracked commit `a8fa7e0`, adapted to the current assembly receipts. The imported Strata upstream record remains unchanged.
| Profile | Exact assets | Tag scope |
| --- | --- | --- |
| CLI | binary, BUILD-PROVENANCE.txt, ELF-AUDIT.txt, SHA256SUMS | cli-preview-RUN-ATTEMPT or explicit vVERSION |
| Hosted CUDA | binary, PROVENANCE.json, SHA256SUMS, runtime-image.tar, IMAGE-PROVENANCE.json, CUDA-TOOLCHAIN.json, CUDA-LICENSES.tar, IMAGE-SHA256SUMS | cuda-preview-RUN-ATTEMPT |
| Static CUDA | binary, PROVENANCE.json, SHA256SUMS, runtime-image.tar, IMAGE-PROVENANCE.json, IMAGE-SHA256SUMS | static-cuda-preview-RUN-ATTEMPT |
All profiles reject missing/extra files, symlinks, mismatched checksums and source revisions before creating a release. CLI publication requires one exact Commit line and a static x86_64 ELF audit. The existing static CLI lifecycle, Responses, restart and CPU rollback gates remain prerequisites. A version-tag job rebuilds the same gated tag commit with the existing pinned Rust/musl build command, then repeats the original ELF audit and generates checksums for the rebuilt assets; it does not claim bitwise reproducibility against the earlier preview binary.
CUDA publication validates current package `loader_probe` receipts from `--probe-in-runtime-image`, image/package receipt binding and canonical compile-feature digests. These producers do not emit the historical `engine_help_probe` strings; their existing loader/identity/help probes must pass for assembly to emit the current receipts. Hosted toolchain publication additionally binds the actual builder image identity, source, engine hash, compile-feature digest, runtime image identity and saved archive hash. The inactive static CUDA profile preserves its original six-file contract and has no hosted compiler or license receipt qualification. Its runner and build inputs are unchanged.
Publication creates a draft prerelease, streams the exact verified assets, checks response names/sizes, and validates the returned UUID before accepting either the exact same-origin repository/tag/asset download URL or one of the existing exact attachment paths for that UUID, then rereads the remote bytes to compare size and SHA256. It allows at most two same-origin redirects, restricted to attachment paths for the UUID returned by that asset upload. Only then does it remove draft status. Other redirect paths, queries, credentials and foreign asset URLs are rejected; tokens are not forwarded to them. HTTPS verifies certificates; plaintext is accepted only for loopback API fixtures. API error bodies are not printed. An upload or verification failure leaves a draft, and does not publish an incomplete release. A retry uses a fresh run attempt tag; existing release cleanup is an operator action. Gitea previews do not inherit the former GitHub artifact seven-day retention; retention is an operator policy.
Receipts record CI/operator-declared source identity, not binary-to-source attestation. GPU/model qualification stays false; these publications do not establish inference quality, throughput, model readiness or deployment readiness. Synthetic tests exercise API streaming, remote corruption, interrupted uploads, exact profiles, forged rehashed receipts and the current producer validators. Real private Gitea publication remains a workflow qualification gate.
The download URL profile was checked against read-only Gitea release `cuda-preview-2495-1` on git.vezha.io: `/para/leleka/releases/download/{tag}/{asset}`. Gitea 1.27.3 [RedirectDownload](https://raw.githubusercontent.com/go-gitea/gitea/v1.27.3/routers/web/repo/repo.go) finds releases by repository/tag and includes drafts for writers; it serves the associated attachment without requiring a Git tag to exist. Synthetic tests verify download and redirect hashing while the release is still draft and before tag publication, and prove that foreign redirects receive no request or token. Actual fresh CI publication remains unqualified until that gate succeeds.
Publication jobs request `contents: read` and the Gitea-specific `releases: write` permission on their built-in job token; the workflow default and nonpublication jobs keep read-only permissions. This follows the [Gitea 1.27 token-permission contract](https://docs.gitea.com/1.27/usage/actions/token-permissions/). Owner/repository maximums can still clamp the effective token; the real publication gate must succeed before qualification. No stored PAT is read or created.
Gitea 1.27.3 fresh-upload POST and later GET/list metadata can expose different
URLs. [Attachment.DownloadURL](https://raw.githubusercontent.com/go-gitea/gitea/v1.27.3/models/repo/attachment.go)
uses the instance attachment route when the freshly created attachment has no
custom URL; subsequent [release attribute loading](https://raw.githubusercontent.com/go-gitea/gitea/v1.27.3/models/repo/release.go) can populate the repository
release route when attachment names are unique. The publisher admits the same narrowly bound UUID attachment
routes at the initial hop as at redirect hops. Origin, port, path, UUID, query,
fragment, credentials, two-redirect bound, byte count and remote SHA checks remain
mandatory. Synthetic POST tests cover each admitted attachment form, corruption,
invalid/mismatched UUIDs, foreign URLs and wrong repositories without forwarding
a token. This source-derived correction is not proof of fresh private CI publication;
that remains an actual workflow gate.
+122
View File
@@ -0,0 +1,122 @@
# IQ2_S / IQ3_XXS CPU reference parity
GGUF kind 22 (IQ2_S) and kind 18 (IQ3_XXS) preparation decoding now have
explicit Rust routes. This is a bounded quantization port, not a complete
independent inference engine or a model/GPU qualification. No model, request,
user-agent data or server is used by these synthetic CPU tests.
## Pinned layout and provenance
Actual oracle values come from unchanged vendored GGML C at llama.cpp
`3cf03257f219afbe7334045ff7c6a06ac68c627d`, also pinned by imported Strata
`d9ab8435f654c368c586340d490915f6addf56a3`. Original MIT notice and upstream
records remain [in the crate](../crates/quant-core/LICENSE-GGML) and
[in the GGML provenance](../control-plane/third_party/ggml/UPSTREAM.md).
The production C bridge, compiler arithmetic flags, prior 24 oracle tests
and 13 visitor test functions remain byte-preserved.
IQ2_S: 82 bytes / 256 outputs. FP16 LE header at 0–1, 32 grid low bytes at
2–33, 32 raw sign masks at 34–65, eight packed two-bit grid-high bytes at
66–73, eight two-nibble scales at 74–81. Each eight-output group addresses
one 1024-entry eight-byte grid; two groups share each subscale.
Arithmetic preserves `(d * (0.5 + nibble)) * 0.25`, then magnitude multiply,
then sign multiply, without changing evaluation order.
IQ3_XXS: 98 bytes / 256 outputs. FP16 header at 0–1; 64 byte-sized four-value
grid indexes at 2–65; eight little-endian scale/sign u32 words at 66–97.
Each word has four seven-bit sign-table indexes and one high four-bit scale.
Two grids supply the first/second four values of each eight-output group.
Arithmetic preserves `(d * (0.5 + nibble)) * 0.5`, magnitude, then sign.
An independent test parses only each table declaration from pinned C, checks
its count, serializes little-endian values and hashes the entire byte stream.
These hashes match the independent Rust table provenance gates:
| Table | Bytes | SHA256 |
|---|---:|---|
| IQ2_S grid | 8192 | `e1aa1473412b0552c2174c30ef22ab4073f6a181b85a17056e8249bd2932fd88` |
| IQ3_XXS grid | 1024 | `46e35f5a997efdee6c99ce57854c8a0d4f0ff8ca57e5e8a60c0793ea580acf5d` |
| Sign table | 128 | `a76742a603f8beca5212ecce0f1f02f11a4887fd2f7c8b15aca0ea3eb3380c31` |
| Bit masks | 8 | `5ac9831b2e30eb285ef34f8501620f878432d5c04331ad1ae47f977a83ba41a5` |
All FP16 encodings are admitted as before. NaN classification must match;
every other output, including signed zero and infinity signs, matches exact
bits. Neither grid contains zero magnitudes and `(0.5 + nibble)` is positive:
zero packed fields are valid, but are not a zero multiplicative factor for an
infinite header in these formats. Signed-zero headers are explicitly tested.
NaN payload/sign equivalence is not claimed.
## Independent coverage and counts
Synthetic wire packing, parsed C sign coverage and raw-field bookkeeping do
not call Rust decoder helpers. Every expected numerical value is actual C output.
- All **63,488 finite FP16 headers** for both formats: **32,505,856** comparisons.
- IQ2_S **1024** independent patterns require every grid index at all 32
eight-value positions, all 256 raw sign masks at each position, both output
signs at every lane, and all 16 subscale nibbles at every one of 16 positions:
**262,144** comparisons.
- IQ3_XXS **2048** patterns require every grid index at all 64 four-value
positions, all 128 sign codes at all 32 groups, both signs at every output
lane and all 16 scale nibbles at all eight positions: **524,288** comparisons.
- Raw-byte bijections require every byte value at all 80/96 packed-field
positions respectively: **131,072** comparisons.
- Sixteen finite boundary blocks per format through aligned and deliberately
unaligned bulk inputs: **16,384** comparisons. Empty/truncated input and
short/long output reject without changing Rust/C sentinel output.
- All **2048 nonfinite FP16 headers** per format with generated and all-zero
packed fields preserve NaN class and every non-NaN bit pattern.
Total finite comparisons: **33,439,744**, zero tolerance. This covers separate
header/grid/sign/subscale domains and every field position; it does not exhaust
the full joint header × grid × sign × subscale space or arbitrary packed data.
## Bounded visitor
Only kinds 18/22 gain Rust branches, with geometry agreement checked before
seek. Source cap and other routes are unchanged. Synthetic tensors cross two
callbacks, checking exact C bytes, offsets/slices, bounded buffers, receipts,
no seek/callback for malformed shapes, no partial callback on early/late
truncation and no later read after first/second callback failure. Nonfinite,
signed-zero and zero-field fixtures preserve the pinned C value policy.
```sh
cargo test --locked -p leleka-quant-core
cargo clippy --locked -p leleka-quant-core --all-targets -- -D warnings
cargo test --locked -p strata-control --lib ggml_bridge::tests -- --test-threads=2
cargo test --locked -p strata-control --lib gguf_f32_stream::tests
```
## Actual results
Local CPU gates, 2026-10-07, Darwin arm64; Rust 1.99.0
(`b940084d7 2026-09-28`), Apple Clang 21.0.0 (`clang-2100.1.1.101`).
C arithmetic flags and zero tolerance unchanged.
- Standalone quant-core: **36 passed, 0 failed** (eight new tests), all-target
Clippy with warnings denied, owned formatting/whitespace and dependency tree
passed. Every Rust grid/sign entry was independently compared with pinned C
and whole-table canonical byte hashes matched. The one owned private target
was cleaned (385 files, 19.3 MiB) and its directory removed.
- Actual C reference suite: **30 passed, 0 failed**, including six new tests
and all 24 prior functions byte-preserved. All **33,439,744** new finite
exact-bit comparisons passed with zero mismatch; every grid, sign, scale and
raw-field position coverage assertion passed, as did independent complete C
table hashes, all nonfinite encodings, zero-field, bulk and shape gates.
The full suite took 9.46 seconds; this is test runtime, not model throughput.
- Visitor: **15 passed, 0 failed**, including two new tests and 13 prior
functions byte-preserved. IQ2_S raw chunks were **28,126 / 1,394 bytes**, F32
**351,232 / 17,408 bytes**. IQ3_XXS raw chunks were **28,126 / 1,666 bytes**,
F32 **293,888 / 17,408 bytes**. Bounds, source offsets, receipts, no-seek
malformed-shape behavior, early/late truncation, both callback-abort positions
and nonfinite/signed-zero/zero-field gates passed.
- Control-plane library/tests Clippy with warnings denied, full formatting,
diff check and all ten vendored C manifest hashes passed. The normal quant
dependency tree contains only the independent crate. The coordinated shared
control-plane target cache was retained; no private control-plane target or
experimental artifact was created.
No numeric mismatch, tolerance change or quality-gate weakening was observed.
Linux/compiler qualification, real model/GPU inference, model quality and paired
performance are separate. No end-to-end speed or inference-readiness claim.
+63
View File
@@ -0,0 +1,63 @@
# IQ3_S CPU reference parity
The Rust IQ3_S decoder uses the 256-value / 110-byte block layout and grid pinned
to Strata `d9ab8435f654c368c586340d490915f6addf56a3`. Its offline C oracle is the
vendored GGML decoder from llama.cpp `3cf03257f219afbe7334045ff7c6a06ac68c627d`,
recorded in [GGML provenance](../control-plane/third_party/ggml/UPSTREAM.md).
The existing control-plane bridge statically compiles that pinned CPU code. The
independent Rust quantization crate does not depend on the C oracle or bridge.
No upstream source or pin is changed for these tests.
The new bridge test exhausts all **63,488 finite FP16 scale encodings**: both
signed zeros, every positive/negative subnormal, every positive/negative normal,
and the maximum finite scale of either sign. Each gets a deterministic generated
110-byte block with varied packed fields. An explicit byte bijection at each
field position guarantees all 256 byte values over a complete low-pattern-byte
sweep; high-pattern-byte and position mixing vary the joint block patterns. Coverage assertions require every
8-bit low-index, high-index and sign value at every corresponding field position,
every scale nibble at every subblock, and all 512 combined grid indexes.
Every one of the 256 decoded values is compared with `f32::to_bits()` against
the pinned C output: the tolerance is **zero**, including signed zero. This is
63,488 blocks / 16,252,928 element comparisons. It exhausts the FP16 scale domain
and observes each packed field value; it does not exhaust all possible joint
combinations of the 108 packed bytes. A separate 14-block contiguous batch
checks the same exact-bit contract through both `decode_into` paths with a
source pointer deliberately unaligned for the C bridge.
The Rust decoder's existing error for a NaN or infinity block scale is retained.
All **2,048 nonfinite FP16 encodings** are tested for refusal by both Rust entry
points. They are outside the C numerical parity domain, and are never silently
skipped as successful parity cases. The existing pinned block-size, original mixed IQ3_S block and known
Q8_0/Q2_0 tests are retained.
Fixtures are generated synthetic packed bytes, not model weights or captures.
These checks qualify CPU block decoding only. They do not establish real-model
parity, inference quality, readiness, GPU behavior or a performance improvement.
The eventual production engine must qualify its own load, arithmetic and model
semantics independently.
## Targeted gate
```sh
cargo test --locked -p strata-control --lib ggml_bridge::tests
```
## Actual local CPU result, 2026-10-07
- Rust: `rustc 1.99.0 (b940084d7 2026-09-28)`.
- Host target: `aarch64-apple-darwin` (Darwin arm64).
- C compiler: Apple Clang 21.0.0 (`clang-2100.1.1.101`).
- Command above: **6 passed, 0 failed** (172 unrelated tests filtered).
- Finite-scale element bits, every packed-field coverage assertion, unaligned
batch parity and all nonfinite-scale refusals passed.
- Vendored GGML manifest hashes were checked before the run. The production
bridge body and the three original bridge tests remain unchanged.
The first draft generator passed every numerical comparison but failed its
sign-byte coverage assertion. The generator was corrected to the explicit byte
bijection described above; all exact-bit and coverage assertions were retained,
and the complete targeted gate was rerun successfully. No decoder arithmetic or
numerical tolerance was changed. Both private temporary build targets were
cleaned. This result applies to this CPU/compiler configuration; Linux/GCC,
real-model and GPU qualification remain separate.
+93
View File
@@ -0,0 +1,93 @@
# IQ4_NL CPU reference parity
The pure Rust `leleka_quant_core::iq4_nl` decoder implements GGUF kind 20:
18 bytes produce 32 F32 values. Bytes 0–1 hold a little-endian FP16 scale and
bytes 2–17 hold codepoint pairs. The low nibble at byte `2+j` produces element
`j`; the high nibble produces element `j+16`. Multiplication uses the existing
binary16-to-binary32 helper and the signed nonlinear codebook:
```text
-127 -104 -83 -65 -49 -35 -22 -10 1 13 25 38 53 69 89 113
```
The arithmetic/table oracle is the unmodified vendored
`ggml-quants.c::dequantize_row_iq4_nl` and `ggml-common.h::kvalues_iq4nl` from
llama.cpp `3cf03257f219afbe7334045ff7c6a06ac68c627d`, also pinned by imported
Strata `d9ab8435f654c368c586340d490915f6addf56a3`. Source hashes and license
remain in [GGML provenance](../control-plane/third_party/ggml/UPSTREAM.md);
the quant crate's [MIT notice](../crates/quant-core/LICENSE-GGML) is retained.
No upstream source, table or pin is changed. The independent Rust crate has no
C/FFI, GGML, Strata, Python or CUDA build/runtime dependency.
## Numerical and API gates
The new control-plane oracle exhausts all **63,488 finite FP16 scale encodings**,
including both signed zeros, every signed subnormal and normal, and both signs
of the maximum finite value. For every scale its independently generated block
covers all 16 codepoints in each output half. Every decoded value is compared
with the actual pinned C decoder using `f32::to_bits()`: **zero tolerance**,
including signed zero. This is **2,031,616 element comparisons**. Coverage
assertions additionally require all 256 packed byte values at every one of the
16 byte positions and all 16 codepoints at every one of the 32 output positions.
This exhausts the scale/codepoint combinations but not the joint space of all
16 packed bytes. A separate 14-block batch compares exact output bits through
both bulk APIs with deliberately unaligned input, exercising the existing C
bridge's alignment-copy path.
All **2,048 nonfinite FP16 scale encodings** are admitted by both Rust APIs and
the C oracle, preserving IQ4_NL's existing consumer behavior. The two infinity
encodings require exact output bits/signs. All 2,046 NaN encodings require NaN
classification; no portable NaN payload or sign equivalence is claimed. The
existing IQ3_S refusal of nonfinite scales is unchanged. Existing consumers
keep their own rejection or downstream value policies.
Standalone tests check independent expected codebook values and split-half
order, signed zero, nonfinite admission, multiple blocks, empty input/output,
malformed input blocks and incorrect output lengths. Invalid shapes leave the
entire caller output unchanged. The decoder allocates no heap buffer and decodes
into caller-owned storage. The visitor remains bounded and retains errors and
consumer receipts; other format branches are unchanged.
Only generated synthetic fixtures are used. Tracked Qwen evidence identifies
IQ4_NL expert/shared-expert/PLE tensors in
[historical validation](build-validation.md), but this gate reads no weights.
This qualifies CPU decoding and bounded preparation integration, not complete
model support, immutable weights, readiness, GPU behavior, model quality or
performance. Other target formats still require C; the control-plane build
still compiles its legacy GGML oracle. Removing that build dependency is a
separate task.
## Targeted commands
```sh
cargo test --locked -p leleka-quant-core
cargo clippy --locked -p leleka-quant-core --all-targets -- -D warnings
cargo test --locked -p strata-control --lib ggml_bridge::tests
cargo test --locked -p strata-control --lib gguf_f32_stream::tests
```
## Actual local CPU result, 2026-10-07
- Rust: `rustc 1.99.0 (b940084d7 2026-09-28)`.
- Host: `aarch64-apple-darwin` (Darwin arm64).
- C compiler: Apple Clang 21.0.0 (`clang-2100.1.1.101`).
- Quant crate: **5 passed, 0 failed**, including three new IQ4_NL tests;
standalone Clippy with warnings denied passed.
- Bridge oracle: **9 passed, 0 failed** (177 unrelated tests filtered), including
three new IQ4_NL tests. All 2,031,616 finite-scale element comparisons,
packed-field/codepoint coverage assertions, unaligned batch comparisons and
all nonfinite admission/classification/infinity-sign comparisons passed.
- QA's separate visitor gate: **7 passed, 0 failed**. Its new finite fixture
compared 1,821 blocks with C output across two callbacks: source chunks
28,152 and 4,626 bytes (cap 28,160), derived chunks 200,192 and 32,896 bytes.
Shape rejection before seek/callback, early/late truncation, callback abort
at either chunk, and nonfinite classification/infinity signs passed.
- Vendored GGML manifest hashes, owned-file formatting and `git diff --check`
passed. The production C bridge body and all six earlier bridge test
functions remain byte unchanged. The private oracle build target was cleaned.
No finite numeric mismatch was observed, and no numerical tolerance was relaxed.
NaN payload/sign differences were not measured; the nonfinite gate compares the
explicit classification/admission contract above. These results apply to this
CPU/compiler configuration; Linux/GCC, real-model and GPU qualification remain
separate.
+120
View File
@@ -0,0 +1,120 @@
# Q4_K / Q5_K CPU reference parity
This port implements GGUF kind 12 (Q4_K) and kind 13 (Q5_K) preparation decoding
in the independent standard-library-only Rust quant crate. It does not replace
the complete engine or prove model/GPU readiness. Other preparation formats still
use the legacy C decoder. No model weights, request data or user experiments are
read by these gates.
## Pinned layout and arithmetic
The oracle is actual output from the unmodified vendored GGML C decoder at
llama.cpp `3cf03257f219afbe7334045ff7c6a06ac68c627d`, also pinned by imported
Strata `d9ab8435f654c368c586340d490915f6addf56a3`. The source hashes and original
MIT license remain in [GGML provenance](../control-plane/third_party/ggml/UPSTREAM.md)
and [the quant crate notice](../crates/quant-core/LICENSE-GGML).
The production C bridge, prior fourteen oracle tests and compiler arithmetic
flags remain unchanged.
Both formats output 256 values and have two independent little-endian FP16
header values: `d` at bytes 0–1 and `dmin` at 2–3. Twelve packed scale/minimum
bytes occupy 4–15. Q4_K is 144 bytes with four 32-byte nibble groups at 16–143.
Q5_K is 176 bytes with a shared 32-byte high-bit bank at 16–47 and nibble groups
at 48–175. Each pair produces two consecutive 32-element halves. The Q5 bank
reuses each lane byte with masks 1/2, 4/8, 16/32 and 64/128 across the four pairs.
Six-bit scale/minimum unpacking preserves the different lower/upper field
locations for subblocks 0–3 and 4–7.
The arithmetic retains separate operations in C order: `d * subscale`,
`dmin * subminimum`, then `scaled_d * quant - scaled_minimum`. The Rust code does
not use `mul_add`; this gate does not change C contraction or fast-math flags.
All FP16 header encodings are admitted, preserving the old C value policy.
Infinity multiplied by zero and infinity subtraction can yield NaN. Shape
errors leave caller output untouched; downstream consumers keep their own
value policies. Signed-zero output bits are part of finite parity; NaN payload
or sign equivalence is not claimed.
## Independent coverage
Expected numerical output always comes from the pinned C decoder, never from
the new Rust implementation or its packed-scale helper. Generated bytes and
coverage bookkeeping are independent of those production functions.
- For each format, every one of the **63,488 finite FP16 encodings** is exercised
separately in the `d` role with `dmin=0.5` and the `dmin` role with `d=-1`.
These sweeps contribute **65,011,712** exact element comparisons across the
two formats and roles. They do not exhaust both FP16 values jointly.
- Each format separately compares **65,536 independently generated packed
patterns** with fixed finite scales. Assertions require every byte value at
every packed scale/minimum field and quant field; every six-bit subscale and
minimum at every one of eight positions; every quant code at every output
position; and, for Q5_K, every byte value at each high-bank lane. Each block
additionally covers all 16 Q4 codes or 32 Q5 codes in each output half. These
cases contribute **33,554,432** comparisons.
- A **20×20** joint finite boundary matrix includes positive/negative zero,
signed minimum/largest subnormals, normal boundaries, adjacent-to-one values
and maximum finite values. Twenty further equal-scale fixtures per format
explicitly require exact cancellation to positive zero. These contribute
**215,040** comparisons.
- Sixteen-block boundary batches per format run with both 16-byte aligned and
deliberately unaligned inputs through both bulk APIs, adding **16,384**
comparisons. Invalid input/output lengths must reject before changing any
sentinel output, for both the Rust and C APIs.
- Every **2,048 nonfinite FP16 encoding** is exercised in each header role for
each format with independently packed fields and explicit all-zero packed
fields. A **10×10** joint matrix includes finite, zero, infinity and NaN
headers. NaN classification must agree and every non-NaN output must match
exact bits, including infinity signs and any finite zero.
All finite gates use exact `f32::to_bits()` equality and zero tolerance.
The finite corpus contributes **98,797,568** comparisons. It does not exhaust
all 63,488² finite header pairs, all combinations of packed fields, or every
scale/code combination at every header pair.
## Bounded visitor
Only kinds 12 and 13 gain new Rust routes. Their decoder/metadata geometry must
agree before seek; other format branches and the source cap remain unchanged.
A synthetic tensor per format crosses two callbacks, verifying the actual C
bytes, exact source offsets, total F32 byte receipt and bounded source/derived
slices. Empty/misaligned shapes reject before seek or callback; first/late
truncation never delivers a partial chunk; callback failure at either callback
stops later reads. Nonfinite joint headers and zero packed fields retain C
classification and all non-NaN output bits. Previous nine visitor tests remain.
```sh
cargo test --locked -p leleka-quant-core
cargo clippy --locked -p leleka-quant-core --all-targets -- -D warnings
cargo test --locked -p strata-control --lib ggml_bridge::tests -- --test-threads=2
cargo test --locked -p strata-control --lib gguf_f32_stream::tests
```
## Actual local CPU result, 2026-10-07
- Rust: `rustc 1.99.0 (b940084d7 2026-09-28)`.
- Host: `aarch64-apple-darwin` (Darwin arm64).
- C compiler: Apple Clang 21.0.0 (`clang-2100.1.1.101`), with unchanged C build
flags and no arithmetic tolerance or contraction-policy changes.
- Standalone quant crate: **20 passed, 0 failed** (eight new helper/Q4_K/Q5_K
tests). All-target Clippy with warnings denied and owned-file formatting passed.
The owned temporary target was cleaned and removed.
- Pinned C oracle: **19 passed, 0 failed**, including five new tests and all
fourteen prior tests byte preserved. All **98,797,568** new finite exact-bit
comparisons, every packed/subscale/minimum/code position coverage assertion,
both nonfinite header roles, explicit zero fields, joint edge matrices,
cancellation, aligned/unaligned bulk and shape-sentinel gates passed.
- Visitor: **11 passed, 0 failed**, including two new tests and all nine prior
visitor test functions byte preserved. Q4_K used source chunks 28,080/2,448
bytes and F32 chunks 199,680/17,408 bytes; Q5_K used 28,160/2,992 and
163,840/17,408 bytes. Offsets, receipts, all shape/truncation/callback gates
and nonfinite header/zero-field behavior passed.
- Control-plane library/test Clippy with warnings denied, formatting, diff and
all ten vendored GGML manifest hash checks passed. The production bridge and
C source remain unchanged; normal quant-crate dependency tree is crate-only.
The existing coordinated shared target cache was retained.
No finite mismatch was observed and no quality gate or tolerance was weakened.
NaN payload/sign equivalence is outside this classification contract. These
results apply to this CPU/compiler configuration; Linux/GCC qualification,
actual model/GPU inference, model quality and performance remain separate.
+111
View File
@@ -0,0 +1,111 @@
# Q6_K / Q2_0 CPU reference parity
GGUF kind 14 (Q6_K) and kind 42 (Q2_0) preparation decoding gains explicit
independent Rust routes. This does not replace the full inference engine.
Other unported preparation formats still use the C bridge; no GPU, model or
user-agent data is accessed by these synthetic CPU gates.
## Pinned reference and layout
Expected numeric output comes from the unchanged vendored GGML C implementation,
llama.cpp `3cf03257f219afbe7334045ff7c6a06ac68c627d` and imported Strata
`d9ab8435f654c368c586340d490915f6addf56a3`. Source hashes and original MIT notice
remain in [GGML provenance](../control-plane/third_party/ggml/UPSTREAM.md) and
[the crate notice](../crates/quant-core/LICENSE-GGML). The C bridge production
code, compiler arithmetic flags, nineteen previous oracle tests and eleven
previous visitor test functions remain unchanged.
Q6_K is 210 bytes / 256 outputs: low nibble bank 0–127, high two-bit bank
128–191, sixteen signed int8 subscales 192–207, little-endian FP16 header
208–209. Each 128-output half uses separate low/high/scale offsets; each has
four 32-output quadrants and two 16-lane subscale positions per quadrant.
Arithmetic keeps `(d * signed_subscale) * (six_bit_code - 32)` in C order.
Q2_0 is 18 bytes / 64 outputs: little-endian FP16 header 0–1 and sixteen
packed bytes 2–17. Four consecutive two-bit fields in each byte map to
`{-1, 0, 1, 2}` and multiply as `(code - 1) * d`, matching pinned C order.
Both formats admit every FP16 encoding as the old C consumers do. Inf times
zero subscale or zero signed quant yields NaN; all non-NaN values including
signed zero and infinity signs use exact bits. NaN payload/sign equivalence
is outside this classification contract. Bulk shape errors must not write
caller output.
## Independent synthetic coverage
The input generators and coverage bookkeeping never call Rust unpack helpers.
Every expected numeric value is actual C output, not a Rust-derived expectation.
- Every **63,488 finite FP16 encoding**: one Q6_K block and four Q2_0 blocks
per header. The four Q2 patterns put each code at every output position.
This contributes **32,505,856** finite comparisons.
- Every **256 signed subscale × 64 quant code** pair at each of Q6_K's 256
output positions with one fixed finite header; assertions cover both halves,
all quadrants/lanes and every subscale location. This contributes
**4,194,304** comparisons.
- Independent byte bijections exercise every one of 256 byte values at all
208 Q6 packed-field positions and all sixteen Q2 packed-byte positions.
Q2 coverage additionally requires every code at all 64 consecutive outputs.
These contribute **81,920** comparisons.
- Sixteen-block finite boundary batches through aligned and deliberately
unaligned bulk slices contribute **10,240** comparisons. Empty/truncated
source and short/long output shapes reject before modifying sentinel output,
in both Rust and C APIs.
- Every **2,048 nonfinite FP16 encoding** is tested for Q6 generated fields,
explicit zero subscales and explicit zero signed quants, and Q2's four
code-position patterns. NaN class agrees; every non-NaN output matches bits.
Total finite comparisons: **36,792,320**, with zero tolerance.
This exhausts separate domains, not the full FP16 × signed-subscale × quant
joint space, all arbitrary packed-field combinations or NaN payloads.
## Bounded visitor
Only kinds 14 and 42 gain routes; geometry agreement is checked before seek.
The source cap and other routes are unchanged. Synthetic tensors cross two
callbacks: exact C bytes, source offsets/slices, bounded derived buffers and
F32 byte receipts are checked. Malformed shapes do not seek or call back;
early/late truncation cannot deliver partial chunks; callback failure at the
first or second callback stops further reads. Nonfinite and signed-zero
headers with explicit zero factors retain C output semantics.
```sh
cargo test --locked -p leleka-quant-core
cargo clippy --locked -p leleka-quant-core --all-targets -- -D warnings
cargo test --locked -p strata-control --lib ggml_bridge::tests -- --test-threads=2
cargo test --locked -p strata-control --lib gguf_f32_stream::tests
```
## Actual results
Local CPU gates on 2026-10-07:
- Rust `1.99.0 (b940084d7 2026-09-28)`, Darwin arm64, Apple Clang 21.0.0
(`clang-2100.1.1.101`); unchanged C arithmetic flags and zero tolerance.
- Actual pinned C oracle: **24 passed, 0 failed**, including five new tests
and nineteen previous tests byte-preserved. All **36,792,320** new finite
comparisons and every field/per-position scale-code coverage assertion passed
with zero numerical mismatch. All nonfinite, zero-factor, bulk and sentinel
gates passed. The complete oracle runtime was 16.63 seconds, a test duration
rather than an inference performance result.
- Visitor: **13 passed, 0 failed**, including two new tests and eleven previous
functions byte-preserved. Q6 used raw chunks **28,140 / 3,570 bytes**, derived
chunks **137,216 / 17,408 bytes**. Q2 used raw **28,152 / 306 bytes**, derived
**400,384 / 4,352 bytes**. Offset, bounded-buffer, receipt, early/late truncation,
malformed-shape, first/second callback abort and nonfinite/zero-factor tests
passed.
- Control-plane library/tests Clippy with warnings denied, full workspace
formatting, diff checks, all ten vendored GGML source hash checks and
quant-core normal dependency tree passed. The tree contains only the
independent Rust crate, with no production dependencies.
- Standalone quant-core: **28 passed, 0 failed** (eight new: five Q6 and
three Q2 tests), all-target Clippy with warnings denied, formatting and
normal dependency tree passed. The initial 28/28 test run also passed;
a test-only temporary-vector lint was corrected to equivalent stack storage
before the final gate, with no arithmetic or assertion change. The final
owned temporary target was cleaned (359 files, 16.1 MiB) and removed; the
earlier Clippy target was also removed.
- Existing coordinated shared control-plane target cache retained; no new
private control-plane build target or test artifact was created.
Linux/compiler qualification, model/GPU inference, quality and paired end-to-end
performance are separate gates. No performance or inference-readiness claim is made.
+106
View File
@@ -0,0 +1,106 @@
# Q8_0 and IQ4_XS CPU reference parity
This source port replaces GGUF kind 8 (Q8_0) and kind 23 (IQ4_XS) preparation
arithmetic with independent Rust modules in `leleka-quant-core`. The crate has
no production dependency beyond the standard library and no C/FFI, Strata,
Python or CUDA build/runtime dependency. Remaining preparation formats still
use the control plane's existing GGML C decoder; complete inference remains
separate.
## Pinned layouts and arithmetic
The numerical oracle is the unchanged vendored `ggml-quants.c` from llama.cpp
`3cf03257f219afbe7334045ff7c6a06ac68c627d`, also pinned by imported Strata
`d9ab8435f654c368c586340d490915f6addf56a3`. Source hashes and MIT attribution
remain in [GGML provenance](../control-plane/third_party/ggml/UPSTREAM.md)
and [the crate's retained notice](../crates/quant-core/LICENSE-GGML).
No native source or compiler arithmetic flag is changed.
- Q8_0: 34 bytes / 32 values. The little-endian FP16 scale occupies bytes 0–1;
remaining bytes are signed int8 values, including -128. Each output preserves
the pinned C operand order: `signed_quant * scale`.
- IQ4_XS: 136 bytes / 256 values. FP16 scale occupies bytes 0–1, little-endian
packed high scale bits bytes 2–3, low scale nibbles bytes 4–7 and value nibbles
bytes 8–135. Eight subblocks each produce 32 outputs. The six-bit subscale is
biased by -32; the intermediate is `scale * signed_subscale`, followed by
multiplication with the shared nonlinear IQ4 codebook. Low/high value nibbles
retain the two 16-element output halves. The codebook shared with IQ4_NL is
unchanged; moving it does not change its values or pin.
Both APIs accept every FP16 scale encoding, matching their previous C paths.
Infinity times a zero Q8 quant or zero IQ4_XS subscale produces NaN. Consumers
retain responsibility for value admission. IQ3_S's existing nonfinite rejection
is unchanged. Shape errors reject before output writes, empty input/output is a
valid zero-block operation, and arbitrary input alignment requires no heap
allocation in the Rust decoders.
## Independent oracle scope
All fixtures are generated synthetic bytes; no model weights or user data are
read. Finite comparisons use actual pinned C decoder output and exact
`f32::to_bits()` equality, including signed zero, with zero numerical tolerance.
- Q8_0 exhausts all **63,488 finite FP16 encodings** and all **256 signed byte
codes at every scale**: **16,252,928** element comparisons. Coverage assertions
additionally require every byte code at every one of the 32 output positions.
- IQ4_XS exhausts all **63,488 finite FP16 encodings**, all **64 signed subscales
at each scale** and all **16 nonlinear codes at each subscale**. Eight blocks
per scale produce **130,023,424** element comparisons, including both output
halves. Coverage assertions require every subscale at every one of eight
subblock positions, all 256 packed byte values at each of 128 fields, and all
16 codepoints at each of 256 output positions.
- Every one of **2,048 nonfinite FP16 encodings** is admitted by both Rust bulk
APIs and C. NaN classification is compared; non-NaN infinities must match exact
bits/signs. Q8 infinity checks contain all signed codes including zero;
IQ4_XS checks contain every subscale including zero. No portable NaN payload
or sign equivalence is inferred.
- A separate 14-block finite boundary batch for each format compares both bulk
APIs using input intentionally one byte beyond a 16-byte boundary, exercising
the C bridge's alignment-copy behavior and Rust's alignment-free decoder.
- Standalone tests check independent expected values, signed zeros, lane layout,
multiple blocks, nonfinite admission and malformed shapes preserving output.
Root's separate bounded visitor tests cover integration, offsets, callback
aborts, truncation and F32 byte receipts.
These corpora cover the stated scalar scale/codepoint domains and field
positions. They do not exhaust the joint space of all packed bytes or all
combinations of different subblock scales in one block, qualify an entire model,
prove Linux/GCC parity, measure performance or exercise a GPU.
## Commands
```sh
cargo test --locked -p leleka-quant-core
cargo clippy --locked -p leleka-quant-core --all-targets -- -D warnings
cargo test --locked -p strata-control --lib ggml_bridge::tests -- --test-threads=2
cargo test --locked -p strata-control --lib gguf_f32_stream::tests
```
## Actual local CPU result, 2026-10-07
- Rust: `rustc 1.99.0 (b940084d7 2026-09-28)`.
- Host: `aarch64-apple-darwin` (Darwin arm64).
- C compiler: Apple Clang 21.0.0 (`clang-2100.1.1.101`).
- Standalone quant crate: **12 passed, 0 failed** (three new Q8_0 and four new
IQ4_XS tests); all-target Clippy with warnings denied passed. The initial
standalone tests passed, then Clippy found a test-only range predicate;
an equivalent range expression was applied and the final full scoped suite
and Clippy both passed. No decoder arithmetic or numerical gate was changed.
- Pinned C bridge oracle: **14 passed, 0 failed**, including five new tests and
all nine earlier tests byte preserved. The finite corpora's **146,276,352**
element comparisons, per-position coverage assertions, both unaligned batches
and all nonfinite classification/infinity-sign/zero cases passed.
- Bounded GGUF visitor: **9 passed, 0 failed**; both new formats' geometry guards,
two-chunk exact C bytes, source offsets, output byte receipts, malformed/truncated
input, callback failure stopping subsequent reads and nonfinite behavior passed.
- Control-plane library/test Clippy with warnings denied, formatting and diff
checks passed. All ten vendored GGML manifest hashes passed; production bridge
code, prior test functions and C compiler arithmetic flags are unchanged.
- The normal quant-crate dependency tree contains only `leleka-quant-core`.
Both owned temporary standalone build targets were removed; the separately
coordinated existing shared target cache was retained.
No finite numeric mismatch occurred and no tolerance was relaxed. The NaN gate
compares classification rather than payload/sign equivalence. These results
apply to this CPU/compiler configuration. Linux/GCC, real-model quality,
complete inference and GPU qualification remain separate gates.
+71 -7
View File
@@ -5,12 +5,14 @@ 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 json
import os
from pathlib import Path, PurePosixPath
import platform
import shutil
import stat
import tarfile
import tempfile
import time
@@ -54,21 +56,83 @@ def validate_lock(lock, manifest):
def extract(archive, destination, root_name):
if not root_name or '/' in root_name or '\\' in root_name or root_name in ('.','..'):
raise ValueError('invalid component root')
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:
if len(members)>50000 or any(x.size<0 for x in members) or sum(x.size for x in members)>6*1024**3:
raise ValueError('archive expansion limit exceeded')
seen=set()
seen={}
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:
raw_name=item.name
if not raw_name or '\x00' in raw_name or '\\' in raw_name or raw_name.startswith('/'):
raise ValueError('archive path outside component root')
if item.name in seen:
parts=raw_name.split('/')
if parts[-1]=='' and item.isdir():parts.pop()
if not parts or any(part in ('','.','..') for part in parts) or parts[0]!=root_name:
raise ValueError('archive path outside component root')
name='/'.join(parts)
if name in seen:
raise ValueError('duplicate archive member')
seen.add(item.name)
if name==root_name and not item.isdir():
raise ValueError('component root is not a directory')
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.mode & (stat.S_ISUID|stat.S_ISGID|stat.S_ISVTX):
raise ValueError('archive member has privileged mode bits')
clone=copy.copy(item);clone.name=name
if item.issym() or item.islnk():
link=item.linkname
if not link or '\x00' in link or '\\' in link or link.startswith('/'):
raise ValueError('archive link outside component root')
target=list(parts[:-1] if item.issym() else [])
for part in link.split('/'):
if part in ('','.'):continue
if part=='..':
if len(target)<=1:raise ValueError('archive link outside component root')
target.pop()
else:target.append(part)
if not target or target[0]!=root_name:
raise ValueError('archive link outside component root')
if item.islnk():clone.linkname='/'.join(target)
if item.isdir():
clone.mode=(item.mode & 0o755)|0o700
elif item.isfile():
clone.mode=(item.mode & 0o755)|0o600
if item.mode & 0o111:clone.mode|=0o100
# Never apply archive ownership. Numeric IDs are the builder's own
# identity; tarfile 3.11's root-only chown path therefore stays put.
clone.uid=os.geteuid();clone.gid=os.getegid();clone.uname=clone.gname=''
seen[name]=(item,clone)
for name,(item,_) in seen.items():
parts=name.split('/')
for depth in range(1,len(parts)):
parent='/'.join(parts[:depth])
if parent in seen and not seen[parent][0].isdir():
raise ValueError('archive member is nested under a non-directory')
if item.islnk():
target=item.linkname
if target not in seen or not (seen[target][0].isfile() or seen[target][0].islnk()):
raise ValueError('archive hard link target is missing or unsupported')
# Python 3.11 (Debian Bookworm) lacks tarfile's `filter=` argument.
# Every member is normalized and validated above before the legacy
# extractor sees it; links are constrained to the private component tree.
destination.mkdir(mode=0o700,parents=True,exist_ok=True)
if os.path.lexists(destination/root_name):raise ValueError('component root already exists')
(destination/root_name).mkdir(mode=0o700)
dirs=sorted((v[1] for v in seen.values() if v[0].isdir()),key=lambda x:(x.name.count('/'),x.name))
files=sorted((v[1] for v in seen.values() if v[0].isfile()),key=lambda x:x.name)
symlinks=sorted((v[1] for v in seen.values() if v[0].issym()),key=lambda x:x.name)
hardlinks={name:clone for name,(item,clone) in seen.items() if item.islnk()}
ordered_hardlinks=[];visiting=set();emitted=set()
def emit_hardlink(name):
if name in emitted:return
if name in visiting:raise ValueError('archive hard link cycle')
visiting.add(name);target=hardlinks[name].linkname
if target in hardlinks:emit_hardlink(target)
visiting.remove(name);emitted.add(name);ordered_hardlinks.append(hardlinks[name])
for name in sorted(hardlinks):emit_hardlink(name)
source.extractall(destination,members=dirs+files+ordered_hardlinks+symlinks,numeric_owner=True)
return destination/root_name
+120 -2
View File
@@ -14,7 +14,9 @@ import platform
import re
import shutil
import subprocess
import sys
import tempfile
import uuid
REPO = Path(__file__).resolve().parents[1]
TARGET = 'x86_64-unknown-linux-musl'
@@ -31,6 +33,43 @@ def sha256(path):
return hashlib.file_digest(source, 'sha256').hexdigest()
def build_features(path, revision):
"""Read a bounded, exact-schema static CUDA feature receipt without following links."""
if path is None:
return None
fd = os.open(path, os.O_RDONLY | os.O_NONBLOCK | os.O_NOFOLLOW)
with os.fdopen(fd, 'rb') as source:
if not stat.S_ISREG(os.fstat(source.fileno()).st_mode):
raise ValueError('build feature receipt must be a regular file')
raw = source.read(65537)
if len(raw) > 65536:
raise ValueError('build feature receipt exceeds size limit')
try:
record = json.loads(raw)
except (UnicodeDecodeError, json.JSONDecodeError) as error:
raise ValueError('build feature receipt must be UTF-8 JSON') from error
if (not isinstance(record, dict) or set(record) != {
'schema_version', 'source_revision', 'cuda_architectures', 'features'} or
type(record['schema_version']) is not int or record['schema_version'] != 1 or
record['source_revision'] != revision or
not isinstance(record['cuda_architectures'], str) or
not re.fullmatch(r'[0-9]+(?:-(?:real|virtual))?(?:;[0-9]+(?:-(?:real|virtual))?)*',
record['cuda_architectures'])):
raise ValueError('unsupported or source-mismatched build feature receipt')
canonical = (json.dumps(record, sort_keys=True, indent=2) + '\n').encode()
if raw != canonical:
raise ValueError('build feature receipt is not canonical JSON')
features = record['features']
if (not isinstance(features, dict) or set(features) != {
'cuda', 'cuda_static_runtime', 'cxx_static_runtime', 'kar_ple', 'kar_experts', 'ple_trace'} or
any(type(value) is not bool for value in features.values()) or
features['cuda'] is not True or features['cuda_static_runtime'] is not True or
features['cxx_static_runtime'] is not True or
features['kar_experts'] is not False or features['ple_trace'] is not False):
raise ValueError('build feature receipt violates the static CUDA PLE package contract')
return record, hashlib.sha256(raw).hexdigest()
def source_check(repo, revision):
if not re.fullmatch(r'[0-9a-f]{40}', revision):
raise ValueError('source revision must be a full lowercase Git SHA')
@@ -68,6 +107,74 @@ def static_outer(binary):
return {'program_headers': headers, 'dynamic_section': dynamic}
def loader_probe(binary, probe, audit, container=False):
if not container:
run([binary, 'provision', '--config', probe],
env={'PATH': os.defpath, 'CUDA_VISIBLE_DEVICES': '',
'NVIDIA_VISIBLE_DEVICES': 'void'}, timeout=30)
return {'environment': 'assembly-host'}
# Use the same immutable base as the runtime image. A CPU runner's libc
# need not satisfy the separately audited embedded engine's libc baseline.
spec = importlib.util.spec_from_file_location('runtime_image', REPO / 'scripts/build-runtime-image.py')
runtime = importlib.util.module_from_spec(spec)
spec.loader.exec_module(runtime)
runtime.docker('pull', '--platform', 'linux/amd64', runtime.BASE, timeout=300)
glibc = runtime.check_glibc({'engine_elf_audit': audit},
runtime.isolated_run(runtime.BASE, ['GNU_LIBC_VERSION'], entrypoint='getconf'))
image_id = runtime.docker('image', 'inspect', '--format', '{{.Id}}', runtime.BASE).stdout.strip()
name = 'strata-package-probe-' + uuid.uuid4().hex
staging_name = name + '-stage'
volume = name
try:
with tempfile.TemporaryDirectory(prefix='strata-package-probe-') as tmp:
copied = Path(tmp) / 'cli'
shutil.copyfile(binary, copied)
copied.chmod(0o755)
config = Path(tmp) / 'probe.json'
shutil.copyfile(probe, config)
config.chmod(0o644)
runtime.docker('volume', 'create', volume)
runtime.docker('create', '--name', staging_name, '--platform', 'linux/amd64',
'--network', 'none', '--cap-drop', 'ALL',
'--mount', 'type=volume,source=' + volume + ',target=/probe',
'--entrypoint', '/bin/true', runtime.BASE)
# The staging container is never started. The serving probe receives
# only a read-only volume, so docker cp cannot mutate its rootfs.
runtime.docker('cp', copied, staging_name + ':/probe/cli', timeout=180)
runtime.docker('cp', config, staging_name + ':/probe/probe.json')
runtime.docker('create', '--name', name, '--platform', 'linux/amd64',
'--network', 'none', '--read-only', '--user', '65532:65532',
'--cap-drop', 'ALL', '--security-opt', 'no-new-privileges',
'--tmpfs', '/tmp:rw,nosuid,nodev,size=1g',
'--mount', 'type=volume,source=' + volume + ',target=/probe,readonly',
'-e', 'CUDA_VISIBLE_DEVICES=', '-e', 'NVIDIA_VISIBLE_DEVICES=void',
'-e', 'LD_LIBRARY_PATH=', '--entrypoint', '/bin/sh', runtime.BASE,
'-c', 'for p in /dev/nvidia*; do if [ -e "$p" ]; then '
'echo "package probe refuses NVIDIA devices" >&2; exit 1; fi; done; '
'exec /probe/cli "$@"',
'package-probe', 'provision', '--config', '/probe/probe.json')
result = runtime.docker('start', '--attach', name, timeout=60, check=False)
code = runtime.docker('inspect', '--format', '{{.State.ExitCode}}', name).stdout.strip()
if result.returncode != 0 or code != '0':
raise ValueError('pinned runtime package provision failed: ' + result.stderr.strip())
finally:
original_failure = sys.exc_info()[0] is not None
errors = []
for command in [('rm', '-f', name), ('rm', '-f', staging_name), ('volume', 'rm', volume)]:
try:
cleaned = runtime.docker(*command, check=False)
if cleaned.returncode and 'No such ' not in cleaned.stderr:
errors.append(cleaned.stderr.strip())
except (OSError, subprocess.SubprocessError) as error:
errors.append(str(error))
if errors:
print('Package probe cleanup failed: ' + '; '.join(errors), file=sys.stderr)
if not original_failure:
raise ValueError('owned package probe cleanup failed')
return {'environment': 'pinned-runtime-container', 'base': runtime.BASE,
'image_id': image_id, 'glibc': glibc, 'user': '65532:65532', 'gpu_tested': False}
@contextlib.contextmanager
def lock(path):
# Caller-controlled build/output paths are private; keep the inode for reuse.
@@ -96,6 +203,9 @@ def assemble(args):
if platform.system() != 'Linux' or platform.machine() != 'x86_64':
raise ValueError('package assembly requires Linux x86_64')
source_check(REPO, args.revision)
features = build_features(getattr(args, 'build_features', None), args.revision)
if args.cpu_fixture and features is not None:
raise ValueError('CPU fixtures cannot claim CUDA build features')
output = args.output.absolute()
output.parent.mkdir(parents=True, exist_ok=True)
output = output.parent.resolve() / output.name
@@ -139,16 +249,20 @@ def assemble(args):
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)
loader = loader_probe(binary, probe, audit,
getattr(args, 'probe_in_runtime_image', False))
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_elf_audit': audit, 'outer_elf_audit': outer,
'cargo_lock_sha256': sha256(REPO / 'control-plane/Cargo.lock'),
'loader_probe': loader,
'cargo_lock_sha256': sha256(REPO / '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.',
'source_provenance': 'Operator/CI-declared engine revision, not binary-to-source attestation.'}
if features is not None:
provenance['build_features'], provenance['build_features_sha256'] = features
(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']))
if os.path.lexists(output):
@@ -165,6 +279,10 @@ 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('--build-features', type=Path,
help='exact build feature receipt emitted by build-static-cuda.sh')
parser.add_argument('--probe-in-runtime-image', action='store_true',
help='execute actual provision in the pinned runtime base instead of the assembly host')
args = parser.parse_args()
try:
print(json.dumps(assemble(args)))
+29
View File
@@ -62,6 +62,32 @@ def freeze(package, stage, receipt_sha, cpu_fixture):
p.get('target') != 'x86_64-unknown-linux-musl' or
not re.fullmatch(r'[0-9a-f]{40}', p.get('source_revision', ''))):
raise ValueError('unsupported package provenance or explicit fixture mode mismatch')
feature_record = p.get('build_features')
feature_sha = p.get('build_features_sha256')
if feature_record is not None or feature_sha is not None:
if (not isinstance(feature_record, dict) or set(feature_record) != {
'schema_version', 'source_revision', 'cuda_architectures', 'features'} or
type(feature_record['schema_version']) is not int or feature_record['schema_version'] != 1 or
feature_record['source_revision'] != p['source_revision'] or
not isinstance(feature_record['cuda_architectures'], str) or
not re.fullmatch(r'[0-9]+(?:-(?:real|virtual))?(?:;[0-9]+(?:-(?:real|virtual))?)*',
feature_record['cuda_architectures']) or
not isinstance(feature_sha, str) or
not re.fullmatch(r'[0-9a-f]{64}', feature_sha)):
raise ValueError('invalid static CUDA build feature provenance')
feature_values = feature_record['features']
if (not isinstance(feature_values, dict) or set(feature_values) != {
'cuda', 'cuda_static_runtime', 'cxx_static_runtime', 'kar_ple', 'kar_experts', 'ple_trace'} or
any(type(value) is not bool for value in feature_values.values()) or
feature_values['cuda'] is not True or feature_values['cuda_static_runtime'] is not True or
feature_values['cxx_static_runtime'] is not True or
feature_values['kar_experts'] is not False or feature_values['ple_trace'] is not False):
raise ValueError('invalid static CUDA feature selection')
canonical = (json.dumps(feature_record, sort_keys=True, indent=2) + '\n').encode()
if hashlib.sha256(canonical).hexdigest() != feature_sha:
raise ValueError('static CUDA build feature digest mismatch')
elif not cpu_fixture:
raise ValueError('CUDA package lacks an explicit build feature receipt')
engine = p.get('engine', {})
if (engine.get('embedded') is not True or engine.get('target_os') != 'linux' or
engine.get('target_arch') != 'x86_64' or
@@ -140,6 +166,9 @@ def assemble(args):
'package_receipt_sha256': args.receipt_sha256, 'source_revision': p['source_revision'],
'kind': p['kind'], 'gpu_tested': False, 'model_tested': False,
'qualification': 'Non-root GPU-hidden embedded identity and loader help only.'}
if p.get('build_features') is not None:
result['build_features'] = p['build_features']['features']
result['build_features_sha256'] = p['build_features_sha256']
success = True
return result
finally:
+71 -6
View File
@@ -6,17 +6,82 @@ build_dir="${STRATA_BUILD_DIR:-${repo_root}/artifacts/build-static-cuda}"
jobs="${BUILD_JOBS:-2}"
[[ "$(uname -s)" == Linux ]] || { echo 'Static CUDA engine builds require Linux.' >&2; exit 1; }
# CUDACXX/CUDAToolkit_ROOT select an existing toolkit; STRATA_GGML_DIR avoids fetching GGML.
extra=()
if [[ -n "${STRATA_GGML_DIR:-}" ]]; then
extra+=("-DSTRATA_GGML_DIR=${STRATA_GGML_DIR}")
if [[ ${STRATA_KAR_PLE+x} ]]; then
kar_ple="${STRATA_KAR_PLE}"
else
kar_ple=0
fi
cmake -S "${repo_root}/engine/strata" -B "${build_dir}" \
case "${kar_ple}" in
0) cmake_kar_ple=OFF ;;
1) cmake_kar_ple=ON ;;
*) echo 'STRATA_KAR_PLE must be exactly 0 or 1.' >&2; exit 2 ;;
esac
if [[ ${SOURCE_REVISION+x} ]]; then
source_revision="${SOURCE_REVISION}"
else
source_revision="$(git -C "${repo_root}" rev-parse HEAD)"
fi
if [[ ! "${source_revision}" =~ ^[0-9a-f]{40}$ ]]; then
echo 'SOURCE_REVISION must be an exact lowercase 40-character Git commit.' >&2
exit 2
fi
# CUDACXX/CUDAToolkit_ROOT select an existing toolkit; STRATA_GGML_DIR avoids fetching GGML.
cmake_args=(
-S "${repo_root}/engine/strata" -B "${build_dir}"
-DSTRATA_ENABLE_CUDA=ON -DSTRATA_ENABLE_HIP=OFF -DSTRATA_CUDA_STATIC=ON \
-DCMAKE_BUILD_TYPE=Release -DCMAKE_CUDA_ARCHITECTURES="${CUDA_ARCHITECTURES:-120}" \
-DSTRATA_NEXT_EXPERIMENTAL_KAR_PLE="${cmake_kar_ple}" \
-DSTRATA_NEXT_EXPERIMENTAL_KAR_EXPERTS=OFF \
-DSTRATA_NEXT_EXPERIMENTAL_PLE_TRACE=OFF \
-DSTRATA_NEXT_KAR_DIR="${repo_root}/gpu/kar" \
-DSTRATA_BUILD_TESTS=OFF -DSTRATA_NATIVE_EXPERTS=ON \
-DSTRATA_PORTABLE=ON "${extra[@]}"
-DSTRATA_PORTABLE=ON
)
if [[ -n "${STRATA_GGML_DIR:-}" ]]; then
cmake_args+=("-DSTRATA_GGML_DIR=${STRATA_GGML_DIR}")
fi
cmake "${cmake_args[@]}"
cmake --build "${build_dir}" --parallel "${jobs}" --target strata
python3 "${repo_root}/scripts/check-static-cuda-elf.py" "${build_dir}/strata"
# generate.cpp handles --help before any model or GPU initialization.
env -u LD_LIBRARY_PATH CUDA_VISIBLE_DEVICES= "${build_dir}/strata" --help
# This records compile capability only. The runtime still requires an explicit
# model/profile selection; PLE is experimental and defaults off at serving time.
python3 - "${build_dir}/BUILD-FEATURES.json" "${kar_ple}" "${CUDA_ARCHITECTURES:-120}" "${source_revision}" <<'PYFEATURES'
import json
import os
from pathlib import Path
import sys
import tempfile
destination, ple, architectures, revision = sys.argv[1:]
record = {
'schema_version': 1,
'source_revision': revision,
'cuda_architectures': architectures,
'features': {
'cuda': True,
'cuda_static_runtime': True,
'cxx_static_runtime': True,
'kar_ple': ple == '1',
'kar_experts': False,
'ple_trace': False,
},
}
path = Path(destination)
path.parent.mkdir(parents=True, exist_ok=True)
fd, temporary = tempfile.mkstemp(prefix='.BUILD-FEATURES-', dir=path.parent)
try:
with os.fdopen(fd, 'w') as output:
json.dump(record, output, sort_keys=True, indent=2)
output.write('\n')
output.flush()
os.fsync(output.fileno())
os.replace(temporary, path)
finally:
if os.path.exists(temporary):
os.unlink(temporary)
PYFEATURES
+13
View File
@@ -10,11 +10,24 @@ 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-static-cuda-profile.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"
python3 "${repo_root}/scripts/test-gitea-release.py"
python3 "${repo_root}/scripts/test-keyless-routing.py"
cargo fmt --manifest-path "${repo_root}/crates/model-format/Cargo.toml" --check
cargo clippy --manifest-path "${repo_root}/Cargo.toml" --locked -p leleka-model-format --all-targets -- -D warnings
cargo test --manifest-path "${repo_root}/Cargo.toml" --locked -p leleka-model-format
cargo test --manifest-path "${repo_root}/Cargo.toml" --locked -p leleka-backend-api
cargo fmt --manifest-path "${repo_root}/crates/quant-core/Cargo.toml" --check
cargo clippy --manifest-path "${repo_root}/Cargo.toml" --locked -p leleka-quant-core --all-targets -- -D warnings
cargo test --manifest-path "${repo_root}/Cargo.toml" --locked -p leleka-quant-core
cargo fmt --manifest-path "${repo_root}/crates/cuda-driver/Cargo.toml" --check
cargo clippy --manifest-path "${repo_root}/Cargo.toml" --locked -p leleka-cuda-driver --all-targets --all-features -- -D warnings
cargo test --manifest-path "${repo_root}/Cargo.toml" --locked -p leleka-cuda-driver
"${repo_root}/scripts/test-cuda-driver-bootstrap.sh"
cargo fmt --manifest-path "${repo_root}/control-plane/Cargo.toml" --check
cargo clippy --manifest-path "${repo_root}/control-plane/Cargo.toml" --locked --all-targets -- -D warnings
cargo test --manifest-path "${repo_root}/control-plane/Cargo.toml" --locked
+49
View File
@@ -0,0 +1,49 @@
"""CPU-only Docker HTTP probe that also works with a remote Docker daemon."""
import json
import subprocess
import uuid
# Official Python 3.11.17 slim OCI index, including Linux amd64 and arm64.
# Python belongs to this disposable test helper, never the serving image.
PROBE_IMAGE = 'python@sha256:0dd364ba7e10242f07755449e3a3d0e35f9efd987952737b90def6709ab0c5ce'
ISOLATION = ['--read-only', '--user', '65532:65532', '--cap-drop', 'ALL',
'--security-opt', 'no-new-privileges', '-e', 'CUDA_VISIBLE_DEVICES=',
'-e', 'NVIDIA_VISIBLE_DEVICES=void']
PROBE = '''import json,sys,urllib.error,urllib.request
route,payload=sys.argv[1:]
body=None if payload == 'null' else json.dumps(json.loads(payload)).encode()
request=urllib.request.Request('http://127.0.0.1:8081'+route,data=body,
headers={'Content-Type':'application/json'})
opener=urllib.request.build_opener(urllib.request.ProxyHandler({}))
try:
response=opener.open(request,timeout=5)
except urllib.error.HTTPError as error:
response=error
with response:
print(json.dumps({'status':response.status,'body':json.load(response)}))
'''
def docker(*args, check=True, timeout=30):
return subprocess.run(['docker', *map(str, args)], check=check,
capture_output=True, text=True, timeout=timeout)
def prepare_probe():
if docker('image', 'inspect', PROBE_IMAGE, check=False).returncode:
docker('pull', PROBE_IMAGE, timeout=120)
identity = docker('image', 'inspect', '--format', '{{.Id}}', PROBE_IMAGE).stdout.strip()
print(f'Isolated HTTP probe: {PROBE_IMAGE}, local image {identity}', flush=True)
def request(container, route, body=None):
name = 'strata-http-probe-' + uuid.uuid4().hex
try:
result = docker('run', '--rm', '--name', name, *ISOLATION,
'--network', f'container:{container}', '--entrypoint', 'python3',
PROBE_IMAGE, '-c', PROBE, route, json.dumps(body))
decoded = json.loads(result.stdout)
return decoded['status'], decoded['body']
finally:
docker('rm', '-f', name, check=False)
+61
View File
@@ -0,0 +1,61 @@
#!/usr/bin/env bash
set -euo pipefail
# Pin the installer independently of rust-toolchain.toml, which pins rustc/cargo.
readonly RUSTUP_VERSION="1.29.0"
readonly RUSTUP_TARGET="x86_64-unknown-linux-gnu"
readonly RUSTUP_INIT_SHA256="4acc9acc76d5079515b46346a485974457b5a79893cfb01112423c89aeb5aa10"
readonly RUSTUP_INIT_URL="https://static.rust-lang.org/rustup/archive/${RUSTUP_VERSION}/${RUSTUP_TARGET}/rustup-init"
# Give each Actions job an isolated installation so a host's rustup cannot
# silently override the version pinned here.
if [[ -n "${RUNNER_TEMP:-}" && -n "${GITHUB_RUN_ID:-}" ]]; then
rustup_home="${RUNNER_TEMP}/strata-rustup-${GITHUB_RUN_ID}-${GITHUB_JOB:-job}"
export CARGO_HOME="${rustup_home}/cargo"
export RUSTUP_HOME="${rustup_home}/rustup"
mkdir -p "$CARGO_HOME"
if [[ -n "${GITHUB_ENV:-}" ]]; then
printf 'CARGO_HOME=%s\nRUSTUP_HOME=%s\n' "$CARGO_HOME" "$RUSTUP_HOME" >> "$GITHUB_ENV"
fi
fi
tmp_dir="$(mktemp -d)"
trap 'rm -rf -- "$tmp_dir"' EXIT
python3 - "$RUSTUP_INIT_URL" "$tmp_dir/rustup-init" <<'PY'
import shutil
import sys
import urllib.request
request = urllib.request.Request(
sys.argv[1], headers={"User-Agent": "strata-next-pinned-rustup-bootstrap/1"}
)
with urllib.request.urlopen(request, timeout=120) as response:
with open(sys.argv[2], "wb") as output:
shutil.copyfileobj(response, output)
PY
printf '%s %s\n' "$RUSTUP_INIT_SHA256" "$tmp_dir/rustup-init" | sha256sum --check --status || {
echo "rustup-init ${RUSTUP_VERSION} checksum mismatch" >&2
exit 1
}
chmod 0755 "$tmp_dir/rustup-init"
"$tmp_dir/rustup-init" -y --no-modify-path \
--default-host "$RUSTUP_TARGET" --default-toolchain none --profile minimal
export PATH="${CARGO_HOME:-$HOME/.cargo}/bin:$PATH"
if [[ -n "${GITHUB_PATH:-}" ]]; then
printf '%s\n' "${CARGO_HOME:-$HOME/.cargo}/bin" >> "$GITHUB_PATH"
fi
rustup set auto-self-update disable
actual_version="$(rustup --version | awk 'NR == 1 { print $2 }')"
if [[ "$actual_version" != "$RUSTUP_VERSION" ]]; then
echo "expected rustup ${RUSTUP_VERSION}, got ${actual_version:-unknown}" >&2
exit 1
fi
if (( $# > 0 )); then
"$@"
fi
+383
View File
@@ -0,0 +1,383 @@
#!/usr/bin/env python3
"""Publish verified CLI or privately built CUDA previews through Gitea's API v1."""
import argparse
import hashlib
import http.client
import ipaddress
import json
import os
from pathlib import Path
import re
import ssl
import stat
import sys
from urllib.parse import urlencode, urljoin, 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'}
STATIC_IMAGE_ASSETS = {'runtime-image.tar', 'IMAGE-PROVENANCE.json'}
STATIC_ASSETS = PACKAGE_ASSETS | STATIC_IMAGE_ASSETS | {'SHA256SUMS', 'IMAGE-SHA256SUMS'}
CLI_ASSETS = {PACKAGE_BINARY, 'BUILD-PROVENANCE.txt', 'ELF-AUDIT.txt', 'SHA256SUMS'}
CHUNK_SIZE = 1024 * 1024
def file_sha256(path):
fd = os.open(path, os.O_RDONLY | os.O_NONBLOCK | 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 canonical_sha(record):
return hashlib.sha256((json.dumps(record, sort_keys=True, indent=2) + '\n').encode()).hexdigest()
def valid_digest(value, prefix=''):
return isinstance(value, str) and re.fullmatch(re.escape(prefix) + r'[0-9a-f]{64}', value) is not None
def verify_artifacts(directory, target, profile='cuda'):
if profile not in {'cli', 'cuda', 'static-cuda'}:
raise ValueError('unsupported artifact profile')
expected = {'cli': CLI_ASSETS, 'cuda': ASSETS, 'static-cuda': STATIC_ASSETS}[profile]
if not directory.is_dir():
raise ValueError('artifact directory does not exist')
paths = list(directory.iterdir())
if {path.name for path in paths} != expected:
raise ValueError(f'artifact directory must contain exactly the {profile.upper()} preview files')
for path in paths:
file_sha256(path)
verify_manifest(directory, 'SHA256SUMS', expected - {'SHA256SUMS'} if profile == 'cli' else PACKAGE_ASSETS)
if profile == 'cli':
provenance = (directory / 'BUILD-PROVENANCE.txt').read_text(encoding='utf-8')
commits = re.findall(r'^Commit: (.*)$', provenance, re.MULTILINE)
if commits != [target] or not re.search(r'^Workflow: https?://\S+$', provenance, re.MULTILINE):
raise ValueError('CLI build provenance is not bound to this exact commit and workflow')
audit = (directory / 'ELF-AUDIT.txt').read_text(encoding='utf-8')
if ('ELF Header:' not in audit or not re.search(r'Class:\s+ELF64', audit) or
not re.search(r'Machine:\s+Advanced Micro Devices X86-64', audit) or
'INTERP' in audit or 'NEEDED' in audit):
raise ValueError('CLI ELF audit does not describe a static x86_64 executable')
else:
verify_manifest(directory, 'IMAGE-SHA256SUMS', STATIC_IMAGE_ASSETS if profile == 'static-cuda' else IMAGE_ASSETS)
package = read_json(directory / 'PROVENANCE.json')
engine = package.get('engine', {})
features = package.get('build_features', {})
feature_sha = package.get('build_features_sha256')
loader = package.get('loader_probe', {})
audit = package.get('engine_elf_audit', {})
if (type(package.get('schema_version')) is not int or package.get('schema_version') != 1 or
package.get('kind') != 'static-cuda-preview' or
package.get('target') != 'x86_64-unknown-linux-musl' or package.get('source_revision') != target or
package.get('gpu_tested') is not False or package.get('model_tested') is not False or
package.get('clean_node_tested') is not False or not isinstance(engine, dict) or
engine.get('embedded') is not True or engine.get('declared_source_revision') != target or
engine.get('target_os') != 'linux' or engine.get('target_arch') != 'x86_64' or
type(engine.get('bytes')) is not int or not 0 < engine['bytes'] <= 1024**3 or
not valid_digest(engine.get('sha256')) or not isinstance(loader, dict) or
loader.get('environment') != 'pinned-runtime-container' or loader.get('gpu_tested') is not False or
loader.get('user') != '65532:65532' or not valid_digest(loader.get('image_id'), 'sha256:')):
raise ValueError('combined package provenance is not a CUDA-only preview for this commit')
if (not isinstance(audit, dict) or audit.get('toolkit_shared_libraries') is not False or
audit.get('host_glibc_required') is not True or
not isinstance(audit.get('minimum_glibc'), str) or
not re.fullmatch(r'[0-9]+\.[0-9]+(?:\.[0-9]+)?', audit['minimum_glibc']) or
not isinstance(loader.get('glibc'), str) or
not re.fullmatch(r'[0-9]+\.[0-9]+(?:\.[0-9]+)?', loader['glibc'])):
raise ValueError('CUDA ELF audit and loader glibc receipts are required')
minimum = tuple(map(int, audit['minimum_glibc'].split('.')))
actual = tuple(map(int, loader['glibc'].split('.')))
if actual + (0,) * (3 - len(actual)) < minimum + (0,) * (3 - len(minimum)):
raise ValueError('loader glibc is below the engine ELF audit requirement')
if (not isinstance(features, dict) or set(features) != {
'schema_version', 'source_revision', 'cuda_architectures', 'features'} or
type(features.get('schema_version')) is not int or features.get('schema_version') != 1 or
features.get('source_revision') != target or
not isinstance(features.get('cuda_architectures'), str) or
not re.fullmatch(r'[0-9]+(?:-(?:real|virtual))?(?:;[0-9]+(?:-(?:real|virtual))?)*', features['cuda_architectures']) or
not valid_digest(feature_sha) or canonical_sha(features) != feature_sha):
raise ValueError('CUDA build feature receipt is not bound to this source and digest')
values = features['features']
if (not isinstance(values, dict) or set(values) != {
'cuda', 'cuda_static_runtime', 'cxx_static_runtime', 'kar_ple', 'kar_experts', 'ple_trace'} or
any(type(value) is not bool for value in values.values()) or
any(values[key] is not True for key in ('cuda', 'cuda_static_runtime', 'cxx_static_runtime')) or
values['kar_experts'] is not False or values['ple_trace'] is not False):
raise ValueError('unsupported CUDA compile feature selection')
image = read_json(directory / 'IMAGE-PROVENANCE.json')
if (type(image.get('schema_version')) is not int or image.get('schema_version') != 1 or
image.get('kind') != 'static-cuda-preview' or
image.get('source_revision') != target or not valid_digest(image.get('image'), 'sha256:') or
not isinstance(image.get('base'), str) or
not re.fullmatch(r'[a-z0-9][a-z0-9./:_-]*@sha256:[0-9a-f]{64}', image['base']) or
image.get('base') != loader.get('base') or image.get('base_glibc') != loader.get('glibc') or
image.get('gpu_tested') is not False or image.get('model_tested') is not False or
image.get('build_features') != values or image.get('build_features_sha256') != feature_sha or
image.get('package_receipt_sha256') != file_sha256(directory / 'SHA256SUMS')):
raise ValueError('runtime image provenance is not qualified for this package and commit')
if profile == 'cuda':
toolchain = read_json(directory / 'CUDA-TOOLCHAIN.json')
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 toolchain.get('build_features') != values or
toolchain.get('build_features_sha256') != feature_sha or
toolchain.get('cuda_architectures') != features['cuda_architectures'] or
not valid_digest(toolchain.get('builder_image_id'), 'sha256:') or
not isinstance(builder, dict) or builder.get('source_commit') != target or
builder.get('image_id') != toolchain.get('builder_image_id') or
builder.get('engine_sha256') != engine['sha256'] or
builder.get('build_features_sha256') != feature_sha or
builder.get('runtime_image_id') != image['image'] or
builder.get('runtime_archive_sha256') != file_sha256(directory / 'runtime-image.tar')):
raise ValueError('CUDA toolchain provenance is not bound to this commit, engine and runtime image')
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')
if parts.scheme == 'http':
try:
local = ipaddress.ip_address(parts.hostname).is_loopback
except ValueError:
local = parts.hostname == 'localhost'
if not local:
raise ValueError('non-loopback Gitea API must use verified HTTPS')
if parts.hostname in {'github.com', 'api.github.com'}:
raise ValueError('API URL must identify Gitea, not GitHub')
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 len(data) > 1024 * 1024:
raise ValueError('Gitea response exceeds size limit')
if response.status != expected_status:
raise RuntimeError(f'Gitea API returned HTTP {response.status}')
result = json.loads(data)
if not isinstance(result, dict):
raise ValueError('Gitea response must be a JSON object')
return result
finally:
conn.close()
def upload_asset(parts, prefix, path, token, asset, expected, repository, tag):
name = asset.name
route = prefix + path + '/assets?' + urlencode({'name': name})
fd = os.open(asset, os.O_RDONLY | os.O_NONBLOCK | 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 len(data) > 1024 * 1024:
raise ValueError('Gitea response exceeds size limit')
if response.status != 201:
raise RuntimeError(f'Gitea asset upload returned HTTP {response.status}')
metadata = json.loads(data)
if not isinstance(metadata, dict):
raise ValueError('Gitea asset response must be a JSON object')
if metadata.get('name') != name or metadata.get('size') != size:
raise ValueError(f'Gitea returned mismatched asset metadata: {name}')
verify_uploaded_asset(parts, token, metadata, expected, repository, tag)
return {'name': name, 'size': size}
finally:
if fd >= 0:
os.close(fd)
if conn is not None:
conn.close()
def validate_download_url(parts, url, allowed_paths):
if not isinstance(url, str):
raise ValueError('Gitea asset lacks its download URL')
asset_url = urlsplit(url)
if (asset_url.scheme != parts.scheme or asset_url.hostname != parts.hostname or
(asset_url.port or (443 if asset_url.scheme == 'https' else 80)) !=
(parts.port or (443 if parts.scheme == 'https' else 80)) or
asset_url.username or asset_url.password or asset_url.query or asset_url.fragment or
asset_url.path not in allowed_paths):
raise ValueError('Gitea asset URL must match its same-origin release or attachment route')
return asset_url
def verify_uploaded_asset(parts, token, metadata, expected, repository, tag):
# Gitea POST may return the UUID attachment route; later reads may return
# the exact release route. Both are bound to the same uploaded asset.
# Validate every hop before sending a scoped token; never follow foreign URLs.
base_path = parts.path.rstrip('/').removesuffix('/api/v1')
repo_path = base_path + '/' + repository
release_path = f"{repo_path}/releases/download/{tag}/{metadata['name']}"
url = metadata.get('browser_download_url')
attachment = metadata.get('uuid')
if not isinstance(attachment, str) or not re.fullmatch(
r'[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}', attachment):
raise ValueError('Gitea asset lacks a valid attachment UUID')
attachment_paths = {f'{base_path}/attachments/{attachment}',
f'{repo_path}/attachments/{attachment}',
f'{repo_path}/releases/attachments/{attachment}'}
initial_paths = {release_path} | attachment_paths
for hop in range(3):
asset_url = validate_download_url(parts, url, initial_paths if hop == 0 else attachment_paths)
conn = connection(parts)
try:
conn.request('GET', asset_url.path, headers={'Authorization': f'token {token}'})
response = conn.getresponse()
if response.status in {301, 302, 303, 307, 308}:
if hop == 2:
raise ValueError('Gitea asset verification exceeds two redirects')
location = response.getheader('Location')
if not location:
raise ValueError('Gitea asset redirect lacks its location')
candidate = urljoin(url, location)
validate_download_url(parts, candidate, attachment_paths)
url = candidate
continue
if response.status != 200:
raise RuntimeError(f'Gitea asset verification returned HTTP {response.status}')
digest = hashlib.sha256()
total = 0
while block := response.read(min(CHUNK_SIZE, expected['size'] - total + 1)):
total += len(block)
if total > expected['size']:
raise ValueError('Gitea uploaded asset exceeds its verified size')
digest.update(block)
if total != expected['size'] or digest.hexdigest() != expected['sha256']:
raise ValueError('Gitea uploaded asset checksum mismatch')
return
finally:
conn.close()
def publish(api_url, repository, token, tag, target, title, notes, directory, profile='cuda'):
if not token:
raise ValueError('GITEA_TOKEN is required')
if not isinstance(token, str) or len(token) > 512 or any(not 33 <= ord(char) <= 126 for char in token):
raise ValueError('GITEA_TOKEN must be bounded printable ASCII without whitespace')
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')
tag_pattern = {'cuda': r'cuda-preview-[0-9]+-[0-9]+',
'static-cuda': r'static-cuda-preview-[0-9]+-[0-9]+',
'cli': r'(?:cli-preview-[0-9]+-[0-9]+|v[0-9][A-Za-z0-9_.-]*)'}.get(profile, '')
if not re.fullmatch(tag_pattern, tag):
raise ValueError('tag does not match the explicit preview profile')
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, profile)
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 or release.get('draft') is not True or
release.get('prerelease') is not True or release.get('tag_name') != tag or
release.get('target_commitish') != target):
raise ValueError('Gitea did not confirm the exact draft prerelease identity')
asset_route = f'/repos/{owner}/{repo}/releases/{release_id}'
uploaded = []
for name in sorted(hashes):
uploaded.append(upload_asset(parts, prefix, asset_route, token, directory / name, hashes[name], repository, tag))
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('--profile', choices=['cli', 'cuda', 'static-cuda'], required=True)
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, args.profile)
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()
+9 -26
View File
@@ -2,32 +2,18 @@
"""Exercise the actual CLI-only scratch image; never starts an inference worker."""
import json
from pathlib import Path
import subprocess
import sys
import time
import urllib.error
import urllib.request
import uuid
def docker(*args, check=True):
return subprocess.run(['docker', *args], check=check, capture_output=True,
text=True, timeout=30)
import subprocess
from docker_smoke_http import ISOLATION, docker, prepare_probe, request
def main(image):
name = 'strata-cli-smoke-' + uuid.uuid4().hex
common = ['--name', name, '--read-only', '--user', '65532:65532',
'--cap-drop', 'ALL', '--security-opt', 'no-new-privileges']
common = ['--name', name, *ISOLATION]
root = Path(__file__).resolve().parents[1]
opener = urllib.request.build_opener(urllib.request.ProxyHandler({}))
def get(port, route):
try:
with opener.open(f'http://127.0.0.1:{port}{route}', timeout=2) as response:
return response.status, json.load(response)
except urllib.error.HTTPError as error:
return error.code, json.load(error)
prepare_probe()
try:
version = docker('run', '--rm', *common, '--network', 'none', image, '--version').stdout
@@ -38,21 +24,18 @@ 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])
docker('run', '-d', *common, '--network', 'none',
'-e', 'STRATA_BIND=127.0.0.1:8081', image, 'serve')
deadline = time.monotonic() + 15
while True:
try:
assert get(port, '/health') == (200, {'status': 'ok'})
assert request(name, '/health') == (200, {'status': 'ok'})
break
except (OSError, AssertionError):
except (OSError, AssertionError, subprocess.CalledProcessError):
if time.monotonic() >= deadline:
raise
time.sleep(0.1)
status, ready = get(port, '/ready')
status, ready = request(name, '/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)
+25 -14
View File
@@ -7,12 +7,8 @@ import subprocess
import sys
import tempfile
import time
import urllib.request
import uuid
def docker(*args, check=True):
return subprocess.run(['docker', *map(str, args)], check=check, capture_output=True, text=True, timeout=30)
from docker_smoke_http import ISOLATION, PROBE_IMAGE, docker, prepare_probe, request as probe_request
def main(receipt):
@@ -24,32 +20,41 @@ 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({}))
volume = name + '-fixture'
staging = name + '-stage'
prepare_probe()
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',
(root/'config.json').write_text(json.dumps({'bind': '127.0.0.1:8081', 'model': 'embedded-fixture',
'engine_probe': True, 'engine': {'executable': '@embedded', 'args': ['/tmp/worker.pid'],
'tokenizer_dir': '/fixture', 'startup_timeout_s': 5, 'max_restarts': 1}}))
for path in root.iterdir(): path.chmod(0o644)
try:
docker('volume', 'create', volume)
docker('run', '-d', '--name', staging, *ISOLATION, '--network', 'none',
'--mount', f'type=volume,src={volume},dst=/fixture',
'--entrypoint', 'python3', PROBE_IMAGE, '-c', 'import time; time.sleep(120)')
# Stream files through the Docker API; runner paths need not exist
# on the daemon host. The serving container gets a read-only volume.
docker('cp', str(root) + '/.', staging + ':/fixture')
docker('rm', '-f', staging)
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', '--network', 'none',
'--mount', f'type=volume,src={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)
status, result = probe_request(name, route, body)
assert status == 200, (status, result)
return result
def ready():
deadline = time.monotonic()+15
while time.monotonic()<deadline:
try:
if request('/status')['ready']: return
except OSError: pass
except (OSError, subprocess.CalledProcessError): pass
time.sleep(.1)
raise AssertionError('container worker did not become ready')
def generate():
@@ -70,8 +75,14 @@ def main(receipt):
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.')
except Exception:
logs = docker('logs', name, check=False)
print('Owned CPU fixture container logs:', logs.stdout, logs.stderr, file=sys.stderr)
raise
finally:
docker('rm','-f',name,check=False)
docker('rm','-f',staging,check=False)
docker('volume','rm',volume,check=False)
if __name__=='__main__': main(sys.argv[1])
+8 -1
View File
@@ -50,7 +50,14 @@ def main():
generated = run(str(binary), 'service-unit', '--config', str(config),
'--working-dir', str(odd), '--env-file', str(env_file)).stdout
unit.write_text(generated)
verify = run('systemd-analyze', '--user', 'verify', str(unit), check=False)
# Offline verification still initializes a user manager context. CI's
# runner container has no login session or /run/user directory; provide
# only this invocation with a private runtime directory, not a live bus.
verify_runtime = root / 'verify-runtime'
verify_runtime.mkdir(mode=0o700)
verify_env = dict(os.environ, XDG_RUNTIME_DIR=str(verify_runtime))
verify = run('systemd-analyze', '--user', 'verify', str(unit),
check=False, env=verify_env)
assert verify.returncode == 0, verify.stderr
# The renderer must fail closed, before printing any installable unit.
bad = run(str(binary), 'service-unit', '--config', 'relative.json',
+269
View File
@@ -0,0 +1,269 @@
#!/usr/bin/env python3
"""Run unchanged native lifecycle gates with a disposable real systemd manager.
CPU-only offline fixture. Setup alone gets mount/UID capabilities; journald,
D-Bus, manager, Rust CLI and synthetic workers have empty capability sets.
The private writable cgroup mount enables real manager process tracking.
Setup uses fixture-only apparmor=unconfined for the private cgroup mount;
default seccomp stays enabled. No host paths/devices/namespaces are shared.
Existing tests exercise stop/rollback; this is not a separate forced-descendant
KillMode test, installed-driver inference, or model quality evidence.
"""
import argparse
import glob
import hashlib
import json
import os
from pathlib import Path
import shutil
import signal
import subprocess
import sys
import tempfile
import time
import uuid
UID = 10001
CAPS = ('SYS_ADMIN', 'CHOWN', 'SETUID', 'SETGID', 'SETPCAP')
FILES = ('smoke-service-unit.py', 'smoke-native-switch.py', 'smoke-worker-cancel.py')
def run(*args, **kwargs):
return subprocess.run(args, check=True, **kwargs)
def no_gpu():
assert not glob.glob('/dev/nvidia*'), 'raw NVIDIA devices are forbidden'
assert os.environ.get('NVIDIA_VISIBLE_DEVICES') == 'void'
assert os.environ.get('CUDA_VISIBLE_DEVICES') == ''
def zero_caps(pid='self'):
status = Path(f'/proc/{pid}/status').read_text()
found = [line.split(':', 1)[1].strip() for line in status.splitlines()
if line.startswith(('CapInh:', 'CapPrm:', 'CapEff:', 'CapBnd:', 'CapAmb:'))]
assert found == ['0000000000000000'] * 5, (pid, found)
assert any(line.startswith('NoNewPrivs:') and line.split(':', 1)[1].strip() == '1'
for line in status.splitlines()), (pid, 'NoNewPrivs missing')
def drop_command(*args):
return ['setpriv', f'--reuid={UID}', f'--regid={UID}', '--clear-groups',
'--bounding-set=-all', '--inh-caps=-all', '--ambient-caps=-all', *args]
def root_setup():
# Direct host invocation must fail before any mount, chown, or unit operation.
assert Path('/.dockerenv').is_file() and os.getpid() == 1 and os.getuid() == 0
nonce = os.environ['LELEKA_MANAGER_FIXTURE_NONCE']
assert len(nonce) == 32 and all(c in '0123456789abcdef' for c in nonce)
no_gpu()
run('dpkg-query', '-W', 'systemd', 'dbus', 'dbus-user-session', 'python3', 'util-linux',
'ca-certificates')
assert Path('/proc/self/cgroup').read_text().strip() == '0::/'
target = Path('/sys/fs/cgroup')
assert target.is_dir() and not target.is_symlink()
mounts = Path('/proc/self/mountinfo').read_text().splitlines()
assert any(line.split()[4] == str(target) and ' - cgroup2 ' in line for line in mounts)
owned = Path('/run') / ('leleka-cgroup-' + nonce)
assert not owned.exists()
owned.mkdir(mode=0o700)
run('mount', '-t', 'cgroup2', 'none', str(owned))
run('mount', '--move', str(owned), str(target))
assert set(Path('/sys/fs/cgroup/cgroup.procs').read_text().split()) <= {str(os.getpid())}
for path in (target, target/'cgroup.procs', target/'cgroup.subtree_control'):
os.chown(path, UID, UID)
# Only known staged regular files are normalized. The CLI remains root-owned.
for name in (*FILES, 'smoke-systemd-manager.py', 'strata-next'):
path = Path('/work') / name
assert path.is_file() and not path.is_symlink()
os.chown(path, 0, 0)
path.chmod(0o755 if name == 'strata-next' else 0o644)
for path in (Path('/run/systemd/journal'), Path('/run/log/journal')):
path.mkdir(parents=True, exist_ok=True)
os.chown(path, UID, UID)
config = Path('/etc/systemd/journald.conf.d')
config.mkdir(exist_ok=True)
(config/'fixture.conf').write_text('[Journal]\nStorage=volatile\nReadKMsg=no\n'
'ForwardToKMsg=no\nForwardToConsole=no\nForwardToWall=no\n')
journal = subprocess.Popen(drop_command('/usr/lib/systemd/systemd-journald'))
env = dict(os.environ, HOME='/home/fixture', USER='fixture', LOGNAME='fixture',
XDG_CONFIG_HOME='/home/fixture/.config',
DBUS_SESSION_BUS_ADDRESS='unix:path=/run/user/10001/fixture-bus',
PYTHONDONTWRITEBYTECODE='1', LELEKA_JOURNAL_PID=str(journal.pid))
# exec retains journald's parent for bounded waitpid/reaping by the test user.
os.execvpe('setpriv', drop_command('python3', '/work/smoke-systemd-manager.py',
'--inside-user'), env)
def finish_process(process):
if process is None:
return
if process.poll() is None:
process.terminate()
try:
process.wait(timeout=5)
except subprocess.TimeoutExpired:
process.kill()
process.wait(timeout=5)
def finish_journal(pid):
try:
os.kill(pid, signal.SIGTERM)
except ProcessLookupError:
pass
deadline = time.monotonic() + 5
while time.monotonic() < deadline:
if os.waitpid(pid, os.WNOHANG)[0]:
return
time.sleep(.05)
os.kill(pid, signal.SIGKILL)
deadline = time.monotonic() + 5
while time.monotonic() < deadline:
if os.waitpid(pid, os.WNOHANG)[0]:
return
time.sleep(.05)
raise TimeoutError('journald did not reap after SIGKILL; outer container removal required')
def user_tests():
assert Path('/.dockerenv').is_file() and os.getpid() == 1
no_gpu()
assert os.getuid() == UID
zero_caps()
journal_pid = int(os.environ['LELEKA_JOURNAL_PID'])
bus = manager = None
failed = False
cleanup_errors = []
try:
bus = subprocess.Popen(['dbus-daemon', '--session', '--nofork',
'--address=' + os.environ['DBUS_SESSION_BUS_ADDRESS']])
manager = subprocess.Popen(['/usr/lib/systemd/systemd', '--user', '--unit=basic.target',
'--log-target=console', '--log-level=warning'])
deadline = time.monotonic() + 25
while True:
assert manager.poll() is None and bus.poll() is None, 'manager or bus exited'
result = subprocess.run(['systemctl', '--user', 'show', '--property=Version'],
text=True, capture_output=True, timeout=3)
if result.returncode == 0 and Path('/run/systemd/journal/stdout').exists():
break
assert time.monotonic() < deadline, result.stderr
time.sleep(.2)
zero_caps(manager.pid)
zero_caps(bus.pid)
zero_caps(journal_pid)
assert str(manager.pid) in Path('/sys/fs/cgroup/init.scope/cgroup.procs').read_text().split()
print(result.stdout.strip(), flush=True)
print('Private real manager, bus, journal and cgroup ready; all capabilities zero', flush=True)
run('python3', '/work/smoke-service-unit.py', '/work/strata-next', '--lifecycle', timeout=600)
run('python3', '/work/smoke-native-switch.py', '/work/strata-next', timeout=300)
except BaseException:
failed = True
raise
finally:
# Every owned process is cleaned even if another cleanup step fails.
for cleanup in (
lambda: subprocess.run(['systemctl', '--user', 'exit'], check=False, timeout=5),
lambda: finish_process(manager), lambda: finish_process(bus),
lambda: finish_journal(journal_pid),
):
try:
cleanup()
except Exception as error:
cleanup_errors.append(str(error))
if cleanup_errors:
print('Fixture cleanup errors: ' + '; '.join(cleanup_errors), file=sys.stderr)
if not failed:
raise RuntimeError('owned manager fixture cleanup failed')
def host(binary):
assert not glob.glob('/dev/nvidia*'), 'manager fixture is restricted to a CPU host'
root = Path(__file__).resolve().parents[1]
binary = binary.resolve(strict=True)
nonce = uuid.uuid4().hex
name = 'leleka-systemd-smoke-' + nonce
image = name + ':fixture'
with tempfile.TemporaryDirectory(prefix=name + '-') as directory:
stage = Path(directory)
dockerfile = root/'deploy/Dockerfile.systemd-smoke'
context = stage/'image-context'
context.mkdir()
shutil.copy2(dockerfile, context/'Dockerfile')
for filename in (*FILES, 'smoke-systemd-manager.py'):
shutil.copy2(root/'scripts'/filename, stage/filename)
shutil.copy2(binary, stage/'strata-next')
def digest(path):
checksum = hashlib.sha256()
with path.open('rb') as source:
for block in iter(lambda: source.read(1024 * 1024), b''):
checksum.update(block)
return checksum.hexdigest()
hashes = {path.name: digest(path) for path in stage.iterdir() if path.is_file()}
hashes['Dockerfile.systemd-smoke'] = digest(dockerfile)
print(json.dumps({'fixture_sha256': hashes}, sort_keys=True), flush=True)
try:
run('docker', 'build', '--platform', 'linux/amd64', '-t', image, str(context), timeout=600)
run('docker', 'create', '--name', name, '--platform', 'linux/amd64', '--tty',
'--network', 'none', '--cgroupns', 'private', '--user', '0', '--cap-drop', 'ALL',
*(arg for cap in CAPS for arg in ('--cap-add', cap)),
'--security-opt', 'no-new-privileges',
'--security-opt', 'apparmor=unconfined',
'-e', 'NVIDIA_VISIBLE_DEVICES=void', '-e', 'CUDA_VISIBLE_DEVICES=',
'-e', 'LELEKA_MANAGER_FIXTURE_NONCE=' + nonce,
image, 'python3', '/work/smoke-systemd-manager.py', '--inside-root', timeout=30)
info = json.loads(subprocess.check_output(['docker', 'inspect', name], text=True))[0]
config = info['HostConfig']
assert config['CgroupnsMode'] == 'private' and config['NetworkMode'] == 'none'
assert not config['Privileged'] and config['PidMode'] == ''
assert not config['Binds'] and not info['Mounts'] and not config['Devices']
assert not config['DeviceRequests'] and config['IpcMode'] == 'private'
assert config['CapDrop'] == ['ALL']
assert {cap.removeprefix('CAP_') for cap in config['CapAdd']} == set(CAPS)
assert set(config['SecurityOpt']) == {'no-new-privileges', 'apparmor=unconfined'}
print(json.dumps({'image_id': info['Image'], 'source': 'isolated CPU fixture',
'setup_security_options': config['SecurityOpt'],
'setup_capabilities': config['CapAdd'],
'user_capabilities': 'zero', 'seccomp': 'Docker default'}), flush=True)
# docker cp works with a remote daemon; runner paths are not bind-mounted.
for filename in (*FILES, 'smoke-systemd-manager.py', 'strata-next'):
run('docker', 'cp', str(stage/filename), name + ':/work/' + filename, timeout=60)
run('docker', 'start', '--attach', name, timeout=1000)
state = json.loads(subprocess.check_output(['docker', 'inspect', name], text=True))[0]['State']
assert state['ExitCode'] == 0, state
finally:
# Container removal is the final namespace-wide cleanup safety net.
original_failure = sys.exc_info()[0] is not None
errors = []
for kind, command in (('container', ['docker', 'rm', '--force', name]),
('image', ['docker', 'image', 'rm', image])):
try:
result = subprocess.run(command, text=True, capture_output=True, timeout=30)
if result.returncode and 'No such ' not in result.stderr:
errors.append(kind + ': ' + result.stderr)
except Exception as error:
errors.append(kind + ': ' + str(error))
if errors:
print('Outer fixture cleanup errors: ' + '; '.join(errors), file=sys.stderr)
if not original_failure:
raise RuntimeError('outer fixture cleanup failed')
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('binary', nargs='?', type=Path)
parser.add_argument('--inside-root', action='store_true')
parser.add_argument('--inside-user', action='store_true')
args = parser.parse_args()
if args.inside_root:
root_setup()
elif args.inside_user:
user_tests()
else:
assert args.binary is not None
host(args.binary)
if __name__ == '__main__':
main()
+29
View File
@@ -20,6 +20,16 @@ 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_safe_hardlink_and_archive_permissions(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/lib/a');item.size=1;item.mode=0o777;t.addfile(item,io.BytesIO(b'a'))
item=tarfile.TarInfo('component/lib/b');item.type=tarfile.LNKTYPE;item.linkname='component/lib/a';t.addfile(item)
out=m.extract(archive,root/'out','component')
self.assertEqual((out/'lib/b').read_bytes(),b'a')
self.assertFalse((out/'lib/a').stat().st_mode & 0o7000)
self.assertFalse((out/'lib/a').stat().st_mode & 0o022)
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:
@@ -30,6 +40,25 @@ class Tests(unittest.TestCase):
t.addfile(item)
with self.assertRaises((ValueError,tarfile.TarError)):m.extract(archive,root/'out','component')
self.assertFalse((root/'escape').exists())
def test_reject_link_ancestor_and_hardlink_escape(self):
for entries in [
[('component/link',tarfile.SYMTYPE,'lib'),('component/link/escape',tarfile.REGTYPE,'')],
[('component/file',tarfile.LNKTYPE,'../../escape')],
]:
with self.subTest(entries=entries),tempfile.TemporaryDirectory() as tmp:
root=Path(tmp);archive=root/'test.tar.xz'
with tarfile.open(archive,'w:xz') as t:
for name,kind,link in entries:
item=tarfile.TarInfo(name);item.type=kind
if kind==tarfile.REGTYPE:item.size=1;t.addfile(item,io.BytesIO(b'x'))
else:item.linkname=link;t.addfile(item)
with self.assertRaises(ValueError):m.extract(archive,root/'out','component')
def test_reject_privileged_modes(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/file');item.size=1;item.mode=0o4755;t.addfile(item,io.BytesIO(b'x'))
with self.assertRaises(ValueError):m.extract(archive,root/'out','component')
def test_component_merge_rejects_conflict(self):
with tempfile.TemporaryDirectory() as tmp:
root=Path(tmp);a=root/'a';b=root/'b';a.mkdir();b.mkdir()
+169
View File
@@ -0,0 +1,169 @@
#!/usr/bin/env bash
# Usage: scripts/test-cuda-driver-bootstrap.sh [--inside]
# Default: isolated Linux CPU Docker mock ELF gate; --inside is container-only.
# Synthetic crate-only workspace; no installed CUDA driver or model data accessed.
set -euo pipefail
repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
image='rust@sha256:114c7a4425406451c2866b6aafe69fe29b1b298832db1277d411ac73c82d04d6'
if [[ "${1:-}" == --inside ]]; then
[[ $# == 1 && -f /.dockerenv && "$(uname -s)" == Linux ]]
[[ "$(id -u)" == 65532 ]]
[[ "$(awk '/^Cap(Eff|Prm|Bnd):/{print $2}' /proc/self/status)" == $'0000000000000000\n0000000000000000\n0000000000000000' ]]
for device in /dev/nvidia* /dev/dri/*; do
[[ ! -e "$device" ]] || { echo 'raw GPU device present; refusing mock gate' >&2; exit 1; }
done
[[ ! -e "${repo_root}/engine" && ! -e "${repo_root}/control-plane" ]]
command -v nvcc >/dev/null && { echo 'unexpected CUDA Toolkit' >&2; exit 1; }
if ldconfig -p 2>/dev/null | grep -q 'libcuda\.so'; then
echo 'installed CUDA driver present; refusing mock gate' >&2; exit 1
fi
work="$(mktemp -d /tmp/leleka-cuda-mock.XXXXXX)"
trap 'result=$?; rm -rf "$work" || { if [[ "$result" == 0 ]]; then result=1; fi; }; exit "$result"' EXIT
mkdir -p "$work/complete" "$work/missing"
cc -std=c11 -Wall -Wextra -Werror -Wno-misleading-indentation -shared -fPIC \
"${repo_root}/crates/cuda-driver/tests/mock_cuda.c" -o "$work/complete/libcuda.so.1"
cc -std=c11 -Wall -Wextra -Werror -Wno-misleading-indentation -shared -fPIC -DMOCK_MISSING_DTOH \
"${repo_root}/crates/cuda-driver/tests/mock_cuda.c" -o "$work/missing/libcuda.so.1"
for symbol in cuInit cuDriverGetVersion cuDeviceGet cuCtxCreate_v2 cuCtxDestroy_v2 \
cuCtxPushCurrent_v2 cuCtxPopCurrent_v2 cuCtxSynchronize cuMemAlloc_v2 cuMemFree_v2 cuMemcpyHtoD_v2 cuModuleLoadData cuModuleGetFunction cuModuleUnload cuLaunchKernel; do
mkdir "$work/missing_$symbol"
cc -std=c11 -Wall -Wextra -Werror -Wno-misleading-indentation -shared -fPIC \
"-D${symbol}=mock_replaced_${symbol}" "${repo_root}/crates/cuda-driver/tests/mock_cuda.c" \
-o "$work/missing_$symbol/libcuda.so.1"
done
readelf -h "$work/complete/libcuda.so.1" | grep 'Class:.*ELF64'
sha256sum "$work/complete/libcuda.so.1" "$work/missing/libcuda.so.1"
sha256sum "${repo_root}/crates/cuda-driver/Cargo.toml" \
"${repo_root}/crates/cuda-driver/src/lib.rs" "${repo_root}/crates/cuda-driver/src/ffi.rs" \
"${repo_root}/crates/cuda-driver/src/vector_add.ptx" \
"${repo_root}/crates/cuda-driver/tests/mock_cuda.c" "${repo_root}/crates/cuda-driver/tests/mock_driver.rs"
rustup component list --installed
rustc --version
cc --version | head -1
export CARGO_TARGET_DIR="$work/target"
cd "$repo_root"
cargo fmt --manifest-path "${repo_root}/Cargo.toml" --all -- --check
cargo test --offline --locked --manifest-path "${repo_root}/Cargo.toml" -p leleka-cuda-driver --lib
cargo clippy --offline --locked --manifest-path "${repo_root}/Cargo.toml" -p leleka-cuda-driver --all-targets --all-features -- -D warnings
LELEKA_CUDA_MOCK_HARNESS=1 LELEKA_CUDA_MOCK_ROOT="$work" \
cargo test --offline --locked --manifest-path "${repo_root}/Cargo.toml" -p leleka-cuda-driver \
--features cuda-driver --test mock_driver -- --exact isolated_cpu_elf_matrix --ignored --test-threads=1 --nocapture
rlib="$(find "$work/target/debug/deps" -maxdepth 1 -name 'libleleka_cuda_driver-*.rlib' -print -quit)"
[[ -n "$rlib" ]]
# Independent negative compile gates: lifetimes/auto-traits cannot escape FFI ownership.
for typename in Driver 'Device<'"'static"'>' 'Context<'"'static"'>' 'DeviceBuffer<'"'static"'>';
do
for trait in Send Sync; do
printf 'use leleka_cuda_driver::*;fn require<T:%s>(){}fn main(){require::<%s>();}\n' "$trait" "$typename" > "$work/reject.rs"
if rustc --edition=2024 --extern "leleka_cuda_driver=$rlib" -L "dependency=$work/target/debug/deps" \
"$work/reject.rs" -o "$work/reject" 2>"$work/reject.log"; then
echo "unsafe trait escape: $typename $trait" >&2; exit 1
fi
grep -Eq 'cannot be (sent|shared).*safely' "$work/reject.log"
echo "compile refusal $typename $trait: PASS"
done
done
cat > "$work/reject.rs" <<'RS'
use leleka_cuda_driver::Driver;
fn main(){let driver=Driver::load().unwrap();let device=driver.device(0).unwrap();let context=device.create_context(16).unwrap();drop(driver);context.synchronize().unwrap();}
RS
if rustc --edition=2024 --extern "leleka_cuda_driver=$rlib" -L "dependency=$work/target/debug/deps" \
"$work/reject.rs" -o "$work/reject" 2>"$work/reject.log"; then echo 'driver lifetime escaped' >&2; exit 1; fi
grep -q 'cannot move out of.*driver.*because it is borrowed' "$work/reject.log"
cat > "$work/reject.rs" <<'RS'
use leleka_cuda_driver::Driver;
fn main(){let driver=Driver::load().unwrap();let device=driver.device(0).unwrap();let context=device.create_context(16).unwrap();let buffer=context.allocate(8).unwrap();context.close().unwrap();buffer.copy_to(&mut [0;8]).unwrap();}
RS
if rustc --edition=2024 --extern "leleka_cuda_driver=$rlib" -L "dependency=$work/target/debug/deps" \
"$work/reject.rs" -o "$work/reject" 2>"$work/reject.log"; then echo 'context lifetime escaped' >&2; exit 1; fi
grep -q 'cannot move out of.*context.*because it is borrowed' "$work/reject.log"
echo 'two lifetime compile refusals: PASS'
cat > "$work/reject.rs" <<'RS'
use leleka_cuda_driver::Driver;
fn main(){let driver=Driver::load().unwrap();let context=driver.device(0).unwrap().create_context(16).unwrap();let mut buffer=context.allocate(4).unwrap();context.vector_add_f32(&buffer,&buffer,&mut buffer).unwrap();}
RS
if rustc --edition=2024 --extern "leleka_cuda_driver=$rlib" -L "dependency=$work/target/debug/deps" \
"$work/reject.rs" -o "$work/reject" 2>"$work/reject.log"; then echo 'output alias escaped' >&2; exit 1; fi
grep -q 'cannot borrow.*buffer.*as mutable because it is also borrowed as immutable' "$work/reject.log"
echo 'vector output alias compile refusal: PASS'
cargo tree --offline --locked --manifest-path "${repo_root}/Cargo.toml" -p leleka-cuda-driver --edges normal
exit 0
fi
[[ $# == 0 ]] || { echo 'Usage: scripts/test-cuda-driver-bootstrap.sh [--inside]' >&2; exit 2; }
staging="$(mktemp -d "${TMPDIR:-/tmp}/leleka-cuda-bootstrap.XXXXXX")"
container=''
setup_container=''
fixture_image=''
cleanup() {
local result=$? failed=0
set +e
if [[ -n "$container" ]]; then docker rm -f "$container" >/dev/null || failed=1; fi
if [[ -n "$setup_container" ]]; then docker rm -f "$setup_container" >/dev/null || failed=1; fi
if [[ -n "$fixture_image" ]]; then docker image rm "$fixture_image" >/dev/null || failed=1; fi
rm -rf "$staging" || failed=1
if [[ "$result" == 0 && "$failed" == 1 ]]; then result=1; fi
exit "$result"
}
trap cleanup EXIT
mkdir -p "$staging/src/crates" "$staging/src/scripts"
cp -R "${repo_root}/crates/cuda-driver" "$staging/src/crates/"
cp "${BASH_SOURCE[0]}" "$staging/src/scripts/test-cuda-driver-bootstrap.sh"
{ printf '[workspace]\nresolver = "3"\nmembers = ["crates/cuda-driver"]\n\n';
sed -n '/^\[workspace.package\]/,$p' "${repo_root}/Cargo.toml"; } > "$staging/src/Cargo.toml"
# Only the already-approved pinned libc registry archive is admitted as a dependency.
libc_archive=''
for candidate in "${CARGO_HOME:-${HOME}/.cargo}"/registry/cache/*/libc-0.2.190.crate; do
if [[ -f "$candidate" ]]; then libc_archive="$candidate"; break; fi
done
[[ -n "$libc_archive" ]]
python3 - "$libc_archive" "$staging/src" "${repo_root}/Cargo.lock" <<'PYVENDOR'
import hashlib,json,pathlib,sys,tarfile
archive,root,lock=map(pathlib.Path,sys.argv[1:])
expected='ce5d3ddc6d3fa000eb1536d85e147bfe31aacaba692ed6a876f95cb7c855be78'
assert hashlib.sha256(archive.read_bytes()).hexdigest()==expected
rows=lock.read_text().split('[[package]]')
packages=[row for row in rows[1:] if '\nname = "leleka-cuda-driver"\n' in row or '\nname = "libc"\n' in row]
assert len(packages)==2
assert 'checksum = "'+expected+'"' in ''.join(packages)
(root/'Cargo.lock').write_text('version = 4\n'+''.join('[[package]]'+row for row in packages))
vendor=root/'vendor'/'libc-0.2.190'
checksums={}
with tarfile.open(archive) as source:
for member in source:
path=pathlib.PurePosixPath(member.name)
assert path.parts[0]=='libc-0.2.190' and '..' not in path.parts and not path.is_absolute()
if member.isdir():continue
assert member.isfile()
relative=pathlib.Path(*path.parts[1:]);destination=vendor/relative
destination.parent.mkdir(parents=True,exist_ok=True)
data=source.extractfile(member).read();destination.write_bytes(data)
checksums[relative.as_posix()]=hashlib.sha256(data).hexdigest()
(vendor/'.cargo-checksum.json').write_text(json.dumps({'files':checksums,'package':expected}))
(root/'.cargo').mkdir()
(root/'.cargo'/'config.toml').write_text('[source.crates-io]\nreplace-with = "vendored-sources"\n[source.vendored-sources]\ndirectory = "vendor"\n')
print('Approved libc registry archive SHA256 '+expected+'; exact files vendor-verified by Cargo')
PYVENDOR
chmod -R a+rX "$staging/src"
docker pull "$image" >/dev/null
docker image inspect "$image" --format 'Pinned CPU base {{.Id}} architecture={{.Architecture}}'
# Rust official image lacks optional lint/format components. Provision only these
# verified pinned-toolchain components in a disposable setup container; runtime
# tests run later with network disabled and zero capabilities/non-root.
setup_container="$(docker create --runtime runc --cap-drop ALL --security-opt no-new-privileges \
--network bridge --memory 1536m --cpus 2 --pids-limit 128 "$image" \
bash -c 'for d in /dev/nvidia* /dev/dri/*; do [[ ! -e "$d" ]] || exit 1; done; rustup component add rustfmt clippy')"
docker start -a "$setup_container"
[[ "$(docker inspect "$setup_container" --format '{{.State.ExitCode}}')" == 0 ]]
fixture_image="$(docker commit "$setup_container")"
docker rm "$setup_container" >/dev/null
setup_container=''
docker image inspect "$fixture_image" --format 'Actual CPU fixture image {{.Id}} architecture={{.Architecture}}'
container="$(docker create --runtime runc --user 65532:65532 --cap-drop ALL \
--security-opt no-new-privileges --network none --memory 1536m --cpus 2 --pids-limit 128 \
--tmpfs /tmp:rw,nosuid,exec,size=768m "$fixture_image" sleep 900)"
configuration="$(docker inspect "$container" --format '{{.HostConfig.NetworkMode}}|{{.HostConfig.Runtime}}|{{.HostConfig.Privileged}}|{{.Config.User}}|{{len .HostConfig.Devices}}|{{len .HostConfig.DeviceRequests}}|{{len .HostConfig.Binds}}|{{.HostConfig.CapDrop}}|{{.HostConfig.SecurityOpt}}')"
[[ "$configuration" == 'none|runc|false|65532:65532|0|0|0|[ALL]|[no-new-privileges]' ]]
echo "CPU mock container: $configuration"
docker cp "$staging/src/." "$container:/src"
docker start "$container" >/dev/null
docker exec "$container" bash /src/scripts/test-cuda-driver-bootstrap.sh --inside
+72
View File
@@ -0,0 +1,72 @@
#!/usr/bin/env bash
# Offline assembly acceptance only; no installed driver, GPU, or PTX execution.
set -euo pipefail
[[ $# == 0 ]] || { echo 'Usage: scripts/test-cuda-fixed-ptx.sh' >&2; exit 2; }
repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
image='ubuntu@sha256:f610ab94648195aa356059f5b41d6085c9d4d903c072430cdd1af7bdb646106b'
work="$(mktemp -d "${TMPDIR:-/tmp}/leleka-fixed-ptx.XXXXXX")"
container=''
cleanup() {
local result=$? failed=0
set +e
if [[ -n "$container" ]]; then docker rm -f "$container" >/dev/null || failed=1; fi
rm -rf "$work" || failed=1
if [[ "$failed" == 1 ]]; then echo 'PTX owned cleanup failed' >&2; result=1; else echo 'PTX owned container/files removed; shared base retained'; fi
exit "$result"
}
trap cleanup EXIT
python3 - "$repo_root" "$work" <<'PY'
import hashlib, json, pathlib, sys, tarfile, urllib.request
root, work = map(pathlib.Path, sys.argv[1:])
lock = json.loads((root/'deploy/cuda-toolkit.lock.json').read_text())
component = next(row for row in lock['components'] if row['component'] == 'cuda_nvcc')
expected = '48e35be3cfbf4b4fbc16828eaec8a7048ee789403049dc409f7b643d6259cf7a'
assert component['version']=='13.0.88' and component['sha256']==expected
assert component['relative_path']=='cuda_nvcc/linux-x86_64/cuda_nvcc-linux-x86_64-13.0.88-archive.tar.xz'
assert int(component['size'])==26657716
url='https://developer.download.nvidia.com/compute/cuda/redist/'+component['relative_path']
with urllib.request.urlopen(url, timeout=60) as response:
data=response.read(26657717)
assert len(data)==26657716 and hashlib.sha256(data).hexdigest()==expected
archive=work/'nvcc.tar.xz'; archive.write_bytes(data)
with tarfile.open(archive, 'r:xz') as source:
member=source.getmember('cuda_nvcc-linux-x86_64-13.0.88-archive/bin/ptxas')
assert member.isfile() and member.size < 100_000_000
binary=source.extractfile(member).read()
assert binary[:4]==b'\x7fELF'
(work/'ptxas').write_bytes(binary); (work/'ptxas').chmod(0o755)
ptx=(root/'crates/cuda-driver/src/vector_add.ptx').read_bytes()
assert 0<len(ptx)<=16384 and b'\0' not in ptx
(work/'vector_add.ptx').write_bytes(ptx)
print('Official archive URL:',url)
print('Official archive bytes/SHA256:',len(data),expected)
print('Extracted ptxas SHA256:',hashlib.sha256(binary).hexdigest())
print('PTX file SHA256:',hashlib.sha256(ptx).hexdigest())
print('Embedded PTX including final NUL SHA256:',hashlib.sha256(ptx+b'\0').hexdigest())
PY
docker pull --platform linux/amd64 "$image" >/dev/null
docker image inspect "$image" --format 'Pinned assembly CPU base {{.Id}} architecture={{.Architecture}}'
container="$(docker create --platform linux/amd64 --runtime runc --user 65532:65532 \
--cap-drop ALL --security-opt no-new-privileges --network none --read-only \
--memory 768m --cpus 2 --pids-limit 64 --tmpfs /tmp:rw,nosuid,exec,size=128m \
"$image" sleep 900)"
configuration="$(docker inspect "$container" --format '{{.HostConfig.NetworkMode}}|{{.HostConfig.Runtime}}|{{.HostConfig.Privileged}}|{{.Config.User}}|{{len .HostConfig.Devices}}|{{len .HostConfig.DeviceRequests}}|{{len .HostConfig.Binds}}|{{.HostConfig.CapDrop}}|{{.HostConfig.SecurityOpt}}')"
[[ "$configuration" == 'none|runc|false|65532:65532|0|0|0|[ALL]|[no-new-privileges]' ]]
echo "PTX assembly container $container: $configuration"
docker start "$container" >/dev/null
# Docker cp writes the container rootfs rather than this running tmpfs on some
# daemon versions. Stream only the two verified files into the owned tmpfs.
docker exec -i "$container" sh -c 'cat > /tmp/ptxas && chmod 0755 /tmp/ptxas' < "$work/ptxas"
docker exec -i "$container" sh -c 'cat > /tmp/vector_add.ptx' < "$work/vector_add.ptx"
docker exec "$container" bash -euc '
for device in /dev/nvidia* /dev/dri/*; do [[ ! -e "$device" ]] || exit 1; done
[[ "$(awk '\''/^Cap(Eff|Prm|Bnd):/{print $2}'\'' /proc/self/status)" == $'\''0000000000000000\n0000000000000000\n0000000000000000'\'' ]]
if ldconfig -p 2>/dev/null | grep -q "libcuda\.so"; then exit 1; fi
uname -sm
/tmp/ptxas --version
echo "argv: /tmp/ptxas -arch=sm_120 /tmp/vector_add.ptx -o /tmp/vector_add.cubin"
/tmp/ptxas -arch=sm_120 /tmp/vector_add.ptx -o /tmp/vector_add.cubin
sha256sum /tmp/ptxas /tmp/vector_add.ptx /tmp/vector_add.cubin
test -s /tmp/vector_add.cubin
echo "Pinned PTX assembler acceptance: PASS (no GPU execution)"
'
+739
View File
@@ -0,0 +1,739 @@
#!/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 re
import tempfile
import threading
from urllib.parse import parse_qs, urlsplit
import unittest
import uuid
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
def workflow_permissions(lines, indent):
"""Read the workflow's explicit permission maps; reject ambiguous syntax.
This is deliberately a bounded contract parser for the committed workflow,
not a general YAML loader. Anchors, inline maps, duplicate keys and broad
grants fail closed rather than being interpreted differently from Gitea.
"""
headers = [index for index, line in enumerate(lines)
if re.match(r'^' + ' ' * indent + r'permissions:', line)]
if not headers:
return None
if len(headers) != 1:
raise ValueError('duplicate permissions map')
start = headers[0]
if lines[start].split(':', 1)[1].split('#', 1)[0].strip():
raise ValueError('permissions must be an explicit map')
result = {}
for line in lines[start + 1:]:
if not line.strip() or line.lstrip().startswith('#'):
continue
spaces = len(line) - len(line.lstrip(' '))
if spaces <= indent:
break
field = re.fullmatch(' ' * (indent + 2) + r'([a-z][a-z-]*):\s*(read|write|none)\s*(?:#.*)?', line)
if field is None or field[1] in result:
raise ValueError('invalid or duplicate permission scope')
result[field[1]] = field[2]
if not result:
raise ValueError('empty permissions map')
return result
def publisher_workflow_contract(text):
if len(text.encode()) > 128 * 1024 or len(text.splitlines()) > 4096:
raise ValueError('workflow exceeds contract limits')
lines = text.splitlines()
if any(re.match(r'^ *\t', line) for line in lines):
raise ValueError('tab indentation is unsupported')
roots = [index for index, line in enumerate(lines) if line == 'jobs:']
if len(roots) != 1:
raise ValueError('expected one explicit jobs map')
start = roots[0]
if workflow_permissions(lines[:start], 0) != {'contents': 'read'}:
raise ValueError('workflow default must remain contents read-only')
jobs, current = {}, None
for line in lines[start + 1:]:
if line.strip() and not line.startswith((' ', '#')):
raise ValueError('unexpected root after jobs')
header = re.fullmatch(r' ([a-zA-Z0-9_-]+):\s*(?:#.*)?', line)
if header:
current = header[1]
if current in jobs or len(jobs) >= 128:
raise ValueError('invalid job map')
jobs[current] = []
elif (line.strip() and not line.lstrip().startswith('#')
and len(line) - len(line.lstrip(' ')) == 2):
raise ValueError('job must use an explicit block map')
elif current is not None:
jobs[current].append(line)
elif line.strip() and not line.lstrip().startswith('#'):
raise ValueError('unsupported jobs syntax')
publishers = set()
call = re.compile(r'(?:^|[\s;&|])python3?(?:\.\d+)?(?:\s+-[A-Za-z]+)*\s+[\"\']?(?:\./)?scripts/publish-gitea-release\.py[\"\']?(?:\s|$)')
for name, section in jobs.items():
commands = []
for index, line in enumerate(section):
run = re.fullmatch(r' run:\s*(.*)', line)
if run is None:
continue
if run[1] in ('|', '|-', '|+', '>', '>-', '>+'):
for body in section[index + 1:]:
if body.strip() and len(body) - len(body.lstrip(' ')) <= 8:
break
if not body.lstrip().startswith('#'):
commands.append(body.strip())
else:
commands.append(run[1])
publishes = any(call.search(command) for command in commands)
scopes = workflow_permissions(section, 4)
if publishes:
if scopes != {'contents': 'read', 'releases': 'write'}:
raise ValueError('publisher requires only contents read and releases write')
publishers.add(name)
elif scopes is not None and any(level == 'write' for level in scopes.values()):
raise ValueError('nonpublisher job must not receive writable scopes')
if len(publishers) != 4:
raise ValueError('expected four actual publisher jobs')
return publishers, jobs
class PublisherWorkflowTests(unittest.TestCase):
def workflow(self):
path = Path(__file__).resolve().parent.parent / '.github/workflows/linux.yml'
with path.open('rb') as source:
data = source.read(128 * 1024 + 1)
self.assertLessEqual(len(data), 128 * 1024)
return data.decode()
def test_actual_publisher_commands_have_narrow_job_permissions(self):
publishers, jobs = publisher_workflow_contract(self.workflow())
self.assertEqual(len(publishers), 4)
self.assertGreater(len(jobs), len(publishers))
# Discovery follows the executed command, not a hard-coded job name.
original = sorted(publishers)[0]
renamed = self.workflow().replace(f' {original}:\n', ' renamed-publication-fixture:\n', 1)
renamed_publishers, _ = publisher_workflow_contract(renamed)
self.assertIn('renamed-publication-fixture', renamed_publishers)
self.assertNotIn(original, renamed_publishers)
def test_permission_regressions_are_rejected_before_publication(self):
text = self.workflow()
publishers, jobs = publisher_workflow_contract(text)
nonpublisher = sorted(set(jobs) - publishers)[0]
mutations = (
text.replace('permissions:\n contents: read', 'permissions:\n contents: write', 1),
text.replace(' releases: write', ' releases: read', 1),
text.replace(' contents: read\n releases: write', ' contents: write\n releases: write', 1),
text.replace(f' {nonpublisher}:\n', f' {nonpublisher}:\n permissions:\n contents: write\n', 1),
text.replace(' releases: write', ' releases: write\n actions: write', 1),
text + '\n inline-job: {permissions: write-all, steps: []}\n',
text + '\n alias-job: *publisher-job\n',
text + '\n anchored-job: &publisher-job\n permissions:\n contents: write\n',
)
for index, mutation in enumerate(mutations):
with self.subTest(regression=index):
self.assertNotEqual(mutation, text)
with self.assertRaises(ValueError):
publisher_workflow_contract(mutation)
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)
self.server.current_draft = self.server.release_payload['draft']
self.server.tag_exists = False
self.server.finalize_payload = None
if self.server.fail_create:
return self.send_json(403, {'message': TOKEN})
return self.send_json(201, dict(self.server.release_payload, 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()
content = bytearray()
remaining = size
while remaining:
block = self.rfile.read(min(128 * 1024, remaining))
if not block:
raise AssertionError('truncated streamed request body')
digest.update(block)
content.extend(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})
attachment = str(uuid.UUID(hashlib.sha256(name.encode()).hexdigest()[:32]))
self.server.downloads[attachment] = bytes(content)
tag = self.server.release_payload['tag_name']
release_path = f'/owner/repo/releases/download/{tag}/{name}'
self.server.release_paths[release_path] = attachment
initial_path = {
None: release_path,
'attachment': f'/attachments/{attachment}',
'repo-attachment': f'/owner/repo/attachments/{attachment}',
'repo-release-attachment': f'/owner/repo/releases/attachments/{attachment}',
}[self.server.initial_attachment_route]
if self.server.wrong_download:
initial_path = initial_path.replace(*self.server.wrong_download)
download = f'http://127.0.0.1:{self.server.server_port}{initial_path}'
if self.server.foreign_download:
download = 'https://foreign.invalid/attachments/id'
return self.send_json(201, {'name': name, 'size': size, 'browser_download_url': download, 'uuid': self.server.uuid_override if self.server.uuid_override is not None else attachment})
self.send_json(404, {'message': 'unexpected route'})
def do_GET(self):
self.server.gets.append((self.path, self.headers.get('Authorization')))
self.server.get_states.append((self.server.current_draft, self.server.tag_exists))
if self.headers.get('Authorization') != f'token {TOKEN}':
return self.send_json(401, {'message': 'bad token'})
attachment = self.server.release_paths.get(self.path)
if attachment is not None and self.server.redirect_mode:
location = f'/attachments/{attachment}'
if self.server.redirect_mode == 'repo-attachment':
location = f'/owner/repo/releases/attachments/{attachment}'
elif self.server.redirect_mode == 'foreign':
location = self.server.foreign_url + location
elif self.server.redirect_mode == 'query':
location += '?token=synthetic'
elif self.server.redirect_mode == 'credentials':
location = f'http://user:password@127.0.0.1:{self.server.server_port}{location}'
elif self.server.redirect_mode == 'wrong-uuid':
location = '/attachments/00000000-0000-0000-0000-000000000000'
elif self.server.redirect_mode == 'wrong-route':
location = '/owner/other/releases/download/tag/asset'
self.send_response(302)
self.send_header('Location', location)
self.send_header('Content-Length', '0')
self.end_headers()
return
if attachment is None:
attachment = self.path.rsplit('/', 1)[-1]
if self.server.redirect_mode in {'loop', 'two-hops'} and '/attachments/' in self.path:
if self.server.redirect_mode == 'loop' or self.path.startswith('/attachments/'):
self.send_response(302)
location = f'/owner/repo/releases/attachments/{attachment}'
self.send_header('Location', location)
self.send_header('Content-Length', '0')
self.end_headers()
return
content = self.server.downloads.get(attachment)
if content is None:
return self.send_json(404, {})
if self.server.corrupt_download:
content = b'x' + content[1:]
self.send_response(200)
self.send_header('Content-Length', str(len(content)))
self.end_headers()
self.wfile.write(content)
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.server.current_draft = self.server.finalize_payload['draft']
self.server.tag_exists = not self.server.current_draft
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.server.downloads = {}
self.server.release_paths = {}
self.server.gets = []
self.server.get_states = []
self.server.current_draft = True
self.server.tag_exists = False
self.server.wrong_download = None
self.server.initial_attachment_route = None
self.server.uuid_override = None
self.server.redirect_mode = None
self.server.foreign_url = 'http://foreign.invalid'
self.server.foreign_download = False
self.server.corrupt_download = 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()
features = {'schema_version': 1, 'source_revision': REVISION, 'cuda_architectures': '120',
'features': {'cuda': True, 'cuda_static_runtime': True, 'cxx_static_runtime': True,
'kar_ple': False, 'kar_experts': False, 'ple_trace': False}}
feature_sha = publisher.canonical_sha(features)
base = 'ubuntu@sha256:' + 'b' * 64
package_provenance = {
'schema_version': 1, 'kind': 'static-cuda-preview', 'source_revision': REVISION,
'target': 'x86_64-unknown-linux-musl', 'gpu_tested': False, 'model_tested': False,
'clean_node_tested': False,
'engine': {'sha256': engine_sha, 'embedded': True, 'target_os': 'linux',
'target_arch': 'x86_64', 'declared_source_revision': REVISION, 'bytes': 19},
'engine_elf_audit': {'toolkit_shared_libraries': False, 'host_glibc_required': True,
'minimum_glibc': '2.39'},
'loader_probe': {'environment': 'pinned-runtime-container', 'base': base, 'glibc': '2.43',
'image_id': 'sha256:' + 'b' * 64, 'user': '65532:65532', 'gpu_tested': False},
'build_features': features, 'build_features_sha256': feature_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 = {
'schema_version': 1, 'kind': 'static-cuda-preview', 'source_revision': REVISION,
'image': 'sha256:' + 'c' * 64, 'base': base, 'base_glibc': '2.43',
'gpu_tested': False, 'model_tested': False, 'package_receipt_sha256': receipt,
'build_features': features['features'], 'build_features_sha256': feature_sha,
'qualification': 'Non-root GPU-hidden embedded identity and loader help only.',
}
(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,
'builder_image_id': 'sha256:' + 'd' * 64, 'cuda_architectures': '120',
'build_features': features['features'], 'build_features_sha256': feature_sha,
'docker_builder': {'source_commit': REVISION, 'engine_sha256': engine_sha,
'image_id': 'sha256:' + 'd' * 64, 'build_features_sha256': feature_sha,
'runtime_image_id': image_provenance['image'],
'runtime_archive_sha256': publisher.file_sha256(directory / 'runtime-image.tar')},
}))
(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$') 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$'):
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)
def rehash(self):
for manifest, names in [('SHA256SUMS', publisher.PACKAGE_ASSETS),
('IMAGE-SHA256SUMS', publisher.IMAGE_ASSETS)]:
(self.directory / manifest).write_text(''.join(
f'{publisher.file_sha256(self.directory / name)} {name}\n' for name in sorted(names)))
image_path = self.directory / 'IMAGE-PROVENANCE.json'
image = json.loads(image_path.read_text())
image['package_receipt_sha256'] = publisher.file_sha256(self.directory / 'SHA256SUMS')
image_path.write_text(json.dumps(image))
(self.directory / 'IMAGE-SHA256SUMS').write_text(''.join(
f'{publisher.file_sha256(self.directory / name)} {name}\n' for name in sorted(publisher.IMAGE_ASSETS)))
def test_current_producer_receipt_contract(self):
# Exercise the producer's own validators, not source-text pattern checks.
import shutil
for filename in ('build-linux-package.py', 'build-runtime-image.py'):
spec = importlib.util.spec_from_file_location('producer', Path(__file__).with_name(filename))
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp)
package = json.loads((self.directory / 'PROVENANCE.json').read_text())
feature_file = root / 'BUILD-FEATURES.json'
feature_file.write_text(json.dumps(package['build_features'], sort_keys=True, indent=2) + '\n')
if filename == 'build-linux-package.py':
self.assertEqual(module.build_features(feature_file, REVISION),
(package['build_features'], package['build_features_sha256']))
else:
source = root / 'source'
stage = root / 'stage'
source.mkdir(); stage.mkdir()
for name in module.FILES:
shutil.copyfile(self.directory / name, source / name)
self.assertEqual(module.freeze(source, stage,
publisher.file_sha256(source / 'SHA256SUMS'), False), package)
self.assertEqual(set(publisher.verify_artifacts(self.directory, REVISION)), publisher.ASSETS)
def test_forged_receipt_bindings_fail_even_with_fresh_checksums(self):
faults = [('CUDA-TOOLCHAIN.json', ('docker_builder', 'engine_sha256'), 'e' * 64),
('CUDA-TOOLCHAIN.json', ('docker_builder', 'runtime_image_id'), 'sha256:' + 'e' * 64),
('CUDA-TOOLCHAIN.json', ('docker_builder', 'source_commit'), 'e' * 40),
('CUDA-TOOLCHAIN.json', ('docker_builder', 'runtime_archive_sha256'), 'e' * 64),
('CUDA-TOOLCHAIN.json', ('build_features_sha256',), 'e' * 64),
('IMAGE-PROVENANCE.json', ('base',), 'ubuntu@sha256:' + 'e' * 64),
('IMAGE-PROVENANCE.json', ('gpu_tested',), True),
('PROVENANCE.json', ('loader_probe', 'environment'), 'assembly-host'),
('PROVENANCE.json', ('build_features', 'source_revision'), 'e' * 40),
('PROVENANCE.json', ('build_features', 'features', 'kar_experts'), True),
('PROVENANCE.json', ('engine_elf_audit', 'toolkit_shared_libraries'), True),
('PROVENANCE.json', ('engine_elf_audit', 'minimum_glibc'), '99.0'),
('PROVENANCE.json', ('loader_probe', 'glibc'), None)]
for filename, keys, value in faults:
with self.subTest(filename=filename, keys=keys):
self.write_artifacts()
path = self.directory / filename
record = json.loads(path.read_text())
dest = record
for key in keys[:-1]:
dest = dest[key]
dest[keys[-1]] = value
path.write_text(json.dumps(record))
self.rehash()
with self.assertRaises(ValueError):
publisher.publish(self.api_url, 'owner/repo', TOKEN, 'cuda-preview-42-1', REVISION,
'title', 'notes', self.directory)
self.assertIsNone(self.server.release_payload)
def write_cli(self):
for path in self.directory.iterdir():
path.unlink()
(self.directory / publisher.PACKAGE_BINARY).write_bytes(b'synthetic-static-cli')
(self.directory / 'BUILD-PROVENANCE.txt').write_text(
f'Commit: {REVISION}\nWorkflow: https://gitea.invalid/owner/repo/actions/runs/42\nrustc fixture\n')
(self.directory / 'ELF-AUDIT.txt').write_text(
'ELF Header:\n Class: ELF64\n Machine: Advanced Micro Devices X86-64\nNo dynamic section.\n')
self.rehash_cli()
def rehash_cli(self):
(self.directory / 'SHA256SUMS').write_text(''.join(
f'{publisher.file_sha256(self.directory / name)} {name}\n'
for name in sorted(publisher.CLI_ASSETS - {'SHA256SUMS'})))
def test_cli_four_assets_and_version_tag_publish_after_all_uploads(self):
self.write_cli()
for tag in ('cli-preview-42-1', 'v0.1.0-preview'):
self.server.assets = []
result = publisher.publish(self.api_url, 'owner/repo', TOKEN, tag, REVISION,
'CLI preview', 'No engine or model.', self.directory, 'cli')
self.assertEqual({asset['name'] for asset in result['assets']}, publisher.CLI_ASSETS)
self.assertTrue(self.server.release_payload['draft'])
self.assertTrue(self.server.release_payload['prerelease'])
self.assertEqual(self.server.finalize_payload, {'draft': False})
def test_cli_mismatch_and_bad_static_audit_fail_before_create(self):
for fault in ('wrong-commit', 'duplicate-commit', 'dynamic-elf', 'tamper', 'extra-file'):
with self.subTest(fault=fault):
self.write_cli()
provenance = self.directory / 'BUILD-PROVENANCE.txt'
if fault == 'wrong-commit':
provenance.write_text(provenance.read_text().replace(REVISION, 'e' * 40))
elif fault == 'duplicate-commit':
provenance.write_text(provenance.read_text() + f'Commit: {REVISION}\n')
elif fault == 'dynamic-elf':
audit = self.directory / 'ELF-AUDIT.txt'
audit.write_text(audit.read_text() + 'INTERP\n')
elif fault == 'extra-file':
(self.directory / 'private-key').write_text('synthetic')
self.rehash_cli()
if fault == 'tamper':
(self.directory / publisher.PACKAGE_BINARY).write_bytes(b'tampered')
with self.assertRaises(ValueError):
publisher.publish(self.api_url, 'owner/repo', TOKEN, 'cli-preview-42-1', REVISION,
'title', 'notes', self.directory, 'cli')
self.assertIsNone(self.server.release_payload)
def test_missing_cuda_files_and_cli_upload_fault_leave_no_published_release(self):
(self.directory / 'CUDA-LICENSES.tar').unlink()
with self.assertRaises(ValueError):
publisher.verify_artifacts(self.directory, REVISION)
self.write_cli()
self.server.fail_asset = True
with self.assertRaises(RuntimeError):
publisher.publish(self.api_url, 'owner/repo', TOKEN, 'cli-preview-42-1', REVISION,
'title', 'notes', self.directory, 'cli')
self.assertTrue(self.server.release_payload['draft'])
self.assertIsNone(self.server.finalize_payload)
def test_remote_corruption_and_foreign_download_leave_release_draft(self):
for flag in ('corrupt_download', 'foreign_download'):
with self.subTest(flag=flag):
setattr(self.server, flag, True)
with self.assertRaises(ValueError):
publisher.publish(self.api_url, 'owner/repo', TOKEN, 'cuda-preview-42-1', REVISION,
'title', 'notes', self.directory)
self.assertTrue(self.server.release_payload['draft'])
self.assertIsNone(self.server.finalize_payload)
setattr(self.server, flag, False)
def test_static_cuda_exact_six_file_profile(self):
for name in ('CUDA-TOOLCHAIN.json', 'CUDA-LICENSES.tar'):
(self.directory / name).unlink()
(self.directory / 'IMAGE-SHA256SUMS').write_text(''.join(
f'{publisher.file_sha256(self.directory / name)} {name}\n'
for name in sorted(publisher.STATIC_IMAGE_ASSETS)))
result = publisher.publish(self.api_url, 'owner/repo', TOKEN, 'static-cuda-preview-42-1', REVISION,
'Static preview', 'No hosted toolchain qualification.', self.directory, 'static-cuda')
self.assertEqual({asset['name'] for asset in result['assets']}, publisher.STATIC_ASSETS)
with self.assertRaises(ValueError):
publisher.verify_artifacts(self.directory, REVISION, 'cuda')
def test_https_policy_and_profile_tag_isolation(self):
for url in ('http://gitea.invalid/api/v1', 'https://api.github.com/api/v1',
'https://user:password@gitea.invalid/api/v1'):
with self.assertRaises(ValueError):
publisher.parse_api_url(url)
for tag in ('cli-preview-42-1', 'static-cuda-preview-42-1', 'v0.1.0'):
with self.assertRaises(ValueError):
publisher.publish(self.api_url, 'owner/repo', TOKEN, tag, REVISION,
'title', 'notes', self.directory, 'cuda')
self.assertIsNone(self.server.release_payload)
def test_invalid_token_is_rejected_without_transport_or_secret_echo(self):
for token in ('synthetic-secret\r\ninjected', 'synthetic secret', 'x' * 513, 'synthetic-\u00e9'):
with self.subTest(token_kind=len(token)):
with self.assertRaisesRegex(ValueError, 'bounded printable ASCII') 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.assertNotIn('synthetic-secret', str(failure.exception))
self.assertIsNone(self.server.release_payload)
def test_nonregular_and_symlink_files_are_rejected_before_transport(self):
import os
path = self.directory / 'CUDA-LICENSES.tar'
path.unlink()
os.mkfifo(path)
with self.assertRaisesRegex(ValueError, 'regular artifact'):
publisher.verify_artifacts(self.directory, REVISION)
path.unlink()
path.symlink_to(self.directory / publisher.PACKAGE_BINARY)
with self.assertRaises(OSError):
publisher.verify_artifacts(self.directory, REVISION)
self.assertIsNone(self.server.release_payload)
def test_release_download_route_and_same_origin_redirects_verify_before_publish(self):
for mode in (None, 'attachment', 'repo-attachment', 'two-hops'):
with self.subTest(mode=mode):
self.server.redirect_mode = mode
self.server.gets = []
self.server.get_states = []
self.server.assets = []
result = publisher.publish(self.api_url, 'owner/repo', TOKEN, 'cuda-preview-42-1', REVISION,
'title', 'notes', self.directory)
self.assertEqual(len(result['assets']), 8)
self.assertEqual(self.server.finalize_payload, {'draft': False})
self.assertTrue(any('/owner/repo/releases/download/cuda-preview-42-1/' in path
for path, _auth in self.server.gets))
self.assertTrue(all(auth == f'token {TOKEN}' for _path, auth in self.server.gets))
expected_gets = 8 * ({None: 1, 'two-hops': 3}.get(mode, 2))
self.assertEqual(len(self.server.gets), expected_gets)
self.assertEqual(self.server.get_states, [(True, False)] * expected_gets)
self.assertFalse(self.server.current_draft)
self.assertTrue(self.server.tag_exists)
def test_foreign_redirect_is_rejected_without_forwarding_token(self):
foreign = ThreadingHTTPServer(('127.0.0.1', 0), FakeGitea)
foreign.gets = []
foreign.get_states = []
foreign.current_draft = True
foreign.tag_exists = False
thread = threading.Thread(target=foreign.serve_forever, daemon=True)
thread.start()
self.addCleanup(foreign.server_close)
self.addCleanup(thread.join)
self.addCleanup(foreign.shutdown)
self.server.foreign_url = f'http://127.0.0.1:{foreign.server_port}'
self.server.redirect_mode = 'foreign'
with self.assertRaisesRegex(ValueError, 'same-origin'):
publisher.publish(self.api_url, 'owner/repo', TOKEN, 'cuda-preview-42-1', REVISION,
'title', 'notes', self.directory)
self.assertEqual(foreign.gets, [])
self.assertEqual(len(self.server.gets), 1)
self.assertIsNone(self.server.finalize_payload)
def test_redirect_limit_and_untrusted_destinations_leave_draft(self):
for mode in ('loop', 'query', 'credentials', 'wrong-uuid', 'wrong-route'):
with self.subTest(mode=mode):
self.server.redirect_mode = mode
self.server.gets = []
with self.assertRaises(ValueError):
publisher.publish(self.api_url, 'owner/repo', TOKEN, 'cuda-preview-42-1', REVISION,
'title', 'notes', self.directory)
self.assertLessEqual(len(self.server.gets), 3)
self.assertTrue(self.server.release_payload['draft'])
self.assertIsNone(self.server.finalize_payload)
def test_fresh_post_attachment_routes_verify_remote_bytes_before_finalizing(self):
for mode in ('attachment', 'repo-attachment', 'repo-release-attachment'):
with self.subTest(mode=mode):
self.server.initial_attachment_route = mode
self.server.gets = []
self.server.get_states = []
result = publisher.publish(self.api_url, 'owner/repo', TOKEN, 'cuda-preview-42-1', REVISION,
'title', 'notes', self.directory)
self.assertEqual(len(result['assets']), 8)
self.assertEqual(len(self.server.gets), 8)
self.assertEqual(self.server.get_states, [(True, False)] * 8)
self.assertTrue(all('/attachments/' in path for path, _auth in self.server.gets))
self.assertTrue(all(auth == f'token {TOKEN}' for _path, auth in self.server.gets))
for asset in result['assets']:
self.assertEqual(asset['sha256'], hashlib.sha256(
(self.directory / asset['name']).read_bytes()).hexdigest())
self.assertEqual(self.server.finalize_payload, {'draft': False})
def test_fresh_post_attachment_remote_corruption_leaves_draft(self):
self.server.initial_attachment_route = 'attachment'
self.server.corrupt_download = True
with self.assertRaisesRegex(ValueError, 'checksum mismatch'):
publisher.publish(self.api_url, 'owner/repo', TOKEN, 'cuda-preview-42-1', REVISION,
'title', 'notes', self.directory)
self.assertEqual(len(self.server.gets), 1)
self.assertTrue(self.server.current_draft)
self.assertIsNone(self.server.finalize_payload)
def test_fresh_post_attachment_untrusted_routes_receive_no_token(self):
for mode, substitution in (
('attachment', ('/attachments/', '/attachments/00000000-0000-0000-0000-000000000000/')),
('repo-attachment', ('/owner/repo/', '/owner/other/')),
('repo-release-attachment', ('/owner/repo/', '/other/repo/')),
('attachment', ('/attachments/', '/attachments/?token=synthetic&uuid=')),
('attachment', ('/attachments/', '/attachments/#'))):
with self.subTest(mode=mode, substitution=substitution):
self.server.initial_attachment_route = mode
self.server.wrong_download = substitution
self.server.gets = []
with self.assertRaisesRegex(ValueError, 'same-origin'):
publisher.publish(self.api_url, 'owner/repo', TOKEN, 'cuda-preview-42-1', REVISION,
'title', 'notes', self.directory)
self.assertEqual(self.server.gets, [])
self.assertIsNone(self.server.finalize_payload)
self.server.wrong_download = None
self.server.foreign_download = True
self.server.gets = []
with self.assertRaisesRegex(ValueError, 'same-origin'):
publisher.publish(self.api_url, 'owner/repo', TOKEN, 'cuda-preview-42-1', REVISION,
'title', 'notes', self.directory)
self.assertEqual(self.server.gets, [])
self.assertIsNone(self.server.finalize_payload)
def test_fresh_post_requires_valid_matching_uuid_before_download(self):
self.server.initial_attachment_route = 'attachment'
for attachment in ('not-a-uuid', '', 73, '00000000-0000-0000-0000-000000000000'):
with self.subTest(attachment=attachment):
self.server.uuid_override = attachment
self.server.gets = []
with self.assertRaises(ValueError):
publisher.publish(self.api_url, 'owner/repo', TOKEN, 'cuda-preview-42-1', REVISION,
'title', 'notes', self.directory)
self.assertEqual(self.server.gets, [])
self.assertIsNone(self.server.finalize_payload)
def test_initial_download_url_requires_exact_repository_tag_and_asset(self):
for substitution in (('/owner/repo/', '/owner/other/'),
('cuda-preview-42-1', 'cuda-preview-43-1'),
('CUDA-LICENSES.tar', 'OTHER.tar')):
with self.subTest(substitution=substitution):
self.server.wrong_download = substitution
self.server.gets = []
with self.assertRaisesRegex(ValueError, 'same-origin release'):
publisher.publish(self.api_url, 'owner/repo', TOKEN, 'cuda-preview-42-1', REVISION,
'title', 'notes', self.directory)
self.assertEqual(self.server.gets, [])
self.assertIsNone(self.server.finalize_payload)
if __name__ == '__main__':
unittest.main()
+54
View File
@@ -35,6 +35,28 @@ class PackageTests(unittest.TestCase):
with self.assertRaises(ValueError):
pkg.snapshot(source, self.root / pin, pin)
def test_build_feature_receipt_is_pinned_strict_and_linkage_safe(self):
revision = 'a' * 40
features = {'schema_version': 1, 'source_revision': revision,
'cuda_architectures': '120',
'features': {'cuda': True, 'cuda_static_runtime': True, 'cxx_static_runtime': True, 'kar_ple': True,
'kar_experts': False, 'ple_trace': False}}
path = self.root / 'BUILD-FEATURES.json'
path.write_text(json.dumps(features, sort_keys=True, indent=2) + '\n')
parsed, digest = pkg.build_features(path, revision)
self.assertEqual(parsed, features)
self.assertEqual(digest, hashlib.sha256(path.read_bytes()).hexdigest())
with self.assertRaisesRegex(ValueError, 'source-mismatched'):
pkg.build_features(path, 'b' * 40)
features['features']['kar_experts'] = True
path.write_text(json.dumps(features, sort_keys=True, indent=2) + '\n')
with self.assertRaisesRegex(ValueError, 'contract'):
pkg.build_features(path, revision)
path.unlink()
path.symlink_to('/dev/null')
with self.assertRaises(OSError):
pkg.build_features(path, revision)
def test_snapshot_rejects_oversize_and_nonregular_without_block(self):
source = self.root / 'engine'
source.write_bytes(b'over limit')
@@ -117,6 +139,38 @@ class PackageTests(unittest.TestCase):
build.assert_not_called()
self.assertEqual((output / 'old').read_text(), 'keep')
def test_assembly_records_workspace_lock_digest(self):
from types import SimpleNamespace
engine = self.root / 'engine'
engine.write_bytes(b'CPU package fixture')
workspace_lock = self.root / 'Cargo.lock'
workspace_lock.write_text('version = 4\n')
target = self.root / 'target'
binary = target / pkg.TARGET / 'release/strata-next'
binary.parent.mkdir(parents=True)
binary.write_bytes(b'outer executable fixture')
args = SimpleNamespace(engine=engine, sha256=pkg.sha256(engine), revision='a' * 40,
output=self.root / 'final', cargo_target_dir=target, cpu_fixture=True)
info = {'embedded': True, 'sha256': args.sha256, 'declared_source_revision': args.revision,
'bytes': engine.stat().st_size, 'target_os': 'linux', 'target_arch': 'x86_64'}
published = {}
def capture_publication(source, output):
published.update(json.loads((source / 'PROVENANCE.json').read_text()))
with (patch.object(pkg, 'REPO', self.root),
patch.object(pkg.platform, 'system', return_value='Linux'),
patch.object(pkg.platform, 'machine', return_value='x86_64'),
patch.object(pkg, 'source_check'), patch.object(pkg.subprocess, 'run'),
patch.object(pkg, 'static_outer', return_value={'fixture': True}),
patch.object(pkg, 'run', side_effect=[json.dumps(info), '', 'rustc fixture', 'cargo fixture']),
patch.object(pkg, 'publish', side_effect=capture_publication)):
pkg.assemble(args)
self.assertEqual(published['cargo_lock_sha256'], pkg.sha256(workspace_lock))
self.assertFalse(published['gpu_tested'])
self.assertFalse(published['model_tested'])
self.assertFalse(list(self.root.glob('.final.stage-*')))
if __name__ == '__main__':
unittest.main()
+54
View File
@@ -0,0 +1,54 @@
#!/usr/bin/env python3
"""Real CPU Docker transport/failure regression; not engine or GPU qualification."""
import importlib.util
from pathlib import Path
import tempfile
import unittest
spec = importlib.util.spec_from_file_location('package', Path(__file__).with_name('build-linux-package.py'))
package = importlib.util.module_from_spec(spec)
spec.loader.exec_module(package)
class LoaderContainerTests(unittest.TestCase):
def test_actual_nonroot_provision_and_failure_cleanup(self):
runtime_spec = importlib.util.spec_from_file_location('runtime', Path(__file__).with_name('build-runtime-image.py'))
runtime = importlib.util.module_from_spec(runtime_spec)
runtime_spec.loader.exec_module(runtime)
def probes():
containers = set(runtime.docker('ps', '-a', '--filter', 'name=strata-package-probe-',
'--format', '{{.ID}}').stdout.splitlines())
volumes = set(runtime.docker('volume', 'ls', '--filter', 'name=strata-package-probe-',
'--format', '{{.Name}}').stdout.splitlines())
return containers, volumes
before = probes()
with tempfile.TemporaryDirectory(prefix='strata-loader-contract-') as tmp:
binary, config = Path(tmp) / 'cli', Path(tmp) / 'config'
config.write_text('{"engine":{"executable":"@embedded"},"engine_probe":true}')
binary.write_text('#!/bin/sh\n'
'test "$(id -u)" = 65532 || exit 21\n'
'test "$1" = provision && test "$2" = --config || exit 22\n'
'grep -q @embedded "$3" || exit 23\n'
'test "$NVIDIA_VISIBLE_DEVICES" = void && test -z "$CUDA_VISIBLE_DEVICES" || exit 24\n'
'touch /tmp/owned-loader-fixture || exit 25\n'
'if touch /forbidden-loader-fixture 2>/dev/null; then exit 26; fi\n')
original = binary.read_bytes()
audit = {'minimum_glibc': '2.38'}
result = package.loader_probe(binary, config, audit, container=True)
self.assertEqual(result['base'], runtime.BASE)
self.assertFalse(result['gpu_tested'])
self.assertEqual(binary.read_bytes(), original)
self.assertEqual(probes(), before)
binary.write_text('#!/bin/sh\nexit 42\n')
with self.assertRaisesRegex(ValueError, 'provision failed'):
package.loader_probe(binary, config, audit, container=True)
self.assertEqual(probes(), before)
with self.assertRaisesRegex(ValueError, 'below engine requirement'):
package.loader_probe(binary, config, {'minimum_glibc': '99.0'}, container=True)
self.assertEqual(probes(), before)
if __name__ == '__main__':
unittest.main()
+49
View File
@@ -1,8 +1,10 @@
#!/usr/bin/env python3
"""Package corruption and ABI rejection without Docker or GPU access."""
import importlib.util
import hashlib
import json
from pathlib import Path
import shutil
import tempfile
import unittest
from types import SimpleNamespace
@@ -26,6 +28,13 @@ class PackageTests(unittest.TestCase):
'declared_source_revision': 'a'*40, 'bytes': 3, 'sha256': 'b'*64},
'engine_elf_audit': {'toolkit_shared_libraries': False,
'host_glibc_required': True, 'minimum_glibc': '2.43'}}
features = {'schema_version': 1, 'source_revision': 'a'*40,
'cuda_architectures': '120',
'features': {'cuda': True, 'cuda_static_runtime': True, 'cxx_static_runtime': True,
'kar_ple': False, 'kar_experts': False, 'ple_trace': False}}
canonical = (json.dumps(features, sort_keys=True, indent=2) + '\n').encode()
self.provenance['build_features'] = features
self.provenance['build_features_sha256'] = hashlib.sha256(canonical).hexdigest()
(self.pkg/b.NAME).write_bytes(b'not executable; validator does not execute input')
self.write()
@@ -46,6 +55,46 @@ class PackageTests(unittest.TestCase):
b.check_glibc(p, 'glibc 2.39\n')
with self.assertRaises(ValueError): b.check_glibc(p, 'musl 1.2.5')
def test_static_cuda_feature_receipt_is_preserved_and_digest_checked(self):
features = {'schema_version': 1, 'source_revision': 'a'*40,
'cuda_architectures': '120',
'features': {'cuda': True, 'cuda_static_runtime': True, 'cxx_static_runtime': True, 'kar_ple': True,
'kar_experts': False, 'ple_trace': False}}
canonical = (json.dumps(features, sort_keys=True, indent=2) + '\n').encode()
self.provenance['build_features'] = features
self.provenance['build_features_sha256'] = hashlib.sha256(canonical).hexdigest()
self.write()
p = self.freeze()
self.assertTrue(p['build_features']['features']['kar_ple'])
self.provenance['build_features_sha256'] = '0'*64
self.write()
shutil.rmtree(self.stage)
self.stage.mkdir()
with self.assertRaisesRegex(ValueError, 'digest mismatch'):
self.freeze()
def test_image_receipt_carries_ple_profile_without_gpu_claim(self):
self.provenance['build_features']['features']['kar_ple'] = True
canonical = (json.dumps(self.provenance['build_features'], sort_keys=True, indent=2) + '\n').encode()
self.provenance['build_features_sha256'] = hashlib.sha256(canonical).hexdigest()
self.write()
args = SimpleNamespace(base=b.BASE, package=self.pkg, receipt_sha256=self.sha, cpu_fixture=False)
image = 'sha256:' + 'c'*64
calls = []
def docker(*argv, **kwargs):
calls.append(argv)
if argv[0] == 'build':
Path(argv[argv.index('--iidfile')+1]).write_text(image)
return SimpleNamespace(stdout='')
engine_info = json.dumps(self.provenance['engine'])
with patch.object(b, 'docker', side_effect=docker), \
patch.object(b, 'isolated_run', side_effect=['glibc 2.43', engine_info, 'help']):
result = b.assemble(args)
self.assertEqual(result['build_features']['kar_ple'], True)
self.assertEqual(result['build_features_sha256'], self.provenance['build_features_sha256'])
self.assertFalse(result['gpu_tested'])
self.assertFalse(any('--gpus' in call for call in calls))
def test_pinned_receipt_rejects_replaced_hashes(self):
(self.pkg/'SHA256SUMS').write_text('a'*64 + ' ../outside\n')
with self.assertRaisesRegex(ValueError, 'pinned receipt'): self.freeze()
+120
View File
@@ -0,0 +1,120 @@
#!/usr/bin/env python3
"""Exercise the static CUDA PLE build contract with a mocked Linux toolchain."""
import json
import os
from pathlib import Path
import shutil
import subprocess
import sys
import tempfile
import unittest
SCRIPT = Path(__file__).with_name('build-static-cuda.sh')
class StaticCudaProfileTests(unittest.TestCase):
def setUp(self):
self.tmp = tempfile.TemporaryDirectory(prefix='strata-cuda-profile-')
self.addCleanup(self.tmp.cleanup)
self.root = Path(self.tmp.name)
self.repo = self.root / 'repo'
(self.repo / 'scripts').mkdir(parents=True)
(self.repo / 'engine/strata').mkdir(parents=True)
shutil.copyfile(SCRIPT, self.repo / 'scripts/build-static-cuda.sh')
checker = self.repo / 'scripts/check-static-cuda-elf.py'
checker.write_text('raise SystemExit(0)\n')
self.bin = self.root / 'bin'
self.bin.mkdir()
(self.bin / 'uname').write_text('#!/bin/sh\necho Linux\n')
(self.bin / 'cmake').write_text(
'#!/usr/bin/env python3\n'
'import json, os, pathlib, sys\n'
'with open(os.environ["CMAKE_CAPTURE"], "a") as out: out.write(json.dumps(sys.argv[1:])+"\\n")\n'
'if "--build" in sys.argv:\n'
' b=pathlib.Path(sys.argv[sys.argv.index("--build")+1]); b.mkdir(parents=True, exist_ok=True)\n'
' p=b/"strata"; p.write_text("#!/bin/sh\\necho help\\n"); p.chmod(0o755)\n')
for executable in self.bin.iterdir(): executable.chmod(0o755)
self.capture = self.root / 'cmake.jsonl'
self.build = self.root / 'build'
subprocess.run(['git', 'init', '-q', str(self.repo)], check=True)
subprocess.run(['git', '-C', str(self.repo), 'add', '.'], check=True)
subprocess.run(['git', '-C', str(self.repo), '-c', 'user.email=fixture@example.invalid',
'-c', 'user.name=Fixture', 'commit', '-qm', 'mock toolchain fixture'], check=True)
def run_profile(self, value='unset', source_revision=None):
env = dict(os.environ)
env.update(PATH=f'{self.bin}{os.pathsep}{env["PATH"]}',
STRATA_BUILD_DIR=str(self.build), CMAKE_CAPTURE=str(self.capture),
CUDA_ARCHITECTURES='120')
env.pop('STRATA_KAR_PLE', None)
env.pop('SOURCE_REVISION', None)
if value != 'unset':
env['STRATA_KAR_PLE'] = value
if source_revision is not None:
env['SOURCE_REVISION'] = source_revision
return subprocess.run(['bash', str(self.repo / 'scripts/build-static-cuda.sh')],
env=env, text=True, capture_output=True)
def captured_configure(self):
calls = [json.loads(line) for line in self.capture.read_text().splitlines()]
configure = next(call for call in reversed(calls) if '-S' in call)
return {arg.split('=', 1)[0]: arg.split('=', 1)[1]
for arg in configure if arg.startswith('-D') and '=' in arg}
def test_defaults_off_and_explicitly_keeps_static_cuda_runtime(self):
result = self.run_profile()
self.assertEqual(result.returncode, 0, result.stderr)
flags = self.captured_configure()
self.assertEqual(flags['-DSTRATA_CUDA_STATIC'], 'ON')
self.assertEqual(flags['-DSTRATA_NEXT_EXPERIMENTAL_KAR_PLE'], 'OFF')
self.assertEqual(flags['-DSTRATA_NEXT_EXPERIMENTAL_KAR_EXPERTS'], 'OFF')
self.assertEqual(flags['-DSTRATA_NEXT_EXPERIMENTAL_PLE_TRACE'], 'OFF')
self.assertEqual(flags['-DSTRATA_NEXT_KAR_DIR'], str(self.repo / 'gpu/kar'))
features = json.loads((self.build / 'BUILD-FEATURES.json').read_text())
self.assertFalse(features['features']['kar_ple'])
self.assertTrue(features['features']['cuda_static_runtime'])
self.assertTrue(features['features']['cxx_static_runtime'])
def test_enabled_profile_is_build_only_and_expert_arm_stays_off(self):
result = self.run_profile('1')
self.assertEqual(result.returncode, 0, result.stderr)
flags = self.captured_configure()
self.assertEqual(flags['-DSTRATA_NEXT_EXPERIMENTAL_KAR_PLE'], 'ON')
self.assertEqual(flags['-DSTRATA_NEXT_EXPERIMENTAL_KAR_EXPERTS'], 'OFF')
self.assertEqual(flags['-DSTRATA_NEXT_EXPERIMENTAL_PLE_TRACE'], 'OFF')
self.assertTrue(json.loads((self.build / 'BUILD-FEATURES.json').read_text())['features']['kar_ple'])
def test_explicit_disable_resets_an_existing_cmake_cache(self):
self.assertEqual(self.run_profile('1').returncode, 0)
result = self.run_profile('0')
self.assertEqual(result.returncode, 0, result.stderr)
self.assertEqual(self.captured_configure()['-DSTRATA_NEXT_EXPERIMENTAL_KAR_PLE'], 'OFF')
self.assertFalse(json.loads((self.build / 'BUILD-FEATURES.json').read_text())['features']['kar_ple'])
def test_invalid_values_fail_before_cmake(self):
for value in ('', 'true', 'ON', '2', '01'):
with self.subTest(value=value):
self.capture.unlink(missing_ok=True)
result = self.run_profile(value)
self.assertEqual(result.returncode, 2)
self.assertIn('exactly 0 or 1', result.stderr)
self.assertFalse(self.capture.exists())
def test_archive_checkout_records_explicit_exact_source_revision(self):
revision = 'a1' * 20
(self.repo / '.git').rename(self.repo / '.git-hidden')
result = self.run_profile('1', source_revision=revision)
self.assertEqual(result.returncode, 0, result.stderr)
features = json.loads((self.build / 'BUILD-FEATURES.json').read_text())
self.assertEqual(features['source_revision'], revision)
def test_invalid_source_revision_fails_before_cmake(self):
result = self.run_profile('1', source_revision='not-a-commit')
self.assertEqual(result.returncode, 2)
self.assertIn('SOURCE_REVISION must be an exact lowercase 40-character Git commit', result.stderr)
self.assertFalse(self.capture.exists())
if __name__ == '__main__':
unittest.main()