STRA-8 add Linux changed-scope coverage gate
Linux / verify (pull_request) Failing after 1m15s
Linux / changed-scope-coverage (pull_request) Skipped
Linux / keyless-cuda (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
Linux / verify (pull_request) Failing after 1m15s
Linux / changed-scope-coverage (pull_request) Skipped
Linux / keyless-cuda (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
This commit is contained in:
@@ -15,6 +15,10 @@ on:
|
||||
description: Build actual CUDA package on isolated hosted CPU (no GPU, private artifact)
|
||||
type: boolean
|
||||
default: false
|
||||
changed_scope_coverage:
|
||||
description: Run exact changed-production Rust line, function and branch coverage on Linux CPU
|
||||
type: boolean
|
||||
default: false
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
@@ -37,6 +41,44 @@ jobs:
|
||||
- name: Local checks
|
||||
run: scripts/check-local.sh
|
||||
|
||||
changed-scope-coverage:
|
||||
if: github.event_name == 'workflow_dispatch' && inputs.changed_scope_coverage
|
||||
needs: verify
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 120
|
||||
permissions:
|
||||
contents: read
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 0
|
||||
- name: Install parser runtime
|
||||
run: apt-get update && apt-get install -y ca-certificates curl python3
|
||||
- name: Install pinned Rust nightly with LLVM coverage tools
|
||||
run: |
|
||||
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y --profile minimal --default-toolchain none
|
||||
echo "$HOME/.cargo/bin" >> "$GITHUB_PATH"
|
||||
export PATH="$HOME/.cargo/bin:$PATH"
|
||||
rustup toolchain install nightly-2026-10-05 --profile minimal --component llvm-tools-preview
|
||||
- name: Test coverage parser and workflow contract
|
||||
run: python3 scripts/test-changed-scope-coverage.py
|
||||
- name: Run exact changed-production coverage gate
|
||||
run: python3 scripts/check-changed-scope-coverage.py --root "$GITHUB_WORKSPACE" --output-dir "$RUNNER_TEMP/changed-scope-coverage"
|
||||
- name: Archive raw LCOV and machine-readable summary
|
||||
if: always()
|
||||
uses: actions/upload-artifact@v4.4.3
|
||||
with:
|
||||
name: changed-scope-coverage-${{ github.run_id }}-${{ github.run_attempt }}
|
||||
path: |
|
||||
${{ runner.temp }}/changed-scope-coverage/coverage.raw.lcov
|
||||
${{ runner.temp }}/changed-scope-coverage/summary.json
|
||||
${{ runner.temp }}/changed-scope-coverage/summary.txt
|
||||
${{ runner.temp }}/changed-scope-coverage/cargo.stderr
|
||||
${{ runner.temp }}/changed-scope-coverage/llvm-cov.stderr
|
||||
${{ runner.temp }}/changed-scope-coverage/llvm-profdata.stderr
|
||||
if-no-files-found: warn
|
||||
retention-days: 14
|
||||
|
||||
keyless-cuda:
|
||||
if: github.event_name == 'workflow_dispatch' && github.event.inputs.keyless_gpu == 'true'
|
||||
needs: verify
|
||||
|
||||
+1667
-212
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
+3871
-724
File diff suppressed because it is too large
Load Diff
@@ -139,7 +139,7 @@ impl StreamedEnsureRequest<'_> {
|
||||
}
|
||||
|
||||
fn reuse_existing(&self, metadata: fs::Metadata) -> Result<PreviewOutcome, Box<dyn Error>> {
|
||||
if !metadata.is_file() || metadata.file_type().is_symlink() {
|
||||
if metadata.file_type().is_symlink() || !metadata.is_file() {
|
||||
return Err("existing KAR path must be a regular file".into());
|
||||
}
|
||||
let summary = if prepare_preview::has_pending_streamed_publication(self.archive)? {
|
||||
@@ -266,8 +266,93 @@ fn preflight_existing_shards(
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use sha2::{Digest, Sha256};
|
||||
use std::time::{SystemTime, UNIX_EPOCH};
|
||||
|
||||
fn gguf_string(bytes: &mut Vec<u8>, value: &str) {
|
||||
bytes.extend_from_slice(&(value.len() as u64).to_le_bytes());
|
||||
bytes.extend_from_slice(value.as_bytes());
|
||||
}
|
||||
|
||||
fn f32_shard(name: &str, values: &[f32]) -> Vec<u8> {
|
||||
let mut bytes = b"GGUF".to_vec();
|
||||
bytes.extend_from_slice(&3u32.to_le_bytes());
|
||||
bytes.extend_from_slice(&1u64.to_le_bytes());
|
||||
bytes.extend_from_slice(&1u64.to_le_bytes());
|
||||
gguf_string(&mut bytes, "general.architecture");
|
||||
bytes.extend_from_slice(&8u32.to_le_bytes());
|
||||
gguf_string(&mut bytes, "qwen35");
|
||||
gguf_string(&mut bytes, name);
|
||||
bytes.extend_from_slice(&1u32.to_le_bytes());
|
||||
bytes.extend_from_slice(&(values.len() as u64).to_le_bytes());
|
||||
bytes.extend_from_slice(&0u32.to_le_bytes());
|
||||
bytes.extend_from_slice(&0u64.to_le_bytes());
|
||||
bytes.resize(bytes.len().div_ceil(32) * 32, 0);
|
||||
bytes.extend(values.iter().flat_map(|value| value.to_le_bytes()));
|
||||
bytes
|
||||
}
|
||||
|
||||
fn iq3_shard() -> Vec<u8> {
|
||||
let mut payload = vec![0u8; crate::iq3_s::BLOCK_BYTES];
|
||||
payload[..2].copy_from_slice(&0x3c00u16.to_le_bytes());
|
||||
let mut bytes = b"GGUF".to_vec();
|
||||
bytes.extend_from_slice(&3u32.to_le_bytes());
|
||||
bytes.extend_from_slice(&1u64.to_le_bytes());
|
||||
bytes.extend_from_slice(&0u64.to_le_bytes());
|
||||
gguf_string(&mut bytes, "expert");
|
||||
bytes.extend_from_slice(&1u32.to_le_bytes());
|
||||
bytes.extend_from_slice(&256u64.to_le_bytes());
|
||||
bytes.extend_from_slice(&21u32.to_le_bytes());
|
||||
bytes.extend_from_slice(&0u64.to_le_bytes());
|
||||
bytes.resize(bytes.len().div_ceil(32) * 32, 0);
|
||||
bytes.extend(payload);
|
||||
bytes
|
||||
}
|
||||
|
||||
fn temporary_directory(label: &str) -> std::path::PathBuf {
|
||||
let stamp = SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.unwrap()
|
||||
.as_nanos();
|
||||
std::env::temp_dir().join(format!("strata-{label}-{}-{stamp}", std::process::id()))
|
||||
}
|
||||
|
||||
fn local_manifest(directory: &Path) -> model::Manifest {
|
||||
let payload = (0..64)
|
||||
.map(|number| [-1.0, -0.25, 0.25, 1.0][number % 4])
|
||||
.collect::<Vec<_>>();
|
||||
let shard = f32_shard("dense", &payload);
|
||||
fs::write(directory.join("tiny.gguf"), &shard).unwrap();
|
||||
let iq3 = iq3_shard();
|
||||
fs::write(directory.join("expert.gguf"), &iq3).unwrap();
|
||||
model::Manifest {
|
||||
schema_version: 1,
|
||||
files: [("tiny.gguf", shard), ("expert.gguf", iq3)]
|
||||
.into_iter()
|
||||
.map(|(name, bytes)| model::ModelFile {
|
||||
name: name.into(),
|
||||
url: format!("https://example.invalid/{name}"),
|
||||
size: bytes.len() as u64,
|
||||
sha256: hex::encode(Sha256::digest(bytes)),
|
||||
})
|
||||
.collect(),
|
||||
}
|
||||
}
|
||||
|
||||
fn ple_manifest(directory: &Path) -> model::Manifest {
|
||||
let mut manifest = local_manifest(directory);
|
||||
let values = (0..512).map(|value| value as f32).collect::<Vec<_>>();
|
||||
let bytes = f32_shard(stream_parts::PLE_TENSOR_NAME, &values);
|
||||
fs::write(directory.join("ple.gguf"), &bytes).unwrap();
|
||||
manifest.files.push(model::ModelFile {
|
||||
name: "ple.gguf".into(),
|
||||
url: "https://example.invalid/ple.gguf".into(),
|
||||
size: bytes.len() as u64,
|
||||
sha256: hex::encode(Sha256::digest(bytes)),
|
||||
});
|
||||
manifest
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn full_model_is_rejected_before_creating_a_download_directory() {
|
||||
let manifest = model::Manifest::from_spec("qwen-iq3-s").await.unwrap();
|
||||
@@ -289,4 +374,193 @@ mod tests {
|
||||
assert!(error.contains("at most 64 MiB"));
|
||||
assert!(!source_dir.exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn streamed_create_and_reuse_verify_local_archive() {
|
||||
let directory = temporary_directory("pipeline");
|
||||
fs::create_dir(&directory).unwrap();
|
||||
let manifest = local_manifest(&directory);
|
||||
let archive = directory.join("tiny.kar");
|
||||
let request = StreamedEnsureRequest {
|
||||
manifest: &manifest,
|
||||
source_dir: &directory,
|
||||
archive: &archive,
|
||||
levels: 2,
|
||||
ple_part_elements: None,
|
||||
};
|
||||
let created = request.create_archive().unwrap();
|
||||
assert!(matches!(created, PreviewOutcome::Created(_)));
|
||||
let metadata = fs::metadata(&archive).unwrap();
|
||||
let reused = request.reuse_existing(metadata).unwrap();
|
||||
assert!(matches!(reused, PreviewOutcome::Reused(_)));
|
||||
verify_streamed_archive(&manifest, &directory, &archive, 2, None).unwrap();
|
||||
fs::remove_dir_all(directory).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn streamed_ple_create_verify_and_reuse_keep_the_partition_policy() {
|
||||
let directory = temporary_directory("pipeline-ple");
|
||||
fs::create_dir(&directory).unwrap();
|
||||
let manifest = ple_manifest(&directory);
|
||||
let archive = directory.join("ple.kar");
|
||||
let request = StreamedEnsureRequest {
|
||||
manifest: &manifest,
|
||||
source_dir: &directory,
|
||||
archive: &archive,
|
||||
levels: 2,
|
||||
ple_part_elements: Some(128),
|
||||
};
|
||||
let created = request.create_archive().unwrap();
|
||||
assert!(matches!(created, PreviewOutcome::Created(_)));
|
||||
assert!(verify_streamed_archive(&manifest, &directory, &archive, 2, Some(128)).is_ok());
|
||||
assert!(matches!(
|
||||
request.reuse_existing(fs::metadata(&archive).unwrap()),
|
||||
Ok(PreviewOutcome::Reused(_))
|
||||
));
|
||||
fs::remove_dir_all(directory).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn preflight_defers_existing_missing_and_resumable_shards() {
|
||||
let directory = temporary_directory("preflight-incomplete");
|
||||
fs::create_dir(&directory).unwrap();
|
||||
let manifest = local_manifest(&directory);
|
||||
let archive = directory.join("model.kar");
|
||||
assert!(preflight_existing_shards(&manifest, &directory, &archive, 2).is_ok());
|
||||
fs::write(&archive, b"existing").unwrap();
|
||||
assert!(preflight_existing_shards(&manifest, &directory, &archive, 2).is_ok());
|
||||
fs::remove_file(&archive).unwrap();
|
||||
fs::remove_file(directory.join("tiny.gguf")).unwrap();
|
||||
assert!(preflight_existing_shards(&manifest, &directory, &archive, 2).is_ok());
|
||||
fs::write(directory.join("tiny.gguf"), b"short").unwrap();
|
||||
assert!(preflight_existing_shards(&manifest, &directory, &archive, 2).is_ok());
|
||||
fs::remove_dir_all(directory).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn preflight_rejects_unsafe_names_and_non_regular_shards() {
|
||||
let directory = temporary_directory("preflight-invalid");
|
||||
fs::create_dir(&directory).unwrap();
|
||||
let mut manifest = local_manifest(&directory);
|
||||
manifest.files.truncate(1);
|
||||
manifest.files[0].name = "../escape.gguf".into();
|
||||
assert!(preflight_existing_shards(&manifest, &directory, Path::new("out"), 2).is_err());
|
||||
manifest.files[0].name = "directory.gguf".into();
|
||||
fs::create_dir(directory.join("directory.gguf")).unwrap();
|
||||
assert!(preflight_existing_shards(&manifest, &directory, Path::new("out"), 2).is_err());
|
||||
fs::remove_dir_all(directory).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn streamed_request_validation_and_archive_path_fail_closed() {
|
||||
let manifest = model::Manifest {
|
||||
schema_version: 1,
|
||||
files: Vec::new(),
|
||||
};
|
||||
let source_dir = Path::new(".");
|
||||
let archive = Path::new("bad\0archive.kar");
|
||||
let invalid = StreamedEnsureRequest {
|
||||
manifest: &manifest,
|
||||
source_dir,
|
||||
archive,
|
||||
levels: 0,
|
||||
ple_part_elements: None,
|
||||
};
|
||||
assert!(invalid.validate().is_err());
|
||||
let invalid_limit = StreamedEnsureRequest {
|
||||
levels: 2,
|
||||
ple_part_elements: Some(31),
|
||||
..invalid
|
||||
};
|
||||
assert!(invalid_limit.validate().is_err());
|
||||
assert!(invalid_limit.resolve_archive().is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn existing_non_regular_archive_is_rejected() {
|
||||
let dir = temporary_directory("non-regular");
|
||||
fs::create_dir(&dir).unwrap();
|
||||
let manifest = model::Manifest {
|
||||
schema_version: 1,
|
||||
files: Vec::new(),
|
||||
};
|
||||
let request = StreamedEnsureRequest {
|
||||
manifest: &manifest,
|
||||
source_dir: &dir,
|
||||
archive: &dir,
|
||||
levels: 2,
|
||||
ple_part_elements: None,
|
||||
};
|
||||
assert!(request.reuse_existing(fs::metadata(&dir).unwrap()).is_err());
|
||||
assert!(
|
||||
StreamedEnsureRequest {
|
||||
manifest: &manifest,
|
||||
source_dir: &dir,
|
||||
archive: &dir,
|
||||
levels: 2,
|
||||
ple_part_elements: None,
|
||||
}
|
||||
.resolve_archive()
|
||||
.is_err()
|
||||
);
|
||||
fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn streamed_archive_resolution_handles_missing_and_symlink_paths() {
|
||||
let dir = temporary_directory("archive-resolution");
|
||||
fs::create_dir(&dir).unwrap();
|
||||
let manifest = model::Manifest {
|
||||
schema_version: 1,
|
||||
files: Vec::new(),
|
||||
};
|
||||
let archive = dir.join("missing.kar");
|
||||
assert_missing_archive_rejected(&manifest, &dir, &archive);
|
||||
let target = dir.join("target");
|
||||
fs::write(&target, b"regular target").unwrap();
|
||||
let link = dir.join("link.kar");
|
||||
std::os::unix::fs::symlink(&target, &link).unwrap();
|
||||
assert_symlink_archive_rejected(&manifest, &dir, &link);
|
||||
fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
fn assert_missing_archive_rejected(
|
||||
manifest: &model::Manifest,
|
||||
source_dir: &Path,
|
||||
archive: &Path,
|
||||
) {
|
||||
let request = ensure_request(manifest, source_dir, archive);
|
||||
assert!(request.resolve_archive().is_err());
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
fn assert_symlink_archive_rejected(
|
||||
manifest: &model::Manifest,
|
||||
source_dir: &Path,
|
||||
archive: &Path,
|
||||
) {
|
||||
let request = ensure_request(manifest, source_dir, archive);
|
||||
assert!(
|
||||
request
|
||||
.reuse_existing(fs::symlink_metadata(archive).unwrap())
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
fn ensure_request<'a>(
|
||||
manifest: &'a model::Manifest,
|
||||
source_dir: &'a Path,
|
||||
archive: &'a Path,
|
||||
) -> StreamedEnsureRequest<'a> {
|
||||
StreamedEnsureRequest {
|
||||
manifest,
|
||||
source_dir,
|
||||
archive,
|
||||
levels: 2,
|
||||
ple_part_elements: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+3583
-896
File diff suppressed because it is too large
Load Diff
@@ -226,6 +226,11 @@ struct ParentHashes {
|
||||
f32: Sha256,
|
||||
}
|
||||
|
||||
struct LayoutHashAccumulator<'a> {
|
||||
part: ParentHashes,
|
||||
parent: &'a mut ParentHashes,
|
||||
}
|
||||
|
||||
struct PartBuildContext<'a> {
|
||||
index: &'a gguf::TensorIndex,
|
||||
tensor: &'a gguf::TensorInfo,
|
||||
@@ -264,12 +269,20 @@ impl<'a> ShardPlanner<'a> {
|
||||
}
|
||||
|
||||
fn plan_shard(&mut self, shard: &derived_mixed::ShardIdentity) -> Result<(), String> {
|
||||
self.plan_shard_with_open(shard, |path| File::open(path))
|
||||
}
|
||||
|
||||
fn plan_shard_with_open(
|
||||
&mut self,
|
||||
shard: &derived_mixed::ShardIdentity,
|
||||
open: fn(&Path) -> std::io::Result<File>,
|
||||
) -> Result<(), String> {
|
||||
let path = self.source_dir.join(&shard.name);
|
||||
let index = gguf::tensor_index(&path).map_err(|error| error.to_string())?;
|
||||
if index.tensors.len() != shard.tensor_count {
|
||||
return Err("GGUF shard changed during KAR part planning".into());
|
||||
}
|
||||
let mut source = File::open(path).map_err(|error| error.to_string())?;
|
||||
let mut source = open(&path).map_err(|error| error.to_string())?;
|
||||
for tensor in &index.tensors {
|
||||
self.plan_tensor(&index, &mut source, tensor)?;
|
||||
}
|
||||
@@ -361,30 +374,8 @@ impl<'a> ShardPlanner<'a> {
|
||||
hashes: &mut ParentHashes,
|
||||
) -> Result<PartIdentity, String> {
|
||||
let tensor = context.tensor;
|
||||
let (source_sha256, f32_sha256) = if context.split {
|
||||
hash_layout(
|
||||
source,
|
||||
context.index.summary.data_start,
|
||||
tensor,
|
||||
layout,
|
||||
hashes,
|
||||
)?
|
||||
} else {
|
||||
(context.original.source_sha256, context.original.f32_sha256)
|
||||
};
|
||||
Ok(PartIdentity {
|
||||
name: layout.name.clone(),
|
||||
parent_name: tensor.name.clone(),
|
||||
parent_dimensions: tensor.dimensions.clone(),
|
||||
dimensions: layout.dimensions.clone(),
|
||||
source_kind: tensor.kind,
|
||||
source_byte_offset: layout.source_byte_offset,
|
||||
source_bytes: layout.source_bytes,
|
||||
source_sha256,
|
||||
derived_offset: layout.derived_offset,
|
||||
derived_bytes: layout.derived_bytes,
|
||||
f32_sha256,
|
||||
})
|
||||
let hashes = part_hashes(source, layout, context, hashes)?;
|
||||
Ok(part_identity(tensor, layout, hashes))
|
||||
}
|
||||
|
||||
fn verify_parent_hashes(
|
||||
@@ -418,6 +409,45 @@ impl<'a> ShardPlanner<'a> {
|
||||
}
|
||||
}
|
||||
|
||||
fn part_hashes(
|
||||
source: &mut File,
|
||||
layout: &Layout,
|
||||
context: &PartBuildContext<'_>,
|
||||
parent: &mut ParentHashes,
|
||||
) -> Result<([u8; 32], [u8; 32]), String> {
|
||||
if context.split {
|
||||
hash_layout(
|
||||
source,
|
||||
context.index.summary.data_start,
|
||||
context.tensor,
|
||||
layout,
|
||||
parent,
|
||||
)
|
||||
} else {
|
||||
Ok((context.original.source_sha256, context.original.f32_sha256))
|
||||
}
|
||||
}
|
||||
|
||||
fn part_identity(
|
||||
tensor: &gguf::TensorInfo,
|
||||
layout: &Layout,
|
||||
hashes: ([u8; 32], [u8; 32]),
|
||||
) -> PartIdentity {
|
||||
PartIdentity {
|
||||
name: layout.name.clone(),
|
||||
parent_name: tensor.name.clone(),
|
||||
parent_dimensions: tensor.dimensions.clone(),
|
||||
dimensions: layout.dimensions.clone(),
|
||||
source_kind: tensor.kind,
|
||||
source_byte_offset: layout.source_byte_offset,
|
||||
source_bytes: layout.source_bytes,
|
||||
source_sha256: hashes.0,
|
||||
derived_offset: layout.derived_offset,
|
||||
derived_bytes: layout.derived_bytes,
|
||||
f32_sha256: hashes.1,
|
||||
}
|
||||
}
|
||||
|
||||
fn hash_layout(
|
||||
source: &mut File,
|
||||
data_start: u64,
|
||||
@@ -425,39 +455,439 @@ fn hash_layout(
|
||||
layout: &Layout,
|
||||
parent: &mut ParentHashes,
|
||||
) -> Result<([u8; 32], [u8; 32]), String> {
|
||||
let absolute = data_start
|
||||
.checked_add(tensor.offset)
|
||||
.and_then(|offset| offset.checked_add(layout.source_byte_offset))
|
||||
.ok_or("GGUF part offset overflow")?;
|
||||
let mut hashes = ParentHashes {
|
||||
source: Sha256::new(),
|
||||
f32: Sha256::new(),
|
||||
};
|
||||
let absolute = layout_absolute(data_start, tensor.offset, layout.source_byte_offset)?;
|
||||
let mut hashes = LayoutHashAccumulator::new(parent);
|
||||
let count = gguf_f32_stream::visit(
|
||||
source,
|
||||
absolute,
|
||||
tensor.kind,
|
||||
layout.source_bytes,
|
||||
|raw, f32_bytes| {
|
||||
hashes.source.update(raw);
|
||||
hashes.f32.update(f32_bytes);
|
||||
parent.source.update(raw);
|
||||
parent.f32.update(f32_bytes);
|
||||
Ok(())
|
||||
},
|
||||
|raw, f32_bytes| hashes.update(raw, f32_bytes),
|
||||
)?;
|
||||
if count != layout.derived_bytes {
|
||||
return Err("GGUF part derived byte count mismatch".into());
|
||||
}
|
||||
Ok((
|
||||
hashes.source.finalize().into(),
|
||||
hashes.f32.finalize().into(),
|
||||
))
|
||||
Ok(hashes.finish())
|
||||
}
|
||||
|
||||
fn layout_absolute(data_start: u64, tensor_offset: u64, part_offset: u64) -> Result<u64, String> {
|
||||
data_start
|
||||
.checked_add(tensor_offset)
|
||||
.and_then(|offset| offset.checked_add(part_offset))
|
||||
.ok_or_else(|| "GGUF part offset overflow".into())
|
||||
}
|
||||
|
||||
impl LayoutHashAccumulator<'_> {
|
||||
fn new(parent: &mut ParentHashes) -> LayoutHashAccumulator<'_> {
|
||||
LayoutHashAccumulator {
|
||||
part: ParentHashes {
|
||||
source: Sha256::new(),
|
||||
f32: Sha256::new(),
|
||||
},
|
||||
parent,
|
||||
}
|
||||
}
|
||||
|
||||
fn update(&mut self, source: &[u8], f32: &[u8]) -> Result<(), String> {
|
||||
self.part.source.update(source);
|
||||
self.part.f32.update(f32);
|
||||
self.parent.source.update(source);
|
||||
self.parent.f32.update(f32);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn finish(self) -> ([u8; 32], [u8; 32]) {
|
||||
(
|
||||
self.part.source.finalize().into(),
|
||||
self.part.f32.finalize().into(),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::path::PathBuf;
|
||||
use std::time::{SystemTime, UNIX_EPOCH};
|
||||
|
||||
fn gguf_f32(name: &str) -> Vec<u8> {
|
||||
let mut bytes = b"GGUF".to_vec();
|
||||
bytes.extend_from_slice(&3u32.to_le_bytes());
|
||||
bytes.extend_from_slice(&1u64.to_le_bytes());
|
||||
bytes.extend_from_slice(&0u64.to_le_bytes());
|
||||
bytes.extend_from_slice(&(name.len() as u64).to_le_bytes());
|
||||
bytes.extend_from_slice(name.as_bytes());
|
||||
bytes.extend_from_slice(&1u32.to_le_bytes());
|
||||
bytes.extend_from_slice(&32u64.to_le_bytes());
|
||||
bytes.extend_from_slice(&0u32.to_le_bytes());
|
||||
bytes.extend_from_slice(&0u64.to_le_bytes());
|
||||
bytes.resize(bytes.len().div_ceil(32) * 32, 0);
|
||||
bytes.extend((0..32u32).flat_map(|value| (value as f32).to_le_bytes()));
|
||||
bytes
|
||||
}
|
||||
|
||||
fn identity_fixture(
|
||||
directory: &Path,
|
||||
names: &[(&str, &str)],
|
||||
) -> derived_mixed::ShardedIdentity {
|
||||
let entries = names
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(index, (file, tensor))| identity_fixture_entry(directory, index, file, tensor))
|
||||
.collect::<Vec<_>>();
|
||||
let (shards, tensors): (Vec<_>, Vec<_>) = entries.into_iter().unzip();
|
||||
derived_mixed::ShardedIdentity {
|
||||
derived_sha256: [0; 32],
|
||||
derived_bytes: tensors.len() as u64 * 128,
|
||||
shards,
|
||||
tensors,
|
||||
}
|
||||
}
|
||||
|
||||
fn identity_fixture_entry(
|
||||
directory: &Path,
|
||||
index: usize,
|
||||
file_name: &str,
|
||||
tensor_name: &str,
|
||||
) -> (derived_mixed::ShardIdentity, derived_mixed::TensorIdentity) {
|
||||
let bytes = gguf_f32(tensor_name);
|
||||
std::fs::write(directory.join(file_name), &bytes).unwrap();
|
||||
let digest = Sha256::digest(&bytes).into();
|
||||
let f32_bytes = (0..32u32)
|
||||
.flat_map(|value| (value as f32).to_le_bytes())
|
||||
.collect::<Vec<_>>();
|
||||
let f32_digest = Sha256::digest(f32_bytes).into();
|
||||
let shard = derived_mixed::ShardIdentity {
|
||||
name: file_name.into(),
|
||||
gguf_sha256: digest,
|
||||
gguf_bytes: bytes.len() as u64,
|
||||
tensor_count: 1,
|
||||
};
|
||||
let tensor = derived_mixed::TensorIdentity {
|
||||
name: tensor_name.into(),
|
||||
source_kind: 0,
|
||||
source_sha256: f32_digest,
|
||||
derived_offset: index as u64 * 128,
|
||||
derived_bytes: 128,
|
||||
f32_sha256: f32_digest,
|
||||
};
|
||||
(shard, tensor)
|
||||
}
|
||||
|
||||
fn plan_test_dir(label: &str) -> PathBuf {
|
||||
let path = std::env::temp_dir().join(format!(
|
||||
"strata-{label}-{}-{}",
|
||||
std::process::id(),
|
||||
SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.unwrap()
|
||||
.as_nanos()
|
||||
));
|
||||
std::fs::create_dir(&path).unwrap();
|
||||
path
|
||||
}
|
||||
|
||||
fn layout_hash_test_file() -> PathBuf {
|
||||
let path = std::env::temp_dir().join(format!(
|
||||
"strata-layout-hash-{}-{}.gguf",
|
||||
std::process::id(),
|
||||
SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.unwrap()
|
||||
.as_nanos()
|
||||
));
|
||||
std::fs::write(&path, 1.0f32.to_le_bytes()).unwrap();
|
||||
path
|
||||
}
|
||||
|
||||
fn layout_hash_fixture(
|
||||
derived_bytes: u64,
|
||||
) -> (PathBuf, File, gguf::TensorInfo, Layout, ParentHashes) {
|
||||
let path = layout_hash_test_file();
|
||||
let source = File::open(&path).unwrap();
|
||||
let tensor = gguf::TensorInfo {
|
||||
name: "tensor".into(),
|
||||
dimensions: vec![1],
|
||||
kind: 0,
|
||||
offset: 0,
|
||||
bytes: 4,
|
||||
};
|
||||
let layout = Layout {
|
||||
name: "tensor".into(),
|
||||
dimensions: vec![1],
|
||||
source_byte_offset: 0,
|
||||
source_bytes: 4,
|
||||
derived_offset: 0,
|
||||
derived_bytes,
|
||||
};
|
||||
let parent = ParentHashes {
|
||||
source: Sha256::new(),
|
||||
f32: Sha256::new(),
|
||||
};
|
||||
(path, source, tensor, layout, parent)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn layout_absolute_checks_both_offset_additions() {
|
||||
assert_eq!(layout_absolute(10, 20, 30), Ok(60));
|
||||
assert_eq!(
|
||||
layout_absolute(u64::MAX, 1, 0),
|
||||
Err("GGUF part offset overflow".into())
|
||||
);
|
||||
assert_eq!(
|
||||
layout_absolute(0, u64::MAX, 1),
|
||||
Err("GGUF part offset overflow".into())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shard_planner_preserves_manifest_tensor_order_and_rejects_missing_source() {
|
||||
let directory = std::env::temp_dir().join(format!(
|
||||
"strata-plan-parts-{}-{}",
|
||||
std::process::id(),
|
||||
SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.unwrap()
|
||||
.as_nanos()
|
||||
));
|
||||
std::fs::create_dir(&directory).unwrap();
|
||||
let identity = identity_fixture(&directory, &[("a.gguf", "weight")]);
|
||||
let parts = plan_shards_with_limit(&identity, &directory, 32).unwrap();
|
||||
assert_eq!(parts[0][0].name, "weight");
|
||||
std::fs::remove_file(directory.join("a.gguf")).unwrap();
|
||||
assert!(plan_shards_with_limit(&identity, &directory, 32).is_err());
|
||||
std::fs::remove_dir_all(directory).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shard_planner_rejects_missing_ple_and_duplicate_part_names() {
|
||||
let directory = plan_test_dir("plan-invalid");
|
||||
assert_missing_ple_is_rejected(&directory);
|
||||
assert_duplicate_names_are_rejected(&directory);
|
||||
assert_unsplit_ple_is_rejected(&directory);
|
||||
std::fs::remove_dir_all(directory).unwrap();
|
||||
}
|
||||
|
||||
fn assert_missing_ple_is_rejected(directory: &Path) {
|
||||
let identity = identity_fixture(directory, &[("a.gguf", "weight")]);
|
||||
let limits = PlanLimits {
|
||||
max_part_elements: 32,
|
||||
ple_part_elements: Some(32),
|
||||
};
|
||||
assert!(
|
||||
matches!(plan_shards_with_limits(&identity, directory, limits), Err(error) if error.contains("requires per_layer_token_embd.weight"))
|
||||
);
|
||||
}
|
||||
|
||||
fn assert_duplicate_names_are_rejected(directory: &Path) {
|
||||
let identity = identity_fixture(directory, &[("b.gguf", "weight"), ("c.gguf", "weight")]);
|
||||
let error = plan_shards_with_limit(&identity, directory, 32).unwrap_err();
|
||||
assert!(error.contains("duplicate KAR part name"));
|
||||
}
|
||||
|
||||
fn assert_unsplit_ple_is_rejected(directory: &Path) {
|
||||
let identity = identity_fixture(directory, &[("ple.gguf", PLE_TENSOR_NAME)]);
|
||||
let limits = PlanLimits {
|
||||
max_part_elements: 32,
|
||||
ple_part_elements: Some(32),
|
||||
};
|
||||
let error = plan_shards_with_limits(&identity, directory, limits).unwrap_err();
|
||||
assert!(error.contains("must split the PLE tensor"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shard_planner_checks_virtual_tensor_count_and_identity() {
|
||||
let directory = plan_test_dir("plan-count");
|
||||
let mut identity = identity_fixture(&directory, &[("a.gguf", "weight")]);
|
||||
identity.shards.clear();
|
||||
let error = plan_shards_with_limit(&identity, &directory, 32).unwrap_err();
|
||||
assert!(error.contains("tensor count differs"));
|
||||
assert_virtual_source_mismatch_rejected(&directory);
|
||||
std::fs::remove_dir_all(directory).unwrap();
|
||||
}
|
||||
|
||||
fn assert_virtual_source_mismatch_rejected(directory: &Path) {
|
||||
let bytes = gguf_f32("other");
|
||||
let identity = derived_mixed::ShardedIdentity {
|
||||
derived_sha256: [0; 32],
|
||||
derived_bytes: 128,
|
||||
shards: vec![derived_mixed::ShardIdentity {
|
||||
name: "a.gguf".into(),
|
||||
gguf_sha256: Sha256::digest(&bytes).into(),
|
||||
gguf_bytes: bytes.len() as u64,
|
||||
tensor_count: 1,
|
||||
}],
|
||||
tensors: identity_fixture(directory, &[("a.gguf", "weight")]).tensors,
|
||||
};
|
||||
std::fs::write(directory.join("a.gguf"), &bytes).unwrap();
|
||||
let error = plan_shards_with_limit(&identity, directory, 32).unwrap_err();
|
||||
assert!(error.contains("differs from virtual source"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shard_planner_rejects_changed_tensor_count_and_kind() {
|
||||
let directory = std::env::temp_dir().join(format!(
|
||||
"strata-plan-changed-tensor-{}-{}",
|
||||
std::process::id(),
|
||||
SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.unwrap()
|
||||
.as_nanos()
|
||||
));
|
||||
std::fs::create_dir(&directory).unwrap();
|
||||
let mut identity = identity_fixture(&directory, &[("a.gguf", "weight")]);
|
||||
identity.shards[0].tensor_count += 1;
|
||||
assert!(plan_shards_with_limit(&identity, &directory, 32).is_err());
|
||||
identity.shards[0].tensor_count -= 1;
|
||||
identity.tensors[0].source_kind = 1;
|
||||
assert!(plan_shards_with_limit(&identity, &directory, 32).is_err());
|
||||
std::fs::remove_dir_all(directory).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shard_open_failure_is_returned_after_index_validation() {
|
||||
let directory = std::env::temp_dir().join(format!(
|
||||
"strata-plan-open-failure-{}-{}",
|
||||
std::process::id(),
|
||||
SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.unwrap()
|
||||
.as_nanos()
|
||||
));
|
||||
std::fs::create_dir(&directory).unwrap();
|
||||
let identity = identity_fixture(&directory, &[("a.gguf", "weight")]);
|
||||
let mut planner = ShardPlanner::new(
|
||||
&identity,
|
||||
&directory,
|
||||
PlanLimits {
|
||||
max_part_elements: 32,
|
||||
ple_part_elements: None,
|
||||
},
|
||||
);
|
||||
let error = planner.plan_shard_with_open(&identity.shards[0], |_| {
|
||||
Err(std::io::Error::from(std::io::ErrorKind::PermissionDenied))
|
||||
});
|
||||
assert_eq!(
|
||||
error.unwrap_err(),
|
||||
std::io::Error::from(std::io::ErrorKind::PermissionDenied).to_string()
|
||||
);
|
||||
std::fs::remove_dir_all(directory).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn split_parent_hashes_must_match_both_source_digests() {
|
||||
let directory = std::env::temp_dir();
|
||||
let identity = identity_fixture(&directory, &[]);
|
||||
let planner = ShardPlanner::new(
|
||||
&identity,
|
||||
&directory,
|
||||
PlanLimits {
|
||||
max_part_elements: 32,
|
||||
ple_part_elements: None,
|
||||
},
|
||||
);
|
||||
let tensor = parent_hash_test_tensor();
|
||||
let original = parent_hash_test_identity();
|
||||
assert!(
|
||||
planner
|
||||
.verify_parent_hashes(&tensor, &original, true, matching_parent_hashes())
|
||||
.is_ok()
|
||||
);
|
||||
assert_source_hash_mismatch_rejected(&planner, &tensor);
|
||||
assert_f32_hash_mismatch_rejected(&planner, &tensor);
|
||||
}
|
||||
|
||||
fn parent_hash_test_tensor() -> gguf::TensorInfo {
|
||||
gguf::TensorInfo {
|
||||
name: "weight".into(),
|
||||
dimensions: vec![1],
|
||||
kind: 0,
|
||||
offset: 0,
|
||||
bytes: 4,
|
||||
}
|
||||
}
|
||||
|
||||
fn parent_hash_test_identity() -> derived_mixed::TensorIdentity {
|
||||
derived_mixed::TensorIdentity {
|
||||
name: "weight".into(),
|
||||
source_kind: 0,
|
||||
source_sha256: Sha256::digest(b"source").into(),
|
||||
derived_offset: 0,
|
||||
derived_bytes: 4,
|
||||
f32_sha256: Sha256::digest(b"derived").into(),
|
||||
}
|
||||
}
|
||||
|
||||
fn matching_parent_hashes() -> ParentHashes {
|
||||
let mut hashes = ParentHashes {
|
||||
source: Sha256::new(),
|
||||
f32: Sha256::new(),
|
||||
};
|
||||
hashes.source.update(b"source");
|
||||
hashes.f32.update(b"derived");
|
||||
hashes
|
||||
}
|
||||
|
||||
fn assert_source_hash_mismatch_rejected(planner: &ShardPlanner<'_>, tensor: &gguf::TensorInfo) {
|
||||
let mut changed = parent_hash_test_identity();
|
||||
changed.source_sha256[0] ^= 1;
|
||||
assert!(
|
||||
planner
|
||||
.verify_parent_hashes(tensor, &changed, true, matching_parent_hashes())
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
|
||||
fn assert_f32_hash_mismatch_rejected(planner: &ShardPlanner<'_>, tensor: &gguf::TensorInfo) {
|
||||
let mut changed = parent_hash_test_identity();
|
||||
changed.f32_sha256[0] ^= 1;
|
||||
assert!(
|
||||
planner
|
||||
.verify_parent_hashes(tensor, &changed, true, matching_parent_hashes())
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hash_layout_streams_matching_source_and_derived_bytes() {
|
||||
let (path, mut source, tensor, layout, mut parent) = layout_hash_fixture(4);
|
||||
assert_matching_layout_hash(&mut source, &tensor, &layout, &mut parent);
|
||||
drop(source);
|
||||
std::fs::remove_file(path).unwrap();
|
||||
}
|
||||
|
||||
fn assert_matching_layout_hash(
|
||||
source: &mut File,
|
||||
tensor: &gguf::TensorInfo,
|
||||
layout: &Layout,
|
||||
parent: &mut ParentHashes,
|
||||
) {
|
||||
let expected: [u8; 32] = Sha256::digest(1.0f32.to_le_bytes()).into();
|
||||
assert_eq!(
|
||||
hash_layout(source, 0, tensor, layout, parent).unwrap().0,
|
||||
expected
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hash_layout_rejects_derived_byte_count_mismatch() {
|
||||
let (path, mut source, tensor, layout, mut parent) = layout_hash_fixture(8);
|
||||
assert_eq!(
|
||||
hash_layout(&mut source, 0, &tensor, &layout, &mut parent).unwrap_err(),
|
||||
"GGUF part derived byte count mismatch"
|
||||
);
|
||||
drop(source);
|
||||
std::fs::remove_file(path).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hash_layout_propagates_truncated_source_reads() {
|
||||
let (path, mut source, tensor, layout, mut parent) = layout_hash_fixture(8);
|
||||
std::fs::write(&path, []).unwrap();
|
||||
assert!(hash_layout(&mut source, 0, &tensor, &layout, &mut parent).is_err());
|
||||
drop(source);
|
||||
std::fs::remove_file(path).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn giant_per_layer_tensor_becomes_two_contiguous_kar_parts() {
|
||||
|
||||
@@ -1,5 +1,12 @@
|
||||
# Build validation
|
||||
|
||||
## 2026-10-06 — KAR overlay publication recovery
|
||||
|
||||
- Overlay preparation records a source/policy-bound pending intent before archive publication, verifies the archive before atomically publishing its separate sidecar, reads the sidecar back, and removes the intent last. Retry tests cover interruption before archive creation and after archive, sidecar, or intent publication; unrelated archive and sidecar bytes are preserved.
|
||||
- `cargo fmt --manifest-path control-plane/Cargo.toml --check`, all-target Clippy with warnings denied, `cargo test --manifest-path control-plane/Cargo.toml --locked` (198 Rust tests), and `scripts/check-local.sh`'s Python/Rust/replay stages passed. The script stops at the host CPU build because CMake is unavailable on this macOS host.
|
||||
- The CPU CMake/CTest stage passed separately inside GPU-hidden Docker using Ubuntu 24.04 arm64 digest `sha256:534baea6a22c03a63003dbc8dbe78fe34bc0d7e595d9a9dc9834884ff530eb55`, CMake 3.28.3, and GCC 13.3.0: five CTest tests passed. The container had no GPU device or NVIDIA runtime and was removed automatically.
|
||||
- Required §702.1 changed-scope 100% line/function/branch coverage remains **unverified**. The permitted branch-capable coverage attempt was SIGKILLed before it produced a valid machine-readable report; no partial percentage is treated as a pass. This validation does not establish installed-driver inference, model quality, or rollback.
|
||||
|
||||
## 2026-10-03 — experimental PLE quality arm
|
||||
|
||||
The imported engine builds on Linux CUDA 13.2/sm_120 with the optional
|
||||
|
||||
@@ -148,10 +148,20 @@ when that intent matches the current pinned shards and policy and a fresh
|
||||
independent archive verification succeeds; it then writes the sidecar with a
|
||||
no-replace link. An archive without a matching intent is never adopted, and an
|
||||
existing sidecar or archive is never overwritten. Temporary-link cleanup after
|
||||
a successful archive or provenance publication can fail without invalidating
|
||||
the atomically linked destination; any leftover `.part` file is not treated as
|
||||
an archive or sidecar. Recovery proves artifact integrity only, not lossy model
|
||||
quality or serving readiness.
|
||||
a successful archive publication is retried once and cannot invalidate the
|
||||
atomically linked destination; overlay preparation continues to provenance
|
||||
publication after that final link. KAR writer temporary names are scoped to the
|
||||
destination and one of eight fixed slots, created exclusively with mode `0600`,
|
||||
and held under an advisory lock while being written and verified. This bounds
|
||||
crash-left archive temp files per destination. A later write reaps only matching
|
||||
temporary files when it can acquire the lock and confirm current-user ownership
|
||||
and inode identity. Writers also verify that a newly locked slot still names
|
||||
their opened inode before using it, closing the race with reaping. An unlinked
|
||||
pre-publication crash partial is never confused with a final archive; a
|
||||
published hard-link temporary is removed only when it is the same inode as
|
||||
that destination. Recovery proves artifact integrity only, not lossy model
|
||||
quality or serving readiness. Unknown or legacy temporary names are preserved
|
||||
rather than guessed at or deleted.
|
||||
|
||||
`model ensure-sharded-streamed MANIFEST --source-dir DIR --output FILE.kar --levels 2 --ple-part-elements 100000000` selects an experimental v5 partition policy. Only `per_layer_token_embd.weight` gets the smaller limit; other tensors keep the v4 limit. The policy is encoded in the KAR builder string and provenance, and the matching verifier reconstructs every part from the pinned GGUF source. Reuse with another limit or the v4 command fails closed. For the target PLE dimensions, this limit plans 513 adjacent parts of at most 100 million elements, each aligned to complete GGUF rows and quantization blocks. This is a layout calculation, not a new measured archive size or GPU result. Overlay preparation and paired comparison now accept a single split PLE part in a v5 base; a synthetic fixture covers this path, while no full v5 model overlay has been produced. The existing v4 archive and its overlay remain the preserved comparison artifacts; producing a second full-model archive requires more free external storage than is currently available locally.
|
||||
|
||||
@@ -169,6 +179,8 @@ For the target compressed runtime, copy the selected KAR data to VRAM in compres
|
||||
|
||||
The user-facing Linux command checks the installed NVIDIA driver and starts the native engine. It does not carry the driver. The single-file GPU packaging goal still needs a real Linux CUDA build and loader test.
|
||||
|
||||
Experimental `model prepare-kar-overlay` writes a matching `.pending.json` intent before publishing its archive. On retry it verifies the intent, KAR records/CRC and source identity before completing a missing provenance sidecar; the sidecar is no-replace and the intent is removed only after sidecar read-back verification. A complete archive and sidecar without an intent are reused only when both match the current inputs. Incomplete or unrelated outputs fail closed and are never overwritten. This is publication recovery, not approval of the lossy overlay for serving.
|
||||
|
||||
## Cache profiles
|
||||
|
||||
| Profile | Attention state | Status |
|
||||
|
||||
@@ -0,0 +1,617 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Run the pinned Linux unit suite and enforce changed-production Rust coverage."""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
BASELINE = "d3e63a7"
|
||||
NIGHTLY = "nightly-2026-10-05"
|
||||
RUSTC_VERSION = "rustc 1.101.0-nightly (282215592 2026-10-04)"
|
||||
LLVM_VERSION = "LLVM version 23.1.3-rust-1.101.0-nightly"
|
||||
RUST_FILES = (
|
||||
"control-plane/src/kar_overlay.rs",
|
||||
"control-plane/src/kar_stream_encode.rs",
|
||||
"control-plane/src/kar_writer.rs",
|
||||
"control-plane/src/model_pipeline.rs",
|
||||
"control-plane/src/prepare_preview.rs",
|
||||
"control-plane/src/stream_parts.rs",
|
||||
)
|
||||
DOCUMENT_FILES = ("docs/build-validation.md", "docs/compressed-runtime.md")
|
||||
SCOPE_FILES = (*RUST_FILES, *DOCUMENT_FILES)
|
||||
SCOPE_DEFINITION = (
|
||||
"Full bodies of production functions with added lines or corresponding deleted baseline lines; "
|
||||
"cfg(test) item/block lines are excluded; generated production closures remain included."
|
||||
)
|
||||
|
||||
|
||||
def _blank(chars: list[str], start: int, end: int) -> None:
|
||||
for index in range(start, end):
|
||||
if chars[index] != "\n":
|
||||
chars[index] = " "
|
||||
|
||||
|
||||
def _block_end(source: str, start: int) -> int:
|
||||
depth, index = 1, start + 2
|
||||
while index < len(source) and depth:
|
||||
if source.startswith("/*", index):
|
||||
depth, index = depth + 1, index + 2
|
||||
elif source.startswith("*/", index):
|
||||
depth, index = depth - 1, index + 2
|
||||
else:
|
||||
index += 1
|
||||
if depth:
|
||||
raise ValueError(f"unclosed Rust block comment at byte {start}")
|
||||
return index
|
||||
|
||||
|
||||
def _raw_string_end(source: str, start: int) -> int | None:
|
||||
match = re.match(r"(?:br|r)(#{0,})\"", source[start:])
|
||||
if not match:
|
||||
return None
|
||||
marker = '"' + match.group(1)
|
||||
end = source.find(marker, start + match.end())
|
||||
return len(source) if end < 0 else end + len(marker)
|
||||
|
||||
|
||||
def _quoted_end(source: str, start: int) -> int:
|
||||
index = start + 1
|
||||
while index < len(source):
|
||||
if source[index] == "\\":
|
||||
index += 2
|
||||
elif source[index] == '"':
|
||||
return index + 1
|
||||
else:
|
||||
index += 1
|
||||
raise ValueError(f"unclosed Rust string at byte {start}")
|
||||
|
||||
|
||||
def _char_end(source: str, start: int) -> int | None:
|
||||
if start + 2 >= len(source):
|
||||
return None
|
||||
index = start + 1
|
||||
if source[index] == "\\":
|
||||
index += 2
|
||||
if source[start + 1 : start + 3] == "\\u":
|
||||
close = source.find("}", start + 3)
|
||||
if close < 0:
|
||||
return None
|
||||
index = close + 1
|
||||
else:
|
||||
index += 1
|
||||
return index + 1 if index < len(source) and source[index] == "'" else None
|
||||
|
||||
|
||||
def mask_rust(source: str) -> str:
|
||||
chars, index = list(source), 0
|
||||
while index < len(source):
|
||||
raw_end = _raw_string_end(source, index)
|
||||
if raw_end is not None:
|
||||
_blank(chars, index, raw_end)
|
||||
index = raw_end
|
||||
elif source.startswith("//", index):
|
||||
end = source.find("\n", index)
|
||||
end = len(source) if end < 0 else end
|
||||
_blank(chars, index, end)
|
||||
index = end
|
||||
elif source.startswith("/*", index):
|
||||
end = _block_end(source, index)
|
||||
_blank(chars, index, end)
|
||||
index = end
|
||||
elif source[index] == '"':
|
||||
end = _quoted_end(source, index)
|
||||
_blank(chars, index, end)
|
||||
index = end
|
||||
elif source[index] == "'" and (end := _char_end(source, index)):
|
||||
_blank(chars, index, end)
|
||||
index = end
|
||||
else:
|
||||
index += 1
|
||||
return "".join(chars)
|
||||
|
||||
|
||||
def matching(mask: str, start: int, left: str, right: str) -> int:
|
||||
depth = 0
|
||||
for index in range(start, len(mask)):
|
||||
depth += mask[index] == left
|
||||
depth -= mask[index] == right
|
||||
if depth == 0:
|
||||
return index
|
||||
raise ValueError(f"unclosed Rust delimiter {left!r} at byte {start}")
|
||||
|
||||
|
||||
def _body_depths(depths: list[int], char: str, previous: str) -> None:
|
||||
if char == "(": depths[0] += 1
|
||||
elif char == ")": depths[0] -= 1
|
||||
elif char == "[": depths[1] += 1
|
||||
elif char == "]": depths[1] -= 1
|
||||
elif char == "<": depths[2] += 1
|
||||
elif char == ">" and previous != "-" and depths[2]: depths[2] -= 1
|
||||
|
||||
|
||||
def _body_open(mask: str, start: int) -> int:
|
||||
depths = [0, 0, 0]
|
||||
for index in range(start, len(mask)):
|
||||
char = mask[index]
|
||||
_body_depths(depths, char, mask[index - 1] if index else "")
|
||||
if char in "{;" and not any(depths):
|
||||
return index
|
||||
return len(mask)
|
||||
|
||||
|
||||
def _skip_space(mask: str, index: int) -> int:
|
||||
while index < len(mask) and mask[index].isspace():
|
||||
index += 1
|
||||
return index
|
||||
|
||||
|
||||
def _skip_attributes(mask: str, index: int) -> int:
|
||||
while True:
|
||||
index = _skip_space(mask, index)
|
||||
if not mask.startswith("#[", index):
|
||||
return index
|
||||
index = matching(mask, index + 1, "[", "]") + 1
|
||||
|
||||
|
||||
def _skip_visibility(mask: str, index: int) -> int:
|
||||
if not re.match(r"pub\b", mask[index:]):
|
||||
return index
|
||||
index = _skip_space(mask, index + 3)
|
||||
if index < len(mask) and mask[index] == "(":
|
||||
index = matching(mask, index, "(", ")") + 1
|
||||
return _skip_space(mask, index)
|
||||
|
||||
|
||||
def _statement_depths(depths: list[int], char: str) -> bool:
|
||||
if char == "(": depths[0] += 1
|
||||
elif char == ")": depths[0] -= 1
|
||||
elif char == "[": depths[1] += 1
|
||||
elif char == "]": depths[1] -= 1
|
||||
elif char == "{": depths[2] += 1
|
||||
elif char == "}": depths[2] -= 1
|
||||
return char == "}" and not any(depths)
|
||||
|
||||
|
||||
def _statement_end(mask: str, start: int) -> int:
|
||||
depths = [0, 0, 0]
|
||||
for index, char in enumerate(mask[start:], start):
|
||||
if _statement_depths(depths, char):
|
||||
return index + 1
|
||||
if char == ";" and not any(depths):
|
||||
return index + 1
|
||||
raise ValueError(f"cannot find end of Rust statement at byte {start}")
|
||||
|
||||
|
||||
def _item_end(mask: str, start: int) -> int:
|
||||
macro = re.match(r"(?:macro_rules!\s*[A-Za-z_][A-Za-z0-9_]*|[A-Za-z_:][A-Za-z0-9_:]*!)\s*", mask[start:])
|
||||
if macro:
|
||||
group = _skip_space(mask, start + macro.end())
|
||||
if group >= len(mask) or mask[group] not in "{([":
|
||||
raise ValueError(f"unsupported cfg(test) macro at byte {start}")
|
||||
close = {"{": "}", "(": ")", "[": "]"}[mask[group]]
|
||||
return matching(mask, group, mask[group], close) + 1
|
||||
item = re.match(r"(fn|mod|impl|struct|enum|trait|use|const|static|type|extern)\b", mask[start:])
|
||||
if not item:
|
||||
return _statement_end(mask, start)
|
||||
kind, cursor = item.group(1), start + item.end()
|
||||
if kind == "fn":
|
||||
paren = mask.find("(", cursor)
|
||||
close = matching(mask, paren, "(", ")")
|
||||
cursor = _body_open(mask, close + 1)
|
||||
if kind in {"use", "const", "static", "type"}:
|
||||
return _statement_end(mask, cursor)
|
||||
opening = _body_open(mask, cursor)
|
||||
if opening < len(mask) and mask[opening] == "{":
|
||||
return matching(mask, opening, "{", "}") + 1
|
||||
return _statement_end(mask, cursor)
|
||||
|
||||
|
||||
def cfg_test_spans(source: str, mask: str) -> list[tuple[int, int]]:
|
||||
spans = []
|
||||
pattern = re.compile(r"#\s*\[\s*cfg\s*\(\s*test\s*\)\s*\]")
|
||||
for attr in pattern.finditer(mask):
|
||||
if attr.start() and mask[attr.start() - 1] == "!":
|
||||
spans.append((0, len(source)))
|
||||
continue
|
||||
start = _skip_visibility(mask, _skip_attributes(mask, attr.end()))
|
||||
end = _item_end(mask, start)
|
||||
spans.append((attr.start(), end))
|
||||
return _merge_spans(spans)
|
||||
|
||||
|
||||
def _merge_spans(spans: list[tuple[int, int]]) -> list[tuple[int, int]]:
|
||||
merged = []
|
||||
for start, end in sorted(spans):
|
||||
if merged and start <= merged[-1][1]:
|
||||
merged[-1] = (merged[-1][0], max(merged[-1][1], end))
|
||||
else:
|
||||
merged.append((start, end))
|
||||
return merged
|
||||
|
||||
|
||||
def _span_lines(source: str, spans: list[tuple[int, int]]) -> set[int]:
|
||||
lines = set()
|
||||
for start, end in spans:
|
||||
first = source.count("\n", 0, start) + 1
|
||||
last = source.count("\n", 0, end) + 1
|
||||
lines.update(range(first, last + 1))
|
||||
return lines
|
||||
|
||||
|
||||
def rust_functions(source: str) -> tuple[list[dict], set[int]]:
|
||||
mask, found = mask_rust(source), []
|
||||
test_spans = cfg_test_spans(source, mask)
|
||||
test_lines = _span_lines(source, test_spans)
|
||||
for match in re.finditer(r"\bfn\s+([A-Za-z_][A-Za-z0-9_]*)\b", mask):
|
||||
if any(start <= match.start() < end for start, end in test_spans):
|
||||
continue
|
||||
paren = mask.find("(", match.end())
|
||||
close = matching(mask, paren, "(", ")")
|
||||
opening = _body_open(mask, close + 1)
|
||||
if opening >= len(mask) or mask[opening] != "{":
|
||||
continue
|
||||
end = matching(mask, opening, "{", "}") + 1
|
||||
found.append({"name": match.group(1), "start": source.count("\n", 0, match.start()) + 1,
|
||||
"end": source.count("\n", 0, end) + 1})
|
||||
return found, test_lines
|
||||
|
||||
|
||||
def parse_diff_hunks(diff: str) -> tuple[set[int], set[int]]:
|
||||
added, deleted, new_line, old_line = set(), set(), 0, 0
|
||||
for line in diff.splitlines():
|
||||
if line.startswith("@@"):
|
||||
match = re.match(r"@@ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@", line)
|
||||
if not match:
|
||||
raise ValueError(f"invalid unified diff hunk: {line}")
|
||||
old_line, new_line = int(match.group(1)), int(match.group(2))
|
||||
elif line.startswith("+++") or line.startswith("---") or line.startswith("\\"):
|
||||
continue
|
||||
elif line.startswith("+"):
|
||||
added.add(new_line)
|
||||
new_line += 1
|
||||
elif line.startswith("-"):
|
||||
deleted.add(old_line)
|
||||
old_line += 1
|
||||
elif line.startswith(" "):
|
||||
old_line += 1
|
||||
new_line += 1
|
||||
return added, deleted
|
||||
|
||||
|
||||
def select_production_functions(source: str, baseline_source: str, diff: str) -> tuple[list[dict], set[int]]:
|
||||
additions, deletions = parse_diff_hunks(diff)
|
||||
current, test_lines = rust_functions(source)
|
||||
old, old_test_lines = rust_functions(baseline_source)
|
||||
additions.difference_update(test_lines)
|
||||
deletions.difference_update(old_test_lines)
|
||||
deleted_names = {item["name"] for item in old if any(item["start"] <= line <= item["end"] for line in deletions)}
|
||||
selected = [item for item in current if item["name"] in deleted_names or
|
||||
any(item["start"] <= line <= item["end"] for line in additions)]
|
||||
if not selected:
|
||||
raise ValueError("baseline diff selects no current production functions")
|
||||
return selected, test_lines
|
||||
|
||||
|
||||
def parse_lcov(text: str) -> list[dict]:
|
||||
records, record = [], None
|
||||
for line in text.splitlines():
|
||||
if line.startswith("SF:"):
|
||||
if record is not None:
|
||||
raise ValueError("LCOV source record lacks end_of_record")
|
||||
record = {"sf": line[3:], "da": [], "fn": [], "fnda": [], "brda": []}
|
||||
elif line == "end_of_record":
|
||||
if record is None:
|
||||
raise ValueError("LCOV end_of_record without SF")
|
||||
records.append(record)
|
||||
record = None
|
||||
elif record is not None:
|
||||
_parse_lcov_row(record, line)
|
||||
if record is not None:
|
||||
raise ValueError("LCOV source record lacks end_of_record")
|
||||
return records
|
||||
|
||||
|
||||
def _parse_lcov_row(record: dict, line: str) -> None:
|
||||
try:
|
||||
if line.startswith("DA:"):
|
||||
parts = line[3:].split(",")
|
||||
record["da"].append((int(parts[0]), int(parts[1])))
|
||||
elif line.startswith("FN:"):
|
||||
number, name = line[3:].split(",", 1)
|
||||
record["fn"].append((int(number), name))
|
||||
elif line.startswith("FNDA:"):
|
||||
count, name = line[5:].split(",", 1)
|
||||
record["fnda"].append((int(count), name))
|
||||
elif line.startswith("BRDA:"):
|
||||
number, block, branch, taken = line[5:].split(",", 3)
|
||||
record["brda"].append((int(number), block, branch, taken))
|
||||
except (IndexError, ValueError) as error:
|
||||
raise ValueError(f"invalid LCOV row: {line}") from error
|
||||
|
||||
|
||||
def _record_path(record: dict) -> str:
|
||||
path = record["sf"].replace("\\", "/")
|
||||
return next((name for name in RUST_FILES if path == name or path.endswith("/" + name)), "")
|
||||
|
||||
|
||||
def _inside(line: int, functions: list[dict], test_lines: set[int]) -> bool:
|
||||
return line not in test_lines and any(item["start"] <= line <= item["end"] for item in functions)
|
||||
|
||||
|
||||
def _merge_lcov(records: list[dict]) -> dict:
|
||||
by_path = {}
|
||||
for record in records:
|
||||
path = _record_path(record)
|
||||
if path:
|
||||
by_path.setdefault(path, []).append(record)
|
||||
return by_path
|
||||
|
||||
|
||||
def _file_metrics(records: list[dict], functions: list[dict], test_lines: set[int]) -> dict:
|
||||
da, fn, fnda, branch = _merge_record_metrics(records)
|
||||
lines = {line: count for line, count in da.items() if _inside(line, functions, test_lines)}
|
||||
funcs = {key: fnda.get(key[1], 0) for key in fn if _inside(key[0], functions, test_lines)}
|
||||
branches = {key: value for key, value in branch.items() if _inside(key[0], functions, test_lines)}
|
||||
return _metrics(lines, funcs, branches)
|
||||
|
||||
|
||||
def _merge_record_metrics(records: list[dict]) -> tuple[dict, dict, dict, dict]:
|
||||
da, fn, fnda, branch = {}, {}, {}, {}
|
||||
for record in records:
|
||||
_merge_record(record, da, fn, fnda, branch)
|
||||
return da, fn, fnda, branch
|
||||
|
||||
|
||||
def _merge_record(record: dict, da: dict, fn: dict, fnda: dict, branch: dict) -> None:
|
||||
for line, count in record["da"]:
|
||||
da[line] = da.get(line, 0) + count
|
||||
for line, name in record["fn"]:
|
||||
fn[(line, name)] = fn.get((line, name), 0)
|
||||
for count, name in record["fnda"]:
|
||||
fnda[name] = fnda.get(name, 0) + count
|
||||
for line, block, number, taken in record["brda"]:
|
||||
key = (line, block, number)
|
||||
branch[key] = _branch_total(branch.get(key), taken)
|
||||
|
||||
|
||||
def _branch_total(previous: str | None, taken: str) -> str:
|
||||
if previous is None or taken == "-" or previous == "-":
|
||||
return taken
|
||||
return str(int(previous) + int(taken))
|
||||
|
||||
|
||||
def _metrics(lines: dict, functions: dict, branches: dict) -> dict:
|
||||
line_misses = sorted(line for line, hits in lines.items() if hits == 0)
|
||||
fn_misses = [{"line": line, "name": name} for (line, name), hits in functions.items() if hits == 0]
|
||||
branch_misses = [{"line": line, "block": block, "branch": branch, "taken": taken}
|
||||
for (line, block, branch), taken in branches.items() if taken in {"0", "-"}]
|
||||
return {"lines": _metric(len(lines) - len(line_misses), len(lines), line_misses),
|
||||
"functions": _metric(len(functions) - len(fn_misses), len(functions), fn_misses),
|
||||
"branches": _metric(len(branches) - len(branch_misses), len(branches), branch_misses)}
|
||||
|
||||
|
||||
def _metric(hit: int, total: int, misses: list) -> dict:
|
||||
return {"hit": hit, "total": total, "percent": (100.0 * hit / total) if total else 0.0,
|
||||
"misses": misses}
|
||||
|
||||
|
||||
def coverage_report(records: list[dict], scopes: dict[str, tuple[list[dict], set[int]]]) -> dict:
|
||||
by_path, files = _merge_lcov(records), {}
|
||||
totals = {kind: {"hit": 0, "total": 0, "misses": []} for kind in ("lines", "functions", "branches")}
|
||||
for path in RUST_FILES:
|
||||
if path not in by_path:
|
||||
raise ValueError(f"LCOV is missing required Rust source record: {path}")
|
||||
functions, test_lines = scopes[path]
|
||||
metrics = _file_metrics(by_path[path], functions, test_lines)
|
||||
files[path] = {"functions": functions, "metrics": metrics}
|
||||
for kind, values in metrics.items():
|
||||
totals[kind]["hit"] += values["hit"]
|
||||
totals[kind]["total"] += values["total"]
|
||||
totals[kind]["misses"].extend({**miss, "file": path} if isinstance(miss, dict)
|
||||
else {"line": miss, "file": path} for miss in values["misses"])
|
||||
for kind, values in totals.items():
|
||||
values["percent"] = 100.0 * values["hit"] / values["total"] if values["total"] else 0.0
|
||||
return {"baseline": BASELINE, "files": files, "totals": totals}
|
||||
|
||||
|
||||
def _run(command: list[str], root: Path, env: dict | None = None) -> subprocess.CompletedProcess:
|
||||
return subprocess.run(command, cwd=root, env=env, text=True, capture_output=True, check=False)
|
||||
|
||||
|
||||
def _rust_tools(root: Path) -> tuple[Path, Path, dict]:
|
||||
rustc = _run(["rustc", f"+{NIGHTLY}", "-vV"], root)
|
||||
if rustc.returncode:
|
||||
raise RuntimeError(f"pinned rustc is unavailable: {rustc.stderr.strip()}")
|
||||
versions = rustc.stdout.strip()
|
||||
if RUSTC_VERSION not in versions:
|
||||
raise RuntimeError(f"unexpected pinned rustc version: {versions.splitlines()[0]}")
|
||||
details = dict(line.split(": ", 1) for line in versions.splitlines() if ": " in line)
|
||||
sysroot = _run(["rustc", f"+{NIGHTLY}", "--print", "sysroot"], root)
|
||||
if sysroot.returncode or "host" not in details:
|
||||
raise RuntimeError("cannot resolve pinned LLVM tool directory")
|
||||
bindir = Path(sysroot.stdout.strip()) / "lib" / "rustlib" / details["host"] / "bin"
|
||||
tools = (bindir / "llvm-cov", bindir / "llvm-profdata")
|
||||
for tool in tools:
|
||||
version = _run([str(tool), "--version"], root)
|
||||
if version.returncode or LLVM_VERSION not in version.stdout:
|
||||
raise RuntimeError(f"unexpected {tool.name} version: {version.stdout.strip()}")
|
||||
return tools[0], tools[1], {"rustc": versions.splitlines()[0], "llvm": LLVM_VERSION, "host": details["host"]}
|
||||
|
||||
|
||||
def _package_id(root: Path) -> str:
|
||||
result = _run(["cargo", "metadata", "--manifest-path", "control-plane/Cargo.toml",
|
||||
"--locked", "--format-version=1", "--no-deps"], root)
|
||||
if result.returncode:
|
||||
raise RuntimeError(f"cargo metadata failed: {result.stderr.strip()}")
|
||||
packages = [item["id"] for item in json.loads(result.stdout)["packages"]
|
||||
if item["name"] == "strata-control"]
|
||||
if len(packages) != 1:
|
||||
raise RuntimeError(f"expected one strata-control package, found {len(packages)}")
|
||||
return packages[0]
|
||||
|
||||
|
||||
def _cargo_harness(json_path: Path, package_id: str) -> Path:
|
||||
found = []
|
||||
for line in json_path.read_text().splitlines():
|
||||
try: item = json.loads(line)
|
||||
except json.JSONDecodeError: continue
|
||||
if _is_test_lib_artifact(item, package_id):
|
||||
found.append(Path(item["executable"]))
|
||||
if len(found) != 1 or not found[0].is_file():
|
||||
raise RuntimeError(f"expected one built strata-control lib test binary, found {len(found)}")
|
||||
return found[0]
|
||||
|
||||
|
||||
def _is_test_lib_artifact(item: dict, package_id: str) -> bool:
|
||||
target = item.get("target", {})
|
||||
return (item.get("reason") == "compiler-artifact" and item.get("package_id") == package_id
|
||||
and target.get("name") == "strata_control" and target.get("kind") == ["lib"]
|
||||
and target.get("test") and item.get("executable"))
|
||||
|
||||
|
||||
def _changed_scopes(root: Path) -> tuple[dict, dict]:
|
||||
if _run(["git", "cat-file", "-e", f"{BASELINE}^{{commit}}"], root).returncode:
|
||||
raise RuntimeError(f"baseline commit {BASELINE} is unavailable")
|
||||
if _run(["git", "merge-base", "--is-ancestor", BASELINE, "HEAD"], root).returncode:
|
||||
raise RuntimeError(f"baseline {BASELINE} is not an ancestor of HEAD")
|
||||
scopes, functions_by_file = {}, {}
|
||||
for path in RUST_FILES:
|
||||
source = (root / path).read_text()
|
||||
old = _run(["git", "show", f"{BASELINE}:{path}"], root)
|
||||
diff = _run(["git", "diff", "--no-ext-diff", "--unified=0", BASELINE, "--", path], root)
|
||||
if old.returncode or diff.returncode:
|
||||
raise RuntimeError(f"cannot read baseline/diff for {path}")
|
||||
funcs, test_lines = select_production_functions(source, old.stdout, diff.stdout)
|
||||
scopes[path] = (funcs, test_lines)
|
||||
functions_by_file[path] = funcs
|
||||
return scopes, functions_by_file
|
||||
|
||||
|
||||
def _diff_hash(root: Path, paths: tuple[str, ...]) -> str:
|
||||
result = _run(["git", "diff", "--binary", BASELINE, "--", *paths], root)
|
||||
if result.returncode:
|
||||
raise RuntimeError(f"cannot hash changed paths: {', '.join(paths)}")
|
||||
return hashlib.sha256(result.stdout.encode()).hexdigest()
|
||||
|
||||
|
||||
def _commit(root: Path, revision: str) -> str:
|
||||
result = _run(["git", "rev-parse", revision], root)
|
||||
if result.returncode:
|
||||
raise RuntimeError(f"cannot resolve commit {revision}")
|
||||
return result.stdout.strip()
|
||||
|
||||
|
||||
def _coverage_env(out: Path) -> dict:
|
||||
env = os.environ.copy()
|
||||
flags = "-C instrument-coverage -Zcoverage-options=branch --cfg=coverage "
|
||||
flags += "--cfg=coverage_nightly -C link-arg=-Wl,--no-keep-memory"
|
||||
env.update({"RUSTFLAGS": flags,
|
||||
"CARGO_BUILD_JOBS": "1", "CARGO_INCREMENTAL": "0", "RUST_TEST_THREADS": "1",
|
||||
"CARGO_PROFILE_DEV_DEBUG": "0", "CARGO_PROFILE_TEST_DEBUG": "0",
|
||||
"LLVM_PROFILE_FILE": str(out / "profraw" / "%m-%p.profraw")})
|
||||
(out / "profraw").mkdir(parents=True, exist_ok=True)
|
||||
return env
|
||||
|
||||
|
||||
def _write_summary(out: Path, report: dict) -> None:
|
||||
(out / "summary.json").write_text(json.dumps(report, indent=2, sort_keys=True) + "\n")
|
||||
rows = [f"Changed-production coverage vs {report['baseline']}"]
|
||||
for kind, value in report.get("totals", {}).items():
|
||||
rows.append(f"{kind}: {value['hit']}/{value['total']} ({value.get('percent', 0.0):.2f}%)")
|
||||
rows.append(f"Gate: {'PASS' if report.get('passed') else 'FAIL'}")
|
||||
rows.append(f"Reason: {report.get('failure', 'all required gates passed')}")
|
||||
(out / "summary.txt").write_text("\n".join(rows) + "\n")
|
||||
|
||||
|
||||
def _run_instrumented_tests(root: Path, out: Path, env: dict) -> tuple[int, Path, int]:
|
||||
cargo_json, cargo_stderr = out / "cargo.jsonl", out / "cargo.stderr"
|
||||
command = ["cargo", f"+{NIGHTLY}", "test", "--manifest-path", "control-plane/Cargo.toml",
|
||||
"--locked", "-p", "strata-control", "--lib", "--message-format=json-render-diagnostics"]
|
||||
with cargo_json.open("w") as stdout, cargo_stderr.open("w") as stderr:
|
||||
test = subprocess.run(command, cwd=root, env=env, stdout=stdout, stderr=stderr, check=False)
|
||||
binary = _cargo_harness(cargo_json, _package_id(root))
|
||||
profiles = sorted((out / "profraw").glob("*.profraw"))
|
||||
if not profiles:
|
||||
raise RuntimeError("instrumented tests produced no profraw files")
|
||||
return test.returncode, binary, len(profiles)
|
||||
|
||||
|
||||
def _export_lcov(root: Path, out: Path, llvm_cov: Path, llvm_profdata: Path,
|
||||
binary: Path) -> str:
|
||||
profiles = sorted((out / "profraw").glob("*.profraw"))
|
||||
profile = out / "merged.profdata"
|
||||
merge = _run([str(llvm_profdata), "merge", "-sparse", "-o", str(profile), *map(str, profiles)], root)
|
||||
if merge.returncode:
|
||||
(out / "llvm-profdata.stderr").write_text(merge.stderr)
|
||||
raise RuntimeError("llvm-profdata merge failed")
|
||||
export = _run([str(llvm_cov), "export", "--format=lcov", f"--instr-profile={profile}", str(binary)], root)
|
||||
(out / "llvm-cov.stderr").write_text(export.stderr)
|
||||
if export.returncode:
|
||||
raise RuntimeError("llvm-cov export failed")
|
||||
(out / "coverage.raw.lcov").write_text(export.stdout)
|
||||
return export.stdout
|
||||
|
||||
|
||||
def _coverage_passed(state: dict, test_exit: int) -> bool:
|
||||
exact = all(values["total"] > 0 and values["hit"] == values["total"]
|
||||
for values in state["totals"].values())
|
||||
return test_exit == 0 and exact
|
||||
|
||||
|
||||
def _stable_diff(root: Path, state: dict) -> None:
|
||||
if state["rust_six_path_diff_sha256"] != _diff_hash(root, RUST_FILES):
|
||||
raise RuntimeError("Rust source diff changed during coverage collection")
|
||||
if state["full_eight_path_diff_sha256"] != _diff_hash(root, SCOPE_FILES):
|
||||
raise RuntimeError("eight-path source/docs diff changed during coverage collection")
|
||||
|
||||
|
||||
def _attach_scope_result(state: dict, test_exit: int) -> None:
|
||||
state["scope_files"] = list(RUST_FILES)
|
||||
state["scope_definition"] = SCOPE_DEFINITION
|
||||
state["measurement"] = "unit line/function/branch coverage; literal 100 percent required"
|
||||
state["source_diff_sha256"] = state["rust_six_path_diff_sha256"]
|
||||
state["passed"] = _coverage_passed(state, test_exit)
|
||||
state["failure"] = "" if state["passed"] else "unit tests failed or changed-scope coverage was not exactly 100%"
|
||||
|
||||
|
||||
def run_coverage(root: Path, out: Path) -> int:
|
||||
out.mkdir(parents=True, exist_ok=True)
|
||||
state = {"baseline": BASELINE, "head": "unknown", "passed": False, "failure": "not started"}
|
||||
try:
|
||||
state["head"] = _commit(root, "HEAD")
|
||||
state["baseline_commit"] = _commit(root, BASELINE)
|
||||
scopes, _ = _changed_scopes(root)
|
||||
state["rust_six_path_diff_sha256"] = _diff_hash(root, RUST_FILES)
|
||||
state["full_eight_path_diff_sha256"] = _diff_hash(root, SCOPE_FILES)
|
||||
llvm_cov, llvm_profdata, versions = _rust_tools(root)
|
||||
state["toolchain"] = versions
|
||||
test_exit, binary, profile_count = _run_instrumented_tests(root, out, _coverage_env(out))
|
||||
state.update(cargo_exit_code=test_exit, selected_test_binary=str(binary), profraw_files=profile_count)
|
||||
raw = _export_lcov(root, out, llvm_cov, llvm_profdata, binary)
|
||||
report = coverage_report(parse_lcov(raw), scopes)
|
||||
state.update(report)
|
||||
_stable_diff(root, state)
|
||||
_attach_scope_result(state, test_exit)
|
||||
except Exception as error:
|
||||
state["failure"] = f"{type(error).__name__}: {error}"
|
||||
_write_summary(out, state)
|
||||
print((out / "summary.txt").read_text(), end="")
|
||||
return 0 if state["passed"] else 1
|
||||
|
||||
|
||||
def main() -> int:
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--root", type=Path, default=Path.cwd())
|
||||
parser.add_argument("--output-dir", type=Path, required=True)
|
||||
args = parser.parse_args()
|
||||
return run_coverage(args.root.resolve(), args.output_dir.resolve())
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,139 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Deterministic parser and workflow-contract tests for the manual coverage gate."""
|
||||
from __future__ import annotations
|
||||
|
||||
import importlib.util
|
||||
import json
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
EXISTING_JOBS_SHA256 = "26cf64e51e207b9f81cef306e4ec31f3ed817334699e0b0fe7c7a031cb848a25"
|
||||
PUSH_PULL_SHA256 = "cefb2858cd9b21076e171fa764dbf2df1472b911cc0743caa6fac7d09a216c89"
|
||||
SPEC = importlib.util.spec_from_file_location("changed_scope", ROOT / "scripts/check-changed-scope-coverage.py")
|
||||
COVERAGE = importlib.util.module_from_spec(SPEC)
|
||||
SPEC.loader.exec_module(COVERAGE)
|
||||
|
||||
|
||||
def _job_block(text: str, name: str) -> str:
|
||||
lines = text.splitlines(keepends=True)
|
||||
start = next(index for index, line in enumerate(lines) if line == f" {name}:\n")
|
||||
end = next((index for index in range(start + 1, len(lines))
|
||||
if lines[index].startswith(" ") and not lines[index].startswith(" ")
|
||||
and lines[index].strip().endswith(":")), len(lines))
|
||||
return "".join(lines[start:end])
|
||||
|
||||
|
||||
def _lcov(path: str, branch: str = "1") -> str:
|
||||
return (f"SF:{path}\nFN:1,live\nFNDA:1,live\nDA:1,1\nDA:2,1\n"
|
||||
f"BRDA:2,0,0,{branch}\nend_of_record\n")
|
||||
|
||||
|
||||
class ChangedScopeCoverageTests(unittest.TestCase):
|
||||
def test_rust_mask_and_cfg_test_exclusion(self) -> None:
|
||||
source = '''
|
||||
// fn comment() {}
|
||||
const TEXT: &str = r###"fn raw_fake() {}"###;
|
||||
pub fn live(value: u8) -> u8 { if value > 0 { value } else { 0 } }
|
||||
#[cfg(test)]
|
||||
mod tests { #[test] fn hidden() {} }
|
||||
pub fn with_test_only_block() {
|
||||
#[cfg(test)] if true { unreachable!(); }
|
||||
}
|
||||
'''
|
||||
functions, test_lines = COVERAGE.rust_functions(source)
|
||||
self.assertEqual([item["name"] for item in functions], ["live", "with_test_only_block"])
|
||||
self.assertTrue(test_lines)
|
||||
self.assertNotIn("fn raw_fake", COVERAGE.mask_rust(source))
|
||||
|
||||
def test_diff_hunks_select_only_added_and_deleted_new_lines(self) -> None:
|
||||
diff = "--- a/x\n+++ b/x\n@@ -2,2 +2,2 @@\n old\n+added\n-gone\n"
|
||||
self.assertEqual(COVERAGE.parse_diff_hunks(diff), ({3}, {3}))
|
||||
|
||||
def test_changed_scope_selects_body_but_excludes_test_additions(self) -> None:
|
||||
old = "fn stable() { 1 }\nfn live() { 2 }\n#[cfg(test)]\nmod tests { fn sample() {} }\n"
|
||||
new = "fn stable() { 1 }\nfn live() { 3 }\n#[cfg(test)]\nmod tests { fn sample() { 4 } }\n"
|
||||
diff = ("@@ -2 +2 @@\n-fn live() { 2 }\n+fn live() { 3 }\n"
|
||||
"@@ -4 +4 @@\n-mod tests { fn sample() {} }\n+mod tests { fn sample() { 4 } }\n")
|
||||
selected, _ = COVERAGE.select_production_functions(new, old, diff)
|
||||
self.assertEqual([item["name"] for item in selected], ["live"])
|
||||
|
||||
def test_lcov_zero_and_unknown_branches_fail_closed(self) -> None:
|
||||
record = COVERAGE.parse_lcov(_lcov("control-plane/src/kar_writer.rs", "-"))[0]
|
||||
metrics = COVERAGE._file_metrics([record], [{"name": "live", "start": 1, "end": 3}], set())
|
||||
self.assertEqual(metrics["branches"]["hit"], 0)
|
||||
self.assertEqual(metrics["branches"]["misses"][0]["taken"], "-")
|
||||
record = COVERAGE.parse_lcov(_lcov("control-plane/src/kar_writer.rs", "0"))[0]
|
||||
metrics = COVERAGE._file_metrics([record], [{"name": "live", "start": 1, "end": 3}], set())
|
||||
self.assertEqual(metrics["branches"]["hit"], 0)
|
||||
|
||||
def test_coverage_requires_every_production_file_and_exact_hits(self) -> None:
|
||||
scopes = {path: ([{"name": "live", "start": 1, "end": 3}], set())
|
||||
for path in COVERAGE.RUST_FILES}
|
||||
records = [COVERAGE.parse_lcov(_lcov(path))[0] for path in COVERAGE.RUST_FILES]
|
||||
report = COVERAGE.coverage_report(records, scopes)
|
||||
self.assertTrue(all(item["hit"] == item["total"] for item in report["totals"].values()))
|
||||
with self.assertRaisesRegex(ValueError, "missing required Rust source"):
|
||||
COVERAGE.coverage_report(records[:-1], scopes)
|
||||
records[0]["brda"][0] = (2, "0", "0", "0")
|
||||
report = COVERAGE.coverage_report(records, scopes)
|
||||
self.assertNotEqual(report["totals"]["branches"]["hit"], report["totals"]["branches"]["total"])
|
||||
|
||||
def test_cargo_json_selects_only_the_package_lib_test_executable(self) -> None:
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
binary = Path(directory) / "strata_control-test"
|
||||
binary.touch()
|
||||
rows = [{"reason": "compiler-artifact", "package_id": "other 1.0.0",
|
||||
"target": {"name": "strata_control", "kind": ["lib"], "test": True},
|
||||
"executable": str(binary)},
|
||||
{"reason": "compiler-artifact", "package_id": "strata-control 1.0.0",
|
||||
"target": {"name": "strata_control", "kind": ["lib"], "test": True},
|
||||
"executable": str(binary)}]
|
||||
log = Path(directory) / "cargo.jsonl"
|
||||
log.write_text("\n".join(json.dumps(row) for row in rows))
|
||||
self.assertEqual(COVERAGE._cargo_harness(log, "strata-control 1.0.0"), binary)
|
||||
|
||||
def test_workflow_adds_opt_in_cpu_job_without_changing_existing_jobs(self) -> None:
|
||||
current = (ROOT / ".github/workflows/linux.yml").read_text()
|
||||
original = subprocess.run(["git", "show", "HEAD:.github/workflows/linux.yml"],
|
||||
cwd=ROOT, capture_output=True, text=True, check=True).stdout
|
||||
job_names = ("verify", "keyless-cuda", "hosted-cuda-package", "linux-static-cli",
|
||||
"linux-cli-container", "release-cli")
|
||||
self.assertEqual(_digest("".join(_job_block(current, name) for name in job_names)),
|
||||
EXISTING_JOBS_SHA256)
|
||||
self.assertEqual(_digest(_push_pull_block(current)), PUSH_PULL_SHA256)
|
||||
for name in job_names:
|
||||
self.assertEqual(_job_block(current, name), _job_block(original, name), name)
|
||||
self.assertIn("pull_request:\n workflow_dispatch:", current)
|
||||
self.assertIn("changed_scope_coverage:\n description:", current)
|
||||
self.assertIn("type: boolean\n default: false", current)
|
||||
job = _job_block(current, "changed-scope-coverage")
|
||||
self.assertIn("needs: verify", job)
|
||||
self.assertIn("runs-on: ubuntu-latest", job)
|
||||
self.assertNotIn("self-hosted", job)
|
||||
self.assertNotIn("strata-gpu", job)
|
||||
self.assertIn("inputs.changed_scope_coverage", job)
|
||||
self.assertIn("nightly-2026-10-05", job)
|
||||
self.assertIn("scripts/check-changed-scope-coverage.py", job)
|
||||
self.assertIn("if: always()", job)
|
||||
self.assertIn("actions/upload-artifact@v4.4.3", job)
|
||||
self.assertIn("coverage.raw.lcov", job)
|
||||
self.assertIn("summary.json", job)
|
||||
self.assertIn("summary.txt", job)
|
||||
|
||||
|
||||
def _digest(value: str) -> str:
|
||||
import hashlib
|
||||
return hashlib.sha256(value.encode()).hexdigest()
|
||||
|
||||
|
||||
def _push_pull_block(text: str) -> str:
|
||||
start = text.index("on:\n") + len("on:\n")
|
||||
end = text.index(" workflow_dispatch:", start)
|
||||
return text[start:end]
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main(verbosity=2)
|
||||
Reference in New Issue
Block a user