Files
leleka/scripts/test-cuda-driver-bootstrap.sh
Pavlo RatushnyiandClaude Sonnet 5.5 9b08355660 scripts: restore the executable bit lost in the 2026-10-14 import (every workflow job died at "Permission denied")
7f896a8bb changed 100755 to 100644 on 16 scripts that the workflows or check-local.sh execute by path, among them
scripts/install-pinned-rustup.sh (the first step of every job), scripts/test-cuda-fixed-ptx.sh, scripts/test-cuda-driver-bootstrap.sh,
scripts/build-cpu.sh and the GPU gate scripts. A Linux checkout keeps git's mode, so `scripts/install-pinned-rustup.sh ...` failed with
"Permission denied" before any build. Found by running the steps from a `git archive` in a Linux container; the Windows and WSL-on-/mnt/c
runs of the first audit show every file as executable and could not see it. Only modes change; engine/strata is not touched.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-03 01:42:33 +01:00

204 lines
13 KiB
Bash
Executable File

#!/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 -ffp-contract=off -fno-fast-math -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 -ffp-contract=off -fno-fast-math -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 -ffp-contract=off -fno-fast-math -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/src/matvec.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 test --offline --locked --manifest-path "${repo_root}/Cargo.toml" -p leleka-cuda-driver \
--features cuda-driver --lib
cargo clippy --offline --locked --manifest-path "${repo_root}/Cargo.toml" -p leleka-cuda-driver --all-targets --all-features -- -D warnings
MOCK_CUDA_ADD_PTX="${repo_root}/crates/cuda-driver/src/vector_add.ptx" \
MOCK_CUDA_MATVEC_PTX="${repo_root}/crates/cuda-driver/src/matvec.ptx" \
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
mkdir -p "$work/q5"
cc -std=c11 -Wall -Wextra -Werror -Wno-misleading-indentation -ffp-contract=off -fno-fast-math -shared -fPIC \
"${repo_root}/crates/cuda-driver/tests/q5_mock_cuda.c" -lm -o "$work/q5/libcuda.so.1"
MOCK_CUDA_Q5_PTX="${repo_root}/crates/cuda-driver/src/q5_k_q8_1.ptx" \
LELEKA_CUDA_MOCK_HARNESS=1 LELEKA_CUDA_Q5_MOCK_ROOT="$work" \
cargo test --offline --locked --manifest-path "${repo_root}/Cargo.toml" -p leleka-cuda-driver \
--features cuda-driver --test q5_mock -- --exact isolated_q5_protocol_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'
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.matvec_f32(&buffer,&buffer,&mut buffer,1,1).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 'matvec 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 'matvec output alias compile refusal: PASS'
cat > "$work/reject.rs" <<'RSQ5'
use leleka_cuda_driver::{Driver,Q5KProjectionShape};
fn main(){let d=Driver::load().unwrap();let c=d.device(0).unwrap().create_context(4096).unwrap();let mut w=c.allocate(176).unwrap();let x=c.allocate(1024).unwrap();c.q5_k_q8_1(&w,&x,&mut w,Q5KProjectionShape{rows:1,columns:256}).unwrap();}
RSQ5
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 'Q5 output alias escaped' >&2; exit 1; fi
grep -q 'cannot borrow.*w.*as mutable because it is also borrowed as immutable' "$work/reject.log"
echo 'Q5 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
if [[ "$failed" == 0 ]]; then echo 'CPU mock owned containers/image/files removed; shared base retained'; 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