Consolidate translation, linkage, and validation work

Squash 147 commits (2026-08-20 through 2026-08-31) into one change on top
of the exact-kernel-grid work. Covers native lowering and pointer/layout
construction, AIR intrinsic and funnel-shift coverage, BDA address
preservation across aggregate calls, CFG structurization, function-constant
and visible-function specialization, the 30-second translation ceiling, the
authored-case corpus and linkage validation suite, and refreshed byte-exact
MoltenVK evidence.

The kernel-grid lowering in this tree supersedes the 324-line variant in
the parent commit; that file is reduced to its current 139-line form here.

Resulting tree is identical to 7174c7b. Prior history remains reachable at
tag pre-squash-backup and branch backup/pre-squash-7174c7b.

Claude-Session: https://claude.ai/code/session_01D1u4vU7Mr5QNWrnnRHC8iS
This commit is contained in:
Anees Iqbal committed 2026-08-31 09:03:42 +03:00
1 parent d98eae794b
commit 08970cacd2
478 files changed
+70879 -25282

No files matched your search

+1 -1
View File
@@ -674,7 +674,7 @@ mod tests {
entry: "main".into(),
air_ll: "air".into(),
blob_b64: None,
lib_sha256: "22".repeat(32),
lib_sha256s: vec!["22".repeat(32)],
label: "test".into(),
};
let mut options = AbOptions {
+66 -30
View File
@@ -11,7 +11,7 @@ use metal2vulkan_validation::hash::sha256_bytes;
use metal2vulkan_validation::library_module::{self, LibraryModuleRow};
use metal2vulkan_validation::source::{self, SourceRow};
use metal2vulkan_validation::ScratchDir;
use std::collections::HashMap;
use std::collections::{HashMap, HashSet};
use std::fs;
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
@@ -305,8 +305,8 @@ fn run(opts: Options) -> i32 {
let mut by_hash = HashMap::new();
let mut library_modules = HashMap::new();
let mut indexed_entry_duplicates = 0usize;
let indexed_source_hashes = match source::indexed_source_hashes(&opts.out) {
Ok(hashes) => hashes,
let indexed_source_memberships = match source::indexed_source_memberships(&opts.out) {
Ok(memberships) => memberships,
Err(error) => {
eprintln!("{PROGRAM}: load source index: {error}");
return 1;
@@ -321,11 +321,14 @@ fn run(opts: Options) -> i32 {
&mut library_modules,
&mut stats,
);
// Dependency modules are deliberately retained independently. Only stage-entry rows can
// be discarded here, after each metallib, before a broad reharvest accumulates gigabytes
// of entries that SQLite already indexes.
// Dependency modules are deliberately retained independently. A stage-entry row can be
// discarded only when SQLite already knows every parent-library membership observed in
// this batch. Apply that filter after each library so a broad reharvest cannot accumulate
// gigabytes of already-complete entries.
let before_filter = by_hash.len();
by_hash.retain(|hash, _| !indexed_source_hashes.contains(hash));
by_hash.retain(|hash, row| {
!source_memberships_already_indexed(&indexed_source_memberships, hash, row)
});
indexed_entry_duplicates += before_filter - by_hash.len();
}
@@ -337,16 +340,6 @@ fn run(opts: Options) -> i32 {
return if stats.libs_failed == 0 { 0 } else { 1 };
}
let missing_source_hashes =
match source::unindexed_source_hashes(&opts.out, by_hash.keys().cloned()) {
Ok(hashes) => hashes,
Err(error) => {
eprintln!("{PROGRAM}: query source index: {error}");
return 1;
}
};
let indexed_duplicates = by_hash.len() - missing_source_hashes.len();
by_hash.retain(|hash, _| missing_source_hashes.contains(hash));
let mut merge = match source::merge_source_shards(&opts.out, by_hash.into_values()) {
Ok(merge) => merge,
Err(error) => {
@@ -354,7 +347,6 @@ fn run(opts: Options) -> i32 {
return 1;
}
};
merge.duplicates += indexed_duplicates;
merge.duplicates += indexed_entry_duplicates;
let library_merge =
match library_module::merge_library_module_shards(&opts.out, library_modules.into_values())
@@ -367,12 +359,13 @@ fn run(opts: Options) -> i32 {
};
eprintln!(
"# RESULT: libs_ok={} libs_failed={} carved={} entry_batch_unique={} entry_inserted={} entry_replaced={} entry_dup={} entry_shards={} library_module_batch_unique={} library_module_inserted={} library_memberships_added={} library_module_dup={} library_module_shards={} large={} dropped_nonfunctions={} llvm_failed={} ({:.1}s)",
"# RESULT: libs_ok={} libs_failed={} carved={} entry_batch_unique={} entry_inserted={} entry_memberships_added={} entry_replaced={} entry_dup={} entry_shards={} library_module_batch_unique={} library_module_inserted={} library_memberships_added={} library_module_dup={} library_module_shards={} large={} dropped_nonfunctions={} llvm_failed={} ({:.1}s)",
stats.libs_ok,
stats.libs_failed,
stats.blobs_carved,
stats.rows_kept,
merge.inserted,
merge.merged_memberships,
merge.replaced,
stats.duplicates + merge.duplicates,
merge.affected_shards,
@@ -393,6 +386,18 @@ fn run(opts: Options) -> i32 {
}
}
fn source_memberships_already_indexed(
indexed: &HashMap<String, HashSet<String>>,
hash: &str,
row: &SourceRow,
) -> bool {
indexed.get(hash).is_some_and(|memberships| {
row.lib_sha256s
.iter()
.all(|library| memberships.contains(library))
})
}
fn select_metallibs(opts: &Options) -> Result<(Vec<PathBuf>, usize), String> {
if !opts.metallibs.is_empty() {
for path in &opts.metallibs {
@@ -657,7 +662,7 @@ fn harvest_one(
entry,
air_ll: ll_text,
blob_b64: Some(blob_b64),
lib_sha256: lib_sha.clone(),
lib_sha256s: vec![lib_sha.clone()],
label,
};
if merge_source_row(by_hash, row, stats) {
@@ -702,18 +707,22 @@ fn merge_source_row(
stats: &mut HarvestStats,
) -> bool {
let hash = row.air_sha256.clone();
match by_hash.get(&hash) {
match by_hash.get_mut(&hash) {
None => {
by_hash.insert(hash, row);
stats.rows_kept += 1;
true
}
Some(previous) if row.lib_sha256 < previous.lib_sha256 => {
by_hash.insert(hash, row);
stats.duplicates += 1;
false
}
Some(_) => {
Some(previous) => {
previous.lib_sha256s.extend(row.lib_sha256s);
previous.lib_sha256s.sort();
previous.lib_sha256s.dedup();
if source::source_blob_is_preferred(
previous.blob_b64.as_deref(),
row.blob_b64.as_deref(),
) {
previous.blob_b64 = row.blob_b64;
}
stats.duplicates += 1;
false
}
@@ -909,7 +918,7 @@ mod tests {
entry: "k".into(),
air_ll: "ll".into(),
blob_b64: Some("YmxvYg==".into()),
lib_sha256: library.into(),
lib_sha256s: vec![library.into()],
label: "local/test.ll".into(),
}
}
@@ -922,12 +931,39 @@ mod tests {
let mut reverse_stats = HarvestStats::default();
merge_source_row(&mut reverse, row("aa"), &mut reverse_stats);
merge_source_row(&mut reverse, row("bb"), &mut reverse_stats);
assert_eq!(forward[&"11".repeat(32)].lib_sha256, "aa");
assert_eq!(reverse[&"11".repeat(32)].lib_sha256, "aa");
assert_eq!(
forward[&"11".repeat(32)].lib_sha256s,
["aa".to_string(), "bb".to_string()]
);
assert_eq!(
reverse[&"11".repeat(32)].lib_sha256s,
["aa".to_string(), "bb".to_string()]
);
assert_eq!(forward_stats.duplicates, 1);
assert_eq!(reverse_stats.duplicates, 1);
}
#[test]
fn indexed_entry_is_reopened_only_for_a_new_parent_library() {
let hash = "11".repeat(32);
let mut row = SourceRow {
air_sha256: hash.clone(),
stage: "Kernel".into(),
entry: "k".into(),
air_ll: "ll".into(),
blob_b64: Some("YmxvYg==".into()),
lib_sha256s: vec!["aa".into()],
label: "local/test.ll".into(),
};
let mut indexed = HashMap::new();
assert!(!source_memberships_already_indexed(&indexed, &hash, &row));
indexed.insert(hash.clone(), HashSet::from(["aa".to_string()]));
assert!(source_memberships_already_indexed(&indexed, &hash, &row));
row.lib_sha256s.push("bb".into());
assert!(!source_memberships_already_indexed(&indexed, &hash, &row));
}
#[cfg(unix)]
#[test]
fn disassembler_scratch_is_removed_on_success_failure_timeout_and_signal() {
+49
View File
@@ -0,0 +1,49 @@
use metal2vulkan_validation::normalize::normalize_air_identities;
use metal2vulkan_validation::source::corpus_root;
use std::path::PathBuf;
fn main() {
if let Err(error) = run() {
eprintln!("corpus-normalize: {error}");
std::process::exit(1);
}
}
fn run() -> Result<(), String> {
let mut root = corpus_root();
let mut apply = false;
let mut args = std::env::args().skip(1);
while let Some(arg) = args.next() {
match arg.as_str() {
"--corpus" => {
root = PathBuf::from(
args.next()
.ok_or_else(|| "--corpus requires a directory".to_string())?,
);
}
"--apply" => apply = true,
"-h" | "--help" => {
println!("usage: corpus-normalize [--corpus DIR] --apply");
return Ok(());
}
_ => return Err(format!("unknown argument {arg:?}")),
}
}
if !apply {
return Err("refusing to rewrite the corpus without explicit --apply".into());
}
let stats = normalize_air_identities(&root)?;
println!(
"normalized sources={}->{} modules={}->{} cases_rewritten={} cases_deduplicated={} reviews_superseded={} observations_invalidated={} observations_deduplicated={}",
stats.source_rows_before,
stats.source_rows_after,
stats.module_rows_before,
stats.module_rows_after,
stats.cases_rewritten,
stats.cases_deduplicated,
stats.reviews_superseded,
stats.observations_invalidated,
stats.observations_deduplicated,
);
Ok(())
}
@@ -812,7 +812,7 @@ mod tests {
entry: "main".into(),
air_ll: String::new(),
blob_b64: None,
lib_sha256: "22".repeat(32),
lib_sha256s: vec!["22".repeat(32)],
label: "local/x.ll".into(),
};
let proposal = ProposalResponse {
@@ -826,6 +826,7 @@ mod tests {
stage: Stage::Kernel,
buffers: vec![],
argument_buffer_buffers: vec![],
device_buffer_arrays: vec![],
threadgroup_memory: vec![],
imageblock: None,
fragment_imageblock: None,
+26 -4
View File
@@ -104,23 +104,38 @@ fn run() -> Result<(), String> {
selected
};
eprintln!("# cases selected: {}", cases.len());
let mut failures = Vec::new();
for case in cases {
let case_id = case.case_id.clone();
let metal_started = Instant::now();
let metal = metal2vulkan_validation::metal::qualify_case(
let metal = match metal2vulkan_validation::metal::qualify_case(
&root,
case.clone(),
&metal_environment_id,
)?;
) {
Ok(metal) => metal,
Err(error) => {
eprintln!("case {case_id}: metal failed: {error}");
failures.push(format!("case {case_id}: Metal: {error}"));
continue;
}
};
let metal_elapsed = metal_started.elapsed();
let candidate_started = Instant::now();
let candidate = metal2vulkan_validation::candidate::execute_case(
let candidate = match metal2vulkan_validation::candidate::execute_case(
&root,
case,
Backend::Moltenvk,
&metal_environment_id,
&environment_id,
)?;
) {
Ok(candidate) => candidate,
Err(error) => {
eprintln!("case {case_id}: MoltenVK failed: {error}");
failures.push(format!("case {case_id}: MoltenVK: {error}"));
continue;
}
};
let candidate_elapsed = candidate_started.elapsed();
println!(
"{}\tmetal={}\tmoltenvk={:?}\tmetal_seconds={:.3}\tmoltenvk_seconds={:.3}",
@@ -139,6 +154,13 @@ fn run() -> Result<(), String> {
final_sync.source_shards_scanned,
final_sync.source_bytes_scanned
);
if !failures.is_empty() {
return Err(format!(
"{} case execution(s) failed; first: {}",
failures.len(),
failures[0]
));
}
Ok(())
}
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+444 -21
View File
@@ -18,6 +18,8 @@ pub struct AuthoredCase {
#[serde(default)]
pub argument_buffer_buffers: Vec<ArgumentBufferBufferResource>,
#[serde(default)]
pub device_buffer_arrays: Vec<DeviceBufferArrayResource>,
#[serde(default)]
pub threadgroup_memory: Vec<ThreadgroupMemoryResource>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub imageblock: Option<ImageblockResource>,
@@ -69,6 +71,65 @@ pub struct AuthoredCase {
pub authored_by: Option<String>,
}
#[cfg(test)]
pub(crate) const ATTACHMENTLESS_FRAGMENT_AIR: &str = r#"target datalayout = "e-p:64:64:64"
target triple = "air64-apple-macosx14.0.0"
define void @fragment_no_writes() {
ret void
}
!air.fragment = !{!0}
!0 = !{ptr @fragment_no_writes, !1, !2}
!1 = !{}
!2 = !{}
"#;
#[cfg(test)]
pub(crate) fn attachmentless_fragment_test_case(air_sha256: String, entry: String) -> AuthoredCase {
AuthoredCase {
air_sha256,
case_id: "test-attachmentless-fragment".into(),
name: "attachmentless-fragment-smoke".into(),
entry,
stage: Stage::Fragment,
buffers: vec![],
argument_buffer_buffers: vec![],
device_buffer_arrays: vec![],
threadgroup_memory: vec![],
imageblock: None,
fragment_imageblock: None,
acceleration_structures: vec![],
visible_function_references: vec![],
visible_function_tables: vec![],
intersection_function_tables: vec![],
argument_buffer_intersection_function_tables: vec![],
textures: vec![],
texture_arrays: vec![],
argument_buffer_textures: vec![],
samplers: vec![],
render_targets: vec![],
depth_stencil: None,
vertex_inputs: vec![],
vertex_observation: None,
kernel_stage_inputs: vec![],
function_constants: vec![],
dispatch: None,
draw: Some(Draw {
primitive: Primitive::Triangle,
vertex_start: 0,
vertex_count: 3,
instance_count: 1,
}),
tessellation: None,
output: OutputSelection::None,
compare: Comparison::Exact,
execution_safety: ExecutionSafety::LoopFree,
rationale: None,
authored_by: Some("codex:gpt-5.6-sol".into()),
}
}
#[cfg(test)]
pub(crate) fn combined_depth_stencil_test_case(air_sha256: String, entry: String) -> AuthoredCase {
AuthoredCase {
@@ -79,6 +140,7 @@ pub(crate) fn combined_depth_stencil_test_case(air_sha256: String, entry: String
stage: Stage::Fragment,
buffers: vec![],
argument_buffer_buffers: vec![],
device_buffer_arrays: vec![],
threadgroup_memory: vec![],
imageblock: None,
fragment_imageblock: None,
@@ -138,6 +200,7 @@ pub(crate) fn vector_function_constant_test_case(
initial_bytes_b64: Some("q6urqw==".into()),
}],
argument_buffer_buffers: vec![],
device_buffer_arrays: vec![],
threadgroup_memory: vec![],
imageblock: None,
fragment_imageblock: None,
@@ -192,6 +255,7 @@ pub(crate) fn narrow_implicit_imageblock_test_case(
stage: Stage::Kernel,
buffers: vec![],
argument_buffer_buffers: vec![],
device_buffer_arrays: vec![],
threadgroup_memory: vec![],
imageblock: Some(ImageblockResource {
dimensions: [16, 16],
@@ -248,6 +312,7 @@ pub(crate) fn fragment_imageblock_test_case(air_sha256: String, entry: String) -
stage: Stage::Fragment,
buffers: vec![],
argument_buffer_buffers: vec![],
device_buffer_arrays: vec![],
threadgroup_memory: vec![],
imageblock: None,
fragment_imageblock: Some(FragmentImageblockResource {
@@ -359,11 +424,33 @@ pub struct ArgumentBufferBufferResource {
pub initial_bytes_b64: Option<String>,
}
/// A top-level AIR `array_ref<void>` whose backing allocation contains GPU addresses of separately
/// owned device buffers. Slots may be sparse; every undeclared slot is encoded as a null address.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct DeviceBufferArrayResource {
pub binding: u32,
pub length: u32,
pub elements: Vec<DeviceBufferArrayElementResource>,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct DeviceBufferArrayElementResource {
pub index: u32,
pub role: ResourceRole,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub bytes_b64: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub initial_bytes_b64: Option<String>,
}
/// A dynamically sized Metal `threadgroup` buffer argument.
///
/// It occupies the Metal buffer-index namespace but is emitted as descriptor-free Vulkan
/// `Workgroup` storage. Contents are deliberately not authorable: both APIs leave this memory
/// uninitialized, so a meaningful case must initialize every byte it reads in the shader.
/// Its Metal `[[threadgroup(n)]]` index is distinct from `[[buffer(n)]]`; Vulkan emits it as
/// descriptor-free `Workgroup` storage. Contents are deliberately not authorable: both APIs leave
/// this memory uninitialized, so a meaningful case must initialize every byte it reads in the
/// shader.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct ThreadgroupMemoryResource {
@@ -639,6 +726,11 @@ pub struct TextureArrayResource {
pub format: TextureFormat,
#[serde(default = "default_one", skip_serializing_if = "is_one")]
pub sample_count: u32,
/// The specialized fixed-array path owns the base Metal texture slot shared with its layered
/// alternative. Metal binds texture arrays after direct textures, so this declaration makes
/// that otherwise ambiguous overwrite explicit and validated.
#[serde(default, skip_serializing_if = "is_false")]
pub overrides_texture_at_base: bool,
pub elements: Vec<TextureArrayElement>,
}
@@ -675,6 +767,20 @@ const fn is_one(value: &u32) -> bool {
*value == 1
}
const fn is_false(value: &bool) -> bool {
!*value
}
const fn texture_type_is_array_alternative(arrayed: TextureType, element: TextureType) -> bool {
matches!(
(arrayed, element),
(TextureType::D1Array, TextureType::D1)
| (TextureType::D2Array, TextureType::D2)
| (TextureType::D2MultisampleArray, TextureType::D2Multisample)
| (TextureType::CubeArray, TextureType::Cube)
)
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum TextureFormat {
@@ -685,6 +791,7 @@ pub enum TextureFormat {
R16Float,
R16Uint,
Rg16Float,
Rg32Float,
Rgba16Float,
Rgba16Uint,
R32Uint,
@@ -708,6 +815,7 @@ impl TextureFormat {
| Self::R32Sint
| Self::R32Float => 4,
Self::Rg16Float => 4,
Self::Rg32Float => 8,
Self::Rgba16Float | Self::Rgba16Uint => 8,
Self::Rgba32Uint | Self::Rgba32Sint | Self::Rgba32Float => 16,
Self::Depth32Float => 4,
@@ -728,6 +836,7 @@ impl TextureFormat {
Self::R16Float => RuntimeStorageImageFormat::R16Float,
Self::R16Uint => RuntimeStorageImageFormat::R16Uint,
Self::Rg16Float => RuntimeStorageImageFormat::Rg16Float,
Self::Rg32Float => RuntimeStorageImageFormat::Rg32Float,
Self::Rgba16Float => RuntimeStorageImageFormat::Rgba16Float,
Self::Rgba16Uint => RuntimeStorageImageFormat::Rgba16Uint,
Self::R32Uint => RuntimeStorageImageFormat::R32Uint,
@@ -848,7 +957,7 @@ pub(crate) fn product_transform_options(
Ok(options)
}
pub(crate) fn product_transform_options_with_reflection(
pub fn product_transform_options_with_reflection(
case: &AuthoredCase,
reflection: &metal2vulkan::reflect::ShaderReflection,
) -> Result<metal2vulkan::passes::TransformOptions, String> {
@@ -1238,6 +1347,9 @@ pub enum Primitive {
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
pub enum OutputSelection {
/// Execute the entry and compare the exact empty byte sequence. The shared checker accepts this
/// only when reflection exposes no writable observable output.
None,
Buffer {
binding: u32,
offset: u64,
@@ -1249,6 +1361,12 @@ pub enum OutputSelection {
offset: u64,
length: u64,
},
DeviceBufferArrayElement {
binding: u32,
element: u32,
offset: u64,
length: u64,
},
Texture {
binding: u32,
origin: [u32; 3],
@@ -1318,6 +1436,8 @@ struct SemanticCase<'a> {
#[serde(skip_serializing_if = "Vec::is_empty")]
argument_buffer_buffers: Vec<&'a ArgumentBufferBufferResource>,
#[serde(skip_serializing_if = "Vec::is_empty")]
device_buffer_arrays: Vec<&'a DeviceBufferArrayResource>,
#[serde(skip_serializing_if = "Vec::is_empty")]
threadgroup_memory: Vec<&'a ThreadgroupMemoryResource>,
#[serde(skip_serializing_if = "Option::is_none")]
imageblock: &'a Option<ImageblockResource>,
@@ -1372,6 +1492,9 @@ impl AuthoredCase {
argument_buffer_buffers: sorted_refs(&self.argument_buffer_buffers, |resource| {
(resource.buffer_binding, resource.field_offset)
}),
device_buffer_arrays: sorted_refs(&self.device_buffer_arrays, |resource| {
resource.binding
}),
threadgroup_memory: sorted_refs(&self.threadgroup_memory, |resource| resource.binding),
imageblock: &self.imageblock,
fragment_imageblock: &self.fragment_imageblock,
@@ -1430,6 +1553,8 @@ impl AuthoredCase {
#[serde(skip_serializing_if = "Vec::is_empty")]
argument_buffer_buffers: Vec<&'a ArgumentBufferBufferResource>,
#[serde(skip_serializing_if = "Vec::is_empty")]
device_buffer_arrays: Vec<&'a DeviceBufferArrayResource>,
#[serde(skip_serializing_if = "Vec::is_empty")]
threadgroup_memory: Vec<&'a ThreadgroupMemoryResource>,
#[serde(skip_serializing_if = "Option::is_none")]
imageblock: &'a Option<ImageblockResource>,
@@ -1473,6 +1598,9 @@ impl AuthoredCase {
argument_buffer_buffers: sorted_refs(&self.argument_buffer_buffers, |resource| {
(resource.buffer_binding, resource.field_offset)
}),
device_buffer_arrays: sorted_refs(&self.device_buffer_arrays, |resource| {
resource.binding
}),
threadgroup_memory: sorted_refs(&self.threadgroup_memory, |resource| resource.binding),
imageblock: &self.imageblock,
fragment_imageblock: &self.fragment_imageblock,
@@ -1705,6 +1833,86 @@ impl AuthoredCase {
&mut errors,
);
}
let mut device_buffer_array_bindings = HashSet::new();
let mut device_buffer_array_ranges = Vec::<(u64, u64)>::new();
for array in &self.device_buffer_arrays {
if !device_buffer_array_bindings.insert(array.binding) {
errors.push(format!(
"duplicate device-buffer-array binding {}",
array.binding
));
}
if array.length == 0 {
errors.push(format!(
"device-buffer-array binding {} length must be nonzero",
array.binding
));
}
let start = u64::from(array.binding);
let end = start + u64::from(array.length);
if end > u64::from(u32::MAX) + 1 {
errors.push(format!(
"device-buffer-array binding {} length {} overflows the Metal buffer-index namespace",
array.binding, array.length
));
}
if buffer_bindings
.iter()
.any(|binding| (start..end).contains(&u64::from(*binding)))
{
errors.push(format!(
"device-buffer-array binding {} length {} overlaps a buffer binding",
array.binding, array.length
));
}
if device_buffer_array_ranges
.iter()
.any(|(other_start, other_end)| start < *other_end && *other_start < end)
{
errors.push(format!(
"device-buffer-array binding {} length {} overlaps another device-buffer array",
array.binding, array.length
));
}
device_buffer_array_ranges.push((start, end));
let mut previous = None;
for element in &array.elements {
if element.index >= array.length {
errors.push(format!(
"device-buffer-array binding {} element {} exceeds length {}",
array.binding, element.index, array.length
));
}
if previous.is_some_and(|index| element.index <= index) {
errors.push(format!(
"device-buffer-array binding {} elements must be sorted and unique by index",
array.binding
));
}
previous = Some(element.index);
validate_role_bytes(
&format!(
"device-buffer-array binding {} element {}",
array.binding, element.index
),
element.role,
element.bytes_b64.as_deref(),
element.initial_bytes_b64.as_deref(),
&mut errors,
);
}
if array.elements.is_empty() {
errors.push(format!(
"device-buffer-array binding {} must declare at least one element",
array.binding
));
}
}
let device_buffer_array_owns = |binding: u32| {
device_buffer_array_ranges
.iter()
.any(|(start, end)| (*start..*end).contains(&u64::from(binding)))
};
let mut argument_buffer_buffer_keys = HashSet::new();
for buffer in &self.argument_buffer_buffers {
let key = (buffer.buffer_binding, buffer.field_offset);
@@ -1746,12 +1954,6 @@ impl AuthoredCase {
resource.binding
));
}
if buffer_bindings.contains(&resource.binding) {
errors.push(format!(
"binding {} is declared as both a buffer and threadgroup memory",
resource.binding
));
}
}
for resource in &self.acceleration_structures {
if !acceleration_structure_bindings.insert(resource.binding) {
@@ -1766,9 +1968,9 @@ impl AuthoredCase {
resource.binding
));
}
if threadgroup_bindings.contains(&resource.binding) {
if device_buffer_array_owns(resource.binding) {
errors.push(format!(
"binding {} is declared as both threadgroup memory and an acceleration structure",
"binding {} is declared as both a device-buffer-array slot and an acceleration structure",
resource.binding
));
}
@@ -1828,14 +2030,14 @@ impl AuthoredCase {
}
for (other, occupied) in [
("buffer", buffer_bindings.contains(&table.binding)),
(
"threadgroup memory",
threadgroup_bindings.contains(&table.binding),
),
(
"acceleration structure",
acceleration_structure_bindings.contains(&table.binding),
),
(
"device-buffer-array slot",
device_buffer_array_owns(table.binding),
),
] {
if occupied {
errors.push(format!(
@@ -1891,14 +2093,14 @@ impl AuthoredCase {
}
for (other, occupied) in [
("buffer", buffer_bindings.contains(&table.binding)),
(
"threadgroup memory",
threadgroup_bindings.contains(&table.binding),
),
(
"acceleration structure",
acceleration_structure_bindings.contains(&table.binding),
),
(
"device-buffer-array slot",
device_buffer_array_owns(table.binding),
),
] {
if occupied {
errors.push(format!(
@@ -2067,13 +2269,45 @@ impl AuthoredCase {
));
break;
};
if !texture_bindings.insert(slot) {
let function_constant_texture_alternative = element == 0
&& array.overrides_texture_at_base
&& !self.function_constants.is_empty()
&& self.textures.iter().any(|texture| {
texture.binding == array.binding
&& texture.role == ResourceRole::Input
&& array.role == ResourceRole::Input
&& texture.format == array.format
&& texture.sample_count == array.sample_count
&& texture_type_is_array_alternative(
texture.texture_type,
array.texture_type,
)
});
if !texture_bindings.insert(slot) && !function_constant_texture_alternative {
errors.push(format!(
"texture-array binding {} element {element} overlaps Metal texture slot {slot}",
array.binding
));
}
}
if array.overrides_texture_at_base
&& !self.textures.iter().any(|texture| {
texture.binding == array.binding
&& texture.role == ResourceRole::Input
&& array.role == ResourceRole::Input
&& texture.format == array.format
&& texture.sample_count == array.sample_count
&& texture_type_is_array_alternative(
texture.texture_type,
array.texture_type,
)
})
{
errors.push(format!(
"texture-array binding {} overrides_texture_at_base requires a matching input-only layered texture alternative",
array.binding
));
}
if array.elements.len()
> metal2vulkan::meta::TEXTURE_HANDLE_ARRAY_DESCRIPTOR_COUNT as usize
{
@@ -2361,6 +2595,7 @@ impl AuthoredCase {
fn validate_output_selection(&self, errors: &mut Vec<String>) {
match &self.output {
OutputSelection::None => {}
OutputSelection::Buffer {
binding,
offset,
@@ -2418,6 +2653,44 @@ impl AuthoredCase {
errors.push("argument-buffer buffer output range overflows".into());
}
}
OutputSelection::DeviceBufferArrayElement {
binding,
element,
offset,
length,
} => {
let Some(resource) = self
.device_buffer_arrays
.iter()
.find(|item| item.binding == *binding)
.and_then(|array| array.elements.iter().find(|item| item.index == *element))
else {
errors.push(format!(
"device-buffer-array output binding {binding} element {element} is not declared"
));
return;
};
if resource.role == ResourceRole::Input {
errors.push(format!(
"device-buffer-array output binding {binding} element {element} has input-only role"
));
}
if *length == 0 {
errors.push("device-buffer-array output length must be nonzero".into());
}
if let Some(bytes) = initial_bytes(
resource.bytes_b64.as_deref(),
resource.initial_bytes_b64.as_deref(),
) {
if offset.saturating_add(*length) > bytes.len() as u64 {
errors.push(format!(
"device-buffer-array output [{offset}, {}) exceeds binding {binding} element {element} length {}",
offset.saturating_add(*length),
bytes.len()
));
}
}
}
OutputSelection::Texture {
binding,
origin,
@@ -2838,6 +3111,7 @@ mod tests {
initial_bytes_b64: Some("q6urqw==".into()),
}],
argument_buffer_buffers: vec![],
device_buffer_arrays: vec![],
threadgroup_memory: vec![],
imageblock: None,
fragment_imageblock: None,
@@ -2905,6 +3179,93 @@ mod tests {
assert!(error.contains("mixed min/mag"), "{error}");
}
#[test]
fn device_buffer_array_elements_are_sparse_bounded_literal_resources() {
let mut case = example();
case.case_id = "00".repeat(32);
case.buffers.clear();
case.device_buffer_arrays.push(DeviceBufferArrayResource {
binding: 0,
length: 3,
elements: vec![
DeviceBufferArrayElementResource {
index: 0,
role: ResourceRole::Input,
bytes_b64: Some("AQAAAA==".into()),
initial_bytes_b64: None,
},
DeviceBufferArrayElementResource {
index: 2,
role: ResourceRole::Output,
bytes_b64: None,
initial_bytes_b64: Some("q6urqw==".into()),
},
],
});
case.output = OutputSelection::DeviceBufferArrayElement {
binding: 0,
element: 2,
offset: 0,
length: 4,
};
assert_eq!(case.validate_literal_resources(), Ok(()));
case.threadgroup_memory.push(ThreadgroupMemoryResource {
binding: 0,
length: 8,
});
assert_eq!(case.validate_literal_resources(), Ok(()));
case.device_buffer_arrays[0].elements[1].index = 3;
assert!(case
.validate_literal_resources()
.unwrap_err()
.iter()
.any(|error| error.contains("exceeds length 3")));
case.device_buffer_arrays[0].elements[1].index = 2;
case.buffers.push(BufferResource {
binding: 1,
role: ResourceRole::Input,
bytes_b64: Some("AQAAAA==".into()),
initial_bytes_b64: None,
});
assert!(case
.validate_literal_resources()
.unwrap_err()
.iter()
.any(|error| error.contains("overlaps a buffer binding")));
case.buffers.clear();
case.device_buffer_arrays.push(DeviceBufferArrayResource {
binding: 2,
length: 1,
elements: vec![DeviceBufferArrayElementResource {
index: 0,
role: ResourceRole::Input,
bytes_b64: Some("AQAAAA==".into()),
initial_bytes_b64: None,
}],
});
assert!(case
.validate_literal_resources()
.unwrap_err()
.iter()
.any(|error| error.contains("overlaps another device-buffer array")));
}
#[test]
fn rg32_float_has_exact_literal_and_product_format_contracts() {
assert_eq!(TextureFormat::Rg32Float.bytes_per_pixel(), 8);
let state = TextureFormat::Rg32Float
.runtime_storage_specialization()
.unwrap();
assert_eq!(
state.format,
metal2vulkan::reflect::RuntimeStorageImageFormat::Rg32Float
);
assert!(!state.capabilities.storage_image_atomic);
}
#[test]
fn authored_storage_texture_format_is_the_product_specialization_input() {
let mut case = example();
@@ -2924,6 +3285,7 @@ mod tests {
texture_type: TextureType::D2,
format: TextureFormat::R32Uint,
sample_count: 1,
overrides_texture_at_base: false,
elements: vec![TextureArrayElement {
dimensions: [1, 1, 1],
bytes_b64: None,
@@ -3484,6 +3846,7 @@ declare void @air.write_texture_2d.v4f32(ptr addrspace(1), <2 x i32>, <4 x float
texture_type: TextureType::D2,
format: TextureFormat::R32Uint,
sample_count: 1,
overrides_texture_at_base: false,
elements: vec![
TextureArrayElement {
dimensions: [1, 1, 1],
@@ -3517,6 +3880,66 @@ declare void @air.write_texture_2d.v4f32(ptr addrspace(1), <2 x i32>, <4 x float
assert!(errors.contains("overlaps Metal texture slot 5"), "{errors}");
}
#[test]
fn function_constant_layered_and_fixed_texture_alternatives_may_share_the_base_slot() {
let mut case = example();
case.function_constants.push(FunctionConstant {
index: 0,
scalar_type: ScalarType::U32,
lanes: 1,
bytes_b64: "AAAAAA==".into(),
});
case.textures.push(TextureResource {
binding: 0,
role: ResourceRole::Input,
texture_type: TextureType::D2Array,
format: TextureFormat::R32Uint,
dimensions: [1, 1, 1],
sample_count: 1,
bytes_b64: Some("BwAAAA==".into()),
initial_bytes_b64: None,
});
case.texture_arrays.push(TextureArrayResource {
binding: 0,
role: ResourceRole::Input,
texture_type: TextureType::D2,
format: TextureFormat::R32Uint,
sample_count: 1,
overrides_texture_at_base: true,
elements: vec![TextureArrayElement {
dimensions: [1, 1, 1],
bytes_b64: Some("BwAAAA==".into()),
initial_bytes_b64: None,
}],
});
case.case_id = case.computed_case_id().unwrap();
case.validate_literal_resources().unwrap();
let resources = crate::literal::LiteralResources::prepare(&case).unwrap();
assert!(resources.texture_arrays[0].overrides_texture_at_base);
case.function_constants.clear();
case.case_id = case.computed_case_id().unwrap();
let errors = case.validate_literal_resources().unwrap_err().join("\n");
assert!(errors.contains("overlaps Metal texture slot 0"), "{errors}");
case.function_constants.push(FunctionConstant {
index: 0,
scalar_type: ScalarType::U32,
lanes: 1,
bytes_b64: "AAAAAA==".into(),
});
case.textures.clear();
case.case_id = case.computed_case_id().unwrap();
let errors = case.validate_literal_resources().unwrap_err().join("\n");
assert!(
errors.contains(
"overrides_texture_at_base requires a matching input-only layered texture alternative"
),
"{errors}"
);
}
#[test]
fn multisample_array_literals_keep_layers_and_samples_independent() {
use base64::Engine as _;
+523 -37
View File
@@ -1,6 +1,6 @@
use crate::case::{
AccelerationStructureKind, AuthoredCase, ExecutionSafety, ResourceRole, Stage, TextureFormat,
TextureType, VertexObservation,
AccelerationStructureKind, AuthoredCase, ExecutionSafety, OutputSelection, ResourceRole, Stage,
TextureFormat, TextureType, VertexObservation,
};
use crate::library_module::ResolvedLinkedFunctions;
use crate::source::{find_source, SourceRow};
@@ -17,7 +17,54 @@ pub struct CheckedCase {
pub input_sha256: String,
}
pub struct CheckedCaseContract {
pub case: AuthoredCase,
pub reflection: ShaderReflection,
pub linked_functions: ResolvedLinkedFunctions,
pub input_sha256: String,
}
pub fn check_case(root: &Path, case: AuthoredCase) -> Result<CheckedCase, Vec<String>> {
let (mut errors, input_sha256) = check_case_identity(&case);
let source = match find_source(root, &case.air_sha256) {
Ok(Some(source)) => source,
Ok(None) => {
errors.push(format!(
"AIR {} does not exist in aligned source shards or public fixtures",
case.air_sha256
));
return Err(errors);
}
Err(error) => {
errors.push(error);
return Err(errors);
}
};
let checked =
check_case_against_source_with_identity(root, case, &source, errors, input_sha256)?;
Ok(CheckedCase {
case: checked.case,
source,
reflection: checked.reflection,
linked_functions: checked.linked_functions,
input_sha256: checked.input_sha256,
})
}
/// Check an authored case against an already selected exact AIR row.
///
/// Translation workers use this boundary so case validation does not reopen or rescan a source
/// shard after the indexed row has already been handed to the isolated worker.
pub fn check_case_against_source(
root: &Path,
case: AuthoredCase,
source: &SourceRow,
) -> Result<CheckedCaseContract, Vec<String>> {
let (errors, input_sha256) = check_case_identity(&case);
check_case_against_source_with_identity(root, case, source, errors, input_sha256)
}
fn check_case_identity(case: &AuthoredCase) -> (Vec<String>, String) {
let mut errors = case.validate_literal_resources().err().unwrap_or_default();
match case.computed_case_id() {
Ok(computed) if computed != case.case_id => errors.push(format!(
@@ -34,20 +81,16 @@ pub fn check_case(root: &Path, case: AuthoredCase) -> Result<CheckedCase, Vec<St
String::new()
}
};
let source = match find_source(root, &case.air_sha256) {
Ok(Some(source)) => source,
Ok(None) => {
errors.push(format!(
"AIR {} does not exist in aligned source shards or public fixtures",
case.air_sha256
));
return Err(errors);
}
Err(error) => {
errors.push(error);
return Err(errors);
}
};
(errors, input_sha256)
}
fn check_case_against_source_with_identity(
root: &Path,
case: AuthoredCase,
source: &SourceRow,
mut errors: Vec<String>,
input_sha256: String,
) -> Result<CheckedCaseContract, Vec<String>> {
if source.air_sha256 != case.air_sha256 {
errors.push(format!(
"AIR hash mismatch: case={} source={}",
@@ -79,17 +122,16 @@ pub fn check_case(root: &Path, case: AuthoredCase) -> Result<CheckedCase, Vec<St
));
}
}
let linked_functions =
match crate::library_module::resolve_linked_functions(root, &case, &source.lib_sha256) {
Ok(tables) => tables,
Err(table_errors) => {
errors.extend(table_errors);
ResolvedLinkedFunctions::default()
}
};
let linked_functions = match crate::library_module::resolve_linked_functions(root, &case) {
Ok(tables) => tables,
Err(table_errors) => {
errors.extend(table_errors);
ResolvedLinkedFunctions::default()
}
};
validate_visible_reference_closure(&source.air_ll, &linked_functions, &mut errors);
let reflection = match reflect(&source.air_ll, &case) {
let reflection = match reflect(&source.air_ll, &case, &linked_functions) {
Ok(reflection) => reflection,
Err(error) => {
errors.push(format!("product reflection failed: {error}"));
@@ -106,9 +148,8 @@ pub fn check_case(root: &Path, case: AuthoredCase) -> Result<CheckedCase, Vec<St
}
validate_reflection(&case, &reflection, &mut errors);
if errors.is_empty() {
Ok(CheckedCase {
Ok(CheckedCaseContract {
case,
source,
reflection,
linked_functions,
input_sha256,
@@ -165,6 +206,169 @@ fn validate_visible_reference_closure(
}
}
/// Build the exact product linkage described by checked authored resources and reflection.
///
/// Both candidate execution and translation audits use this mapping so table bindings, embedded
/// table fields, linked callbacks, and opaque intersection entries cannot drift between paths.
pub fn product_linkage(
reflection: &ShaderReflection,
linked: &ResolvedLinkedFunctions,
) -> Result<metal2vulkan::linked_functions::LinkedFunctionLinkage, String> {
fn linked_tables(
reflection: &ShaderReflection,
tables: &[crate::library_module::ResolvedFunctionTable],
kind: ResourceKind,
label: &str,
) -> Result<Vec<metal2vulkan::linked_functions::LinkedFunctionTable>, String> {
tables
.iter()
.map(|table| {
let parameter_index = reflection
.bindings
.iter()
.find(|binding| binding.kind == kind && binding.metal_index == table.binding)
.and_then(|binding| binding.param_index)
.ok_or_else(|| {
format!(
"{label} function table binding {} has no reflected entry parameter",
table.binding,
)
})?;
Ok(metal2vulkan::linked_functions::LinkedFunctionTable {
parameter_index,
size: table.size,
entries: table
.entries
.iter()
.map(|entry| metal2vulkan::linked_functions::LinkedFunction {
index: entry.index,
symbol: entry.function.clone(),
module_ll: entry.module.air_ll.clone(),
})
.collect(),
})
})
.collect()
}
let visible_tables = linked_tables(
reflection,
&linked.visible,
ResourceKind::VisibleFunctionTable,
"visible",
)?;
let intersection_tables = linked
.intersection
.iter()
.map(|table| {
let source = match table.location {
crate::library_module::ResolvedIntersectionFunctionTableLocation::Direct {
binding: table_binding,
} => {
let parameter_index = reflection
.bindings
.iter()
.find(|binding| {
binding.kind == ResourceKind::IntersectionFunctionTable
&& binding.metal_index == table_binding
})
.and_then(|binding| binding.param_index)
.ok_or_else(|| {
format!(
"intersection function table binding {table_binding} has no reflected entry parameter"
)
})?;
metal2vulkan::linked_functions::IntersectionFunctionTableSource::Parameter {
parameter_index,
}
}
crate::library_module::ResolvedIntersectionFunctionTableLocation::ArgumentBuffer {
buffer_binding,
field_offset,
} => {
let field = reflection
.argument_buffer_fields
.iter()
.find(|field| {
field.buffer_index == buffer_binding
&& field.field_offset == field_offset
})
.ok_or_else(|| {
format!(
"argument-buffer intersection function table at buffer {buffer_binding} offset {field_offset} has no reflected field"
)
})?;
metal2vulkan::linked_functions::IntersectionFunctionTableSource::ArgumentBuffer {
buffer_parameter_index: field.buffer_param_index,
field_ordinal: field.field_ordinal,
field_offset,
}
}
};
let entries = table
.entries
.iter()
.map(|entry| match entry {
crate::library_module::ResolvedIntersectionFunctionEntry::Linked(entry) => {
metal2vulkan::linked_functions::IntersectionFunctionEntry::Linked(
metal2vulkan::linked_functions::LinkedFunction {
index: entry.index,
symbol: entry.function.clone(),
module_ll: entry.module.air_ll.clone(),
},
)
}
crate::library_module::ResolvedIntersectionFunctionEntry::OpaqueTriangle {
index,
signature,
} => {
use crate::case::IntersectionFunctionSignature as Source;
use metal2vulkan::linked_functions::IntersectionFunctionSignature as Target;
metal2vulkan::linked_functions::IntersectionFunctionEntry::OpaqueTriangle {
index: *index,
signature: signature
.iter()
.map(|flag| match flag {
Source::Instancing => Target::Instancing,
Source::TriangleData => Target::TriangleData,
Source::WorldSpaceData => Target::WorldSpaceData,
Source::InstanceMotion => Target::InstanceMotion,
Source::PrimitiveMotion => Target::PrimitiveMotion,
Source::ExtendedLimits => Target::ExtendedLimits,
Source::MaxLevels => Target::MaxLevels,
Source::IntersectionFunctionBuffer => {
Target::IntersectionFunctionBuffer
}
Source::UserData => Target::UserData,
})
.collect(),
}
}
})
.collect();
Ok(metal2vulkan::linked_functions::IntersectionFunctionTable {
source,
size: table.size,
entries,
})
})
.collect::<Result<Vec<_>, String>>()?;
let visible_references = linked
.references
.iter()
.map(
|reference| metal2vulkan::linked_functions::LinkedFunctionReference {
symbol: reference.function.clone(),
module_ll: reference.module.air_ll.clone(),
},
)
.collect();
Ok(metal2vulkan::linked_functions::LinkedFunctionLinkage {
visible_references,
visible_tables,
intersection_tables,
})
}
fn validate_execution_safety(safety: ExecutionSafety, ll: &str, errors: &mut Vec<String>) {
if has_cfg_cycle(ll) && safety == ExecutionSafety::LoopFree {
errors.push(
@@ -174,16 +378,36 @@ fn validate_execution_safety(safety: ExecutionSafety, ll: &str, errors: &mut Vec
}
}
fn reflect(air_ll: &str, case: &AuthoredCase) -> Result<ShaderReflection, String> {
let unspecialized = metal2vulkan::reflect_sanitized(
fn reflect(
air_ll: &str,
case: &AuthoredCase,
linked: &ResolvedLinkedFunctions,
) -> Result<ShaderReflection, String> {
let function_constants = crate::literal::function_constants(case)?
.into_iter()
.map(|constant| (constant.index, constant.bytes))
.collect::<Vec<_>>();
let initial = metal2vulkan::reflect_sanitized_specialized(
air_ll,
case.stage.product(),
crate::case::product_transform_options(case)?,
&function_constants,
)?;
metal2vulkan::reflect_sanitized(
air_ll,
let linkage = product_linkage(&initial, linked)?;
let linked_air = if linkage.is_empty() {
std::borrow::Cow::Borrowed(air_ll)
} else {
std::borrow::Cow::Owned(metal2vulkan::specialize_linked_module(
air_ll,
case.stage.product(),
&linkage,
)?)
};
metal2vulkan::reflect_sanitized_specialized(
linked_air.as_ref(),
case.stage.product(),
crate::case::product_transform_options_with_reflection(case, &unspecialized)?,
crate::case::product_transform_options_with_reflection(case, &initial)?,
&function_constants,
)
}
@@ -203,8 +427,35 @@ fn validate_reflection(
.buffers
.iter()
.map(|buffer| buffer.binding)
.chain(case.device_buffer_arrays.iter().map(|array| array.binding))
.collect::<HashSet<_>>();
report_set_difference("buffer", &reflected_buffers, &manifest_buffers, errors);
for binding in reflection
.bindings
.iter()
.filter(|binding| binding.kind == ResourceKind::Buffer)
{
let is_array = binding
.type_name
.as_deref()
.is_some_and(metal2vulkan::meta::is_device_buffer_array_type_name);
let authored_as_array = case
.device_buffer_arrays
.iter()
.any(|array| array.binding == binding.metal_index);
if is_array != authored_as_array {
errors.push(format!(
"buffer {} {} a device-buffer array in AIR metadata, but the manifest {}",
binding.metal_index,
if is_array { "is" } else { "is not" },
if authored_as_array {
"authors it as one"
} else {
"does not author it as one"
}
));
}
}
let reflected_argument_buffer_buffers = reflection
.bindings
@@ -346,6 +597,9 @@ fn validate_reflection(
}
validate_implicit_imageblock_attachments(case, reflection, errors);
validate_fragment_imageblock(case, reflection, errors);
if !selected_output_is_reflected_writable(case, reflection) {
errors.push("selected output is not reflected as shader-writable".into());
}
let reflected_acceleration_structures = reflection
.bindings
@@ -447,6 +701,16 @@ fn validate_reflection(
let manifest_textures = case
.textures
.iter()
.filter(|texture| {
!case.texture_arrays.iter().any(|array| {
array.overrides_texture_at_base
&& array.binding == texture.binding
&& reflection.bindings.iter().any(|binding| {
binding.kind == ResourceKind::TextureArray
&& binding.metal_index == array.binding
})
})
})
.map(|texture| texture.binding)
.collect::<HashSet<_>>();
report_set_difference("texture", &reflected_textures, &manifest_textures, errors);
@@ -483,6 +747,15 @@ fn validate_reflection(
let manifest_texture_arrays = case
.texture_arrays
.iter()
.filter(|array| {
!(array.overrides_texture_at_base
&& reflection.bindings.iter().any(|binding| {
matches!(
binding.kind,
ResourceKind::Texture | ResourceKind::StorageImage
) && binding.metal_index == array.binding
}))
})
.map(|texture| texture.binding)
.collect::<HashSet<_>>();
report_set_difference(
@@ -788,6 +1061,124 @@ fn validate_reflection(
validate_vertex_observation(case, reflection, errors);
}
fn selected_output_is_reflected_writable(
case: &AuthoredCase,
reflection: &ShaderReflection,
) -> bool {
use metal2vulkan::reflect::ResourceAccess;
let writable = |access: Option<ResourceAccess>| {
!matches!(
access,
Some(ResourceAccess::Unused | ResourceAccess::ReadOnly | ResourceAccess::Sampled)
)
};
match &case.output {
OutputSelection::None => {
!reflection.bindings.iter().any(|binding| {
matches!(
binding.kind,
ResourceKind::Buffer
| ResourceKind::StorageImage
| ResourceKind::TextureArray
| ResourceKind::EmbeddedArgBufferBuffer
| ResourceKind::EmbeddedArgBufferTexture
) && writable(binding.access)
}) && reflection.render_targets.is_empty()
&& reflection.depth_members.is_empty()
&& reflection.stencil_members.is_empty()
&& !reflection
.implicit_imageblock_attachments
.iter()
.any(|attachment| writable(Some(attachment.access)))
&& !reflection
.fragment_imageblock
.as_ref()
.is_some_and(|imageblock| {
imageblock
.members
.iter()
.any(|member| member.binding.is_some() && writable(Some(member.access)))
})
&& !(case.stage == Stage::Vertex
&& (reflection
.vertex_builtins
.is_some_and(|builtins| builtins.writes_position)
|| !reflection.varyings.is_empty()))
}
OutputSelection::Buffer { binding, .. } => reflection.bindings.iter().any(|reflected| {
reflected.kind == ResourceKind::Buffer
&& reflected.metal_index == *binding
&& writable(reflected.access)
}),
OutputSelection::ArgumentBufferBuffer {
buffer_binding,
field_offset,
..
} => reflection.bindings.iter().any(|reflected| {
reflected.kind == ResourceKind::EmbeddedArgBufferBuffer
&& reflected.embedded_source.is_some_and(|source| {
source.buffer_index == *buffer_binding && source.field_offset == *field_offset
})
&& writable(reflected.access)
}),
OutputSelection::DeviceBufferArrayElement { binding, .. } => {
reflection.bindings.iter().any(|reflected| {
reflected.kind == ResourceKind::Buffer
&& reflected.metal_index == *binding
&& writable(reflected.access)
})
}
OutputSelection::Texture { binding, .. }
| OutputSelection::TextureArrayElement { binding, .. } => {
reflection.bindings.iter().any(|reflected| {
reflected.metal_index == *binding
&& matches!(
reflected.kind,
ResourceKind::StorageImage | ResourceKind::TextureArray
)
&& writable(reflected.access)
})
}
OutputSelection::ArgumentBufferTexture {
buffer_binding,
field_offset,
..
} => reflection.bindings.iter().any(|reflected| {
reflected.kind == ResourceKind::EmbeddedArgBufferTexture
&& reflected.embedded_source.is_some_and(|source| {
source.buffer_index == *buffer_binding && source.field_offset == *field_offset
})
&& writable(reflected.access)
}),
OutputSelection::RenderTarget { index, .. } => {
reflection
.render_targets
.iter()
.any(|target| target.location == *index)
|| reflection
.implicit_imageblock_attachments
.iter()
.any(|attachment| {
attachment.attachment == *index && writable(Some(attachment.access))
})
|| (case.stage == Stage::Vertex && *index == 0 && case.vertex_observation.is_some())
}
OutputSelection::Depth { .. } => !reflection.depth_members.is_empty(),
OutputSelection::Stencil { .. } => !reflection.stencil_members.is_empty(),
OutputSelection::FragmentImageblock { semantic, .. } => reflection
.fragment_imageblock
.as_ref()
.is_some_and(|imageblock| {
imageblock.members.iter().any(|member| {
member.semantic == *semantic
&& member.binding.is_some()
&& writable(Some(member.access))
})
}),
}
}
fn validate_tessellation(
case: &AuthoredCase,
reflection: &ShaderReflection,
@@ -927,6 +1318,7 @@ fn validate_texture_shape(
ReflectedFormat::R16f => TextureFormat::R16Float,
ReflectedFormat::R16ui => TextureFormat::R16Uint,
ReflectedFormat::Rg16f => TextureFormat::Rg16Float,
ReflectedFormat::Rg32f => TextureFormat::Rg32Float,
ReflectedFormat::R32f => TextureFormat::R32Float,
ReflectedFormat::R32i => TextureFormat::R32Sint,
ReflectedFormat::R32ui => TextureFormat::R32Uint,
@@ -944,6 +1336,7 @@ fn validate_texture_shape(
authored_format,
TextureFormat::R8Unorm
| TextureFormat::Rgba8Unorm
| TextureFormat::Rg32Float
| TextureFormat::Rgba16Float
| TextureFormat::R32Float
| TextureFormat::Rgba32Float
@@ -1012,6 +1405,7 @@ fn render_target_format_matches_type(format: TextureFormat, type_name: &str) ->
| TextureFormat::Rgba8Unorm
| TextureFormat::R16Float
| TextureFormat::Rg16Float
| TextureFormat::Rg32Float
| TextureFormat::Rgba16Float
| TextureFormat::R32Float
| TextureFormat::Rgba32Float
@@ -1095,6 +1489,7 @@ fn validate_implicit_imageblock_attachments(
let expected = match attachment.format {
metal2vulkan::meta::TextureFormat::R16f => TextureFormat::R16Float,
metal2vulkan::meta::TextureFormat::Rg16f => TextureFormat::Rg16Float,
metal2vulkan::meta::TextureFormat::Rg32f => TextureFormat::Rg32Float,
metal2vulkan::meta::TextureFormat::R32f => TextureFormat::R32Float,
metal2vulkan::meta::TextureFormat::R32ui => TextureFormat::R32Uint,
metal2vulkan::meta::TextureFormat::Rgba16f => TextureFormat::Rgba16Float,
@@ -1305,6 +1700,93 @@ mod resource_contract_tests {
FunctionTableResource, OutputSelection, ResourceRole, ThreadgroupMemoryResource,
};
#[test]
fn selected_identity_output_requires_a_reflected_write() {
let ll = include_str!("../fixtures/public/kernel_implicit_imageblock_half2.ll");
let case = crate::case::narrow_implicit_imageblock_test_case(
crate::hash::sha256_bytes(ll.as_bytes()),
"kernel_implicit_imageblock_half2".into(),
);
let writable = reflect(ll, &case, &ResolvedLinkedFunctions::default()).unwrap();
assert!(selected_output_is_reflected_writable(&case, &writable));
let read_only_ll = ll.replace(
" call void @air.store.implicit_imageblock.v2f16(<2 x half> %value, i32 0, <2 x i16> %position, i32 0, i16 0)\n",
"",
);
let read_only = reflect(&read_only_ll, &case, &ResolvedLinkedFunctions::default()).unwrap();
assert!(!selected_output_is_reflected_writable(&case, &read_only));
}
#[test]
fn exact_empty_output_requires_no_reflected_write() {
let ll = r#"
define void @no_output() {
entry:
ret void
}
!air.kernel = !{!0}
!0 = !{ptr @no_output, !1, !1}
!1 = !{}
"#;
let mut case: AuthoredCase = serde_json::from_value(serde_json::json!({
"air_sha256": crate::hash::sha256_bytes(ll.as_bytes()),
"case_id": "test-no-output",
"name": "no-output",
"entry": "no_output",
"stage": "kernel",
"dispatch": {"grid": [1, 1, 1], "threads_per_threadgroup": [1, 1, 1]},
"output": {"kind": "none"},
"compare": {"kind": "exact"},
"execution_safety": "loop_free"
}))
.unwrap();
case.case_id = case.computed_case_id().unwrap();
case.validate_literal_resources().unwrap();
let reflection = reflect(ll, &case, &ResolvedLinkedFunctions::default()).unwrap();
assert!(selected_output_is_reflected_writable(&case, &reflection));
let mut vertex_case = case.clone();
vertex_case.stage = Stage::Vertex;
let mut vertex_output = reflection.clone();
vertex_output.vertex_builtins = Some(metal2vulkan::reflect::VertexBuiltins {
writes_position: true,
..Default::default()
});
assert!(!selected_output_is_reflected_writable(
&vertex_case,
&vertex_output
));
vertex_output.vertex_builtins = None;
vertex_output.varyings.push(metal2vulkan::reflect::Varying {
location: 0,
type_name: Some("float4".into()),
name: None,
user_semantic: None,
});
assert!(!selected_output_is_reflected_writable(
&vertex_case,
&vertex_output
));
let writable_ll = include_str!("../fixtures/public/kernel_vector_function_constant.ll");
let mut writable_case = crate::case::vector_function_constant_test_case(
crate::hash::sha256_bytes(writable_ll.as_bytes()),
"kernel_vector_function_constant".into(),
);
let writable_reflection = reflect(
writable_ll,
&writable_case,
&ResolvedLinkedFunctions::default(),
)
.unwrap();
writable_case.output = OutputSelection::None;
assert!(!selected_output_is_reflected_writable(
&writable_case,
&writable_reflection
));
}
#[test]
fn threadgroup_memory_is_authored_and_reflected_without_a_descriptor() {
let source = crate::source::public_sources()
@@ -1325,6 +1807,7 @@ mod resource_contract_tests {
initial_bytes_b64: Some("q6urqw==".into()),
}],
argument_buffer_buffers: vec![],
device_buffer_arrays: vec![],
threadgroup_memory: vec![ThreadgroupMemoryResource {
binding: 0,
length: 4,
@@ -1376,11 +1859,12 @@ mod resource_contract_tests {
}
#[test]
fn function_table_entry_resolves_exact_same_library_module_and_symbol() {
fn function_table_entry_resolves_exact_cross_library_module_and_symbol() {
let scratch = crate::ScratchDir::new("function-table-check").unwrap();
let air_ll = r#"
define void @main(ptr addrspace(1) %output, ptr addrspace(1) %table) {
entry:
store i32 42, ptr addrspace(1) %output, align 4
ret void
}
!air.kernel = !{!0}
@@ -1390,14 +1874,15 @@ entry:
!3 = !{i32 0, !"air.buffer", !"air.location_index", i32 0, i32 1, !"air.write", !"air.arg_type_name", !"uint"}
!4 = !{i32 1, !"air.visible_function_table", !"air.location_index", i32 3, i32 1, !"air.read", !"air.arg_type_name", !"visible_function_table"}
"#;
let library = "11".repeat(32);
let entry_library = "11".repeat(32);
let callback_library = "22".repeat(32);
let source = SourceRow {
air_sha256: crate::hash::sha256_bytes(air_ll.as_bytes()),
stage: "Kernel".into(),
entry: "main".into(),
air_ll: air_ll.into(),
blob_b64: None,
lib_sha256: library.clone(),
lib_sha256s: vec![entry_library],
label: "local/function-table-entry.ll".into(),
};
crate::source::write_source_shards(scratch.path(), [source.clone()]).unwrap();
@@ -1410,7 +1895,7 @@ entry:
module_sha256: module_sha256.clone(),
air_ll: module_ll.into(),
blob_b64: base64::engine::general_purpose::STANDARD.encode(b"owned bitcode"),
lib_sha256s: vec![library],
lib_sha256s: vec![callback_library.clone()],
label: "local/library-module/shade.ll".into(),
}],
)
@@ -1428,6 +1913,7 @@ entry:
initial_bytes_b64: Some("q6urqw==".into()),
}],
argument_buffer_buffers: vec![],
device_buffer_arrays: vec![],
threadgroup_memory: vec![],
imageblock: None,
fragment_imageblock: None,
@@ -1482,7 +1968,7 @@ entry:
checked.linked_functions.visible[0].entries[0]
.module
.lib_sha256s,
vec!["11".repeat(32)]
vec![callback_library]
);
assert!(checked.reflection.bindings.iter().any(|binding| {
binding.kind == ResourceKind::VisibleFunctionTable
+16
View File
@@ -154,6 +154,7 @@ pub fn unsupported_reflection_requirements(
| ReflectedTextureFormat::R16f
| ReflectedTextureFormat::R16ui
| ReflectedTextureFormat::Rg16f
| ReflectedTextureFormat::Rg32f
| ReflectedTextureFormat::R32i
| ReflectedTextureFormat::R32f
| ReflectedTextureFormat::R32ui
@@ -468,6 +469,7 @@ pub fn require_case(case: &AuthoredCase, executor: &str) -> Result<(), String> {
Stage::Fragment | Stage::Vertex => {
if case.render_targets.is_empty()
&& case.depth_stencil.is_none()
&& !(case.stage == Stage::Fragment && matches!(case.output, OutputSelection::None))
&& !case.is_rasterization_disabled_vertex()
{
return Err(format!(
@@ -552,6 +554,7 @@ mod tests {
initial_bytes_b64: Some("q6urqw==".into()),
}],
argument_buffer_buffers: vec![],
device_buffer_arrays: vec![],
threadgroup_memory: vec![],
imageblock: None,
fragment_imageblock: None,
@@ -712,6 +715,19 @@ mod tests {
};
assert!(require_case(&case, "test executor").is_ok());
let mut attachmentless = case.clone();
attachmentless.render_targets.clear();
attachmentless.output = OutputSelection::None;
assert!(require_case(&attachmentless, "test executor").is_ok());
attachmentless.output = OutputSelection::Buffer {
binding: 0,
offset: 0,
length: 4,
};
assert!(require_case(&attachmentless, "test executor")
.unwrap_err()
.contains("at least one attachment"));
case.render_targets.push(RenderTargetResource {
index: 1,
format: TextureFormat::Rgba32Float,
+280 -24
View File
@@ -115,6 +115,11 @@ pub fn rebuild_index(root: &Path, destination: &Path) -> Result<(), String> {
source_offset INTEGER,
source_length INTEGER
);
CREATE TABLE source_library_memberships (
air_sha256 TEXT NOT NULL REFERENCES sources(air_sha256) ON DELETE CASCADE,
lib_sha256 TEXT NOT NULL,
PRIMARY KEY(air_sha256, lib_sha256)
);
CREATE TABLE cases (
case_id TEXT PRIMARY KEY,
air_sha256 TEXT NOT NULL REFERENCES sources(air_sha256),
@@ -177,17 +182,24 @@ pub fn rebuild_index(root: &Path, destination: &Path) -> Result<(), String> {
"INSERT INTO sources (air_sha256, stage, entry, label, shard, source_offset, source_length) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)",
)
.map_err(|error| format!("prepare source insert: {error}"))?;
let mut insert_membership = transaction
.prepare(
"INSERT OR IGNORE INTO source_library_memberships (air_sha256, lib_sha256)
VALUES (?1, ?2)",
)
.map_err(|error| format!("prepare source-membership insert: {error}"))?;
let mut public_hashes = HashSet::new();
for source in public_sources()? {
let air_sha256 = source.air_sha256;
insert_source(
&mut insert,
&mut insert_membership,
&SourceIndexRow {
air_sha256: air_sha256.clone(),
stage: source.stage,
entry: source.entry,
label: source.label,
lib_sha256: source.lib_sha256,
lib_sha256s: source.lib_sha256s,
source_offset: None,
source_length: None,
},
@@ -222,7 +234,12 @@ pub fn rebuild_index(root: &Path, destination: &Path) -> Result<(), String> {
return Err(format!("duplicate private source {}", source.air_sha256));
}
if !public_hashes.contains(&source.air_sha256) {
insert_source(&mut insert, &source, Some(actual_shard))?;
insert_source(
&mut insert,
&mut insert_membership,
&source,
Some(actual_shard),
)?;
}
Ok(())
})?;
@@ -329,6 +346,11 @@ pub fn sync_index_with_stats(root: &Path, destination: &Path) -> Result<IndexSyn
size INTEGER NOT NULL,
modified_ns INTEGER NOT NULL
);
CREATE TABLE IF NOT EXISTS source_library_memberships (
air_sha256 TEXT NOT NULL REFERENCES sources(air_sha256) ON DELETE CASCADE,
lib_sha256 TEXT NOT NULL,
PRIMARY KEY(air_sha256, lib_sha256)
);
CREATE TABLE IF NOT EXISTS index_metadata (
key TEXT PRIMARY KEY,
value TEXT NOT NULL
@@ -406,15 +428,22 @@ pub fn sync_index_with_stats(root: &Path, destination: &Path) -> Result<IndexSyn
"INSERT OR IGNORE INTO sources (air_sha256, stage, entry, label, shard, source_offset, source_length) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)",
)
.map_err(|error| format!("prepare source sync insert: {error}"))?;
let mut insert_membership = transaction
.prepare(
"INSERT OR IGNORE INTO source_library_memberships (air_sha256, lib_sha256)
VALUES (?1, ?2)",
)
.map_err(|error| format!("prepare source-membership sync insert: {error}"))?;
for source in public_sources()? {
insert_source(
&mut insert,
&mut insert_membership,
&SourceIndexRow {
air_sha256: source.air_sha256,
stage: source.stage,
entry: source.entry,
label: source.label,
lib_sha256: source.lib_sha256,
lib_sha256s: source.lib_sha256s,
source_offset: None,
source_length: None,
},
@@ -470,7 +499,7 @@ pub fn sync_index_with_stats(root: &Path, destination: &Path) -> Result<IndexSyn
source.air_sha256, actual, shard
));
}
insert_source(&mut insert, &source, Some(shard))
insert_source(&mut insert, &mut insert_membership, &source, Some(shard))
})?;
transaction
.execute(
@@ -479,6 +508,7 @@ pub fn sync_index_with_stats(root: &Path, destination: &Path) -> Result<IndexSyn
)
.map_err(|error| format!("record source shard {shard} stamp: {error}"))?;
}
drop(insert_membership);
drop(insert);
transaction
.execute(
@@ -512,6 +542,7 @@ pub(crate) fn record_source_shard_write(
let mut connection = Connection::open(&destination)
.map_err(|error| format!("open index {}: {error}", destination.display()))?;
ensure_source_location_columns(&connection)?;
ensure_source_membership_table(&connection)?;
connection
.execute_batch(
"PRAGMA foreign_keys=ON;
@@ -525,6 +556,21 @@ pub(crate) fn record_source_shard_write(
let transaction = connection
.transaction()
.map_err(|error| format!("begin source-shard index update: {error}"))?;
transaction
.execute_batch(
"CREATE TEMP TABLE source_shard_replacement_hashes (
air_sha256 TEXT PRIMARY KEY
);",
)
.map_err(|error| format!("prepare source-shard replacement set: {error}"))?;
transaction
.execute(
"DELETE FROM source_library_memberships WHERE air_sha256 IN (
SELECT air_sha256 FROM sources WHERE shard=?1
)",
[shard],
)
.map_err(|error| format!("clear source memberships for shard {shard}: {error}"))?;
{
let mut upsert = transaction
.prepare(
@@ -541,7 +587,19 @@ pub(crate) fn record_source_shard_write(
WHERE sources.shard IS NOT NULL",
)
.map_err(|error| format!("prepare source-shard index update: {error}"))?;
let mut retain = transaction
.prepare("INSERT INTO source_shard_replacement_hashes VALUES (?1)")
.map_err(|error| format!("prepare retained source hash insert: {error}"))?;
let mut insert_membership = transaction
.prepare(
"INSERT OR IGNORE INTO source_library_memberships (air_sha256, lib_sha256)
VALUES (?1, ?2)",
)
.map_err(|error| format!("prepare source-shard membership update: {error}"))?;
for location in locations {
retain
.execute([&location.air_sha256])
.map_err(|error| format!("retain source {}: {error}", location.air_sha256))?;
upsert
.execute(params![
location.air_sha256,
@@ -553,8 +611,29 @@ pub(crate) fn record_source_shard_write(
location.length,
])
.map_err(|error| format!("index source {}: {error}", location.air_sha256))?;
for library in &location.lib_sha256s {
insert_membership
.execute(params![location.air_sha256, library])
.map_err(|error| {
format!(
"index source {} parent library: {error}",
location.air_sha256
)
})?;
}
}
}
transaction
.execute(
"DELETE FROM sources
WHERE shard=?1
AND NOT EXISTS (
SELECT 1 FROM source_shard_replacement_hashes replacement
WHERE replacement.air_sha256=sources.air_sha256
)",
[shard],
)
.map_err(|error| format!("remove stale sources from shard {shard}: {error}"))?;
transaction
.execute(
"INSERT OR REPLACE INTO indexed_source_shards (shard, size, modified_ns)
@@ -627,7 +706,7 @@ struct SourceIndexRow {
air_sha256: String,
stage: String,
entry: String,
lib_sha256: String,
lib_sha256s: Vec<String>,
label: String,
source_offset: Option<i64>,
source_length: Option<i64>,
@@ -655,18 +734,28 @@ impl SourceIndexRow {
if self.label.trim().is_empty() {
return Err("source label must not be empty".into());
}
if self.lib_sha256 != "owned-synthetic"
&& (self.lib_sha256.len() != 64
|| !self.lib_sha256.bytes().all(|byte| byte.is_ascii_hexdigit())
|| self
.lib_sha256
.bytes()
.any(|byte| byte.is_ascii_uppercase()))
{
return Err(format!(
"source {} lib_sha256 must be lowercase SHA-256",
self.label
));
if self.lib_sha256s.is_empty() {
return Err(format!("source {} has no parent library", self.label));
}
let mut previous = None;
for hash in &self.lib_sha256s {
if hash != "owned-synthetic"
&& (hash.len() != 64
|| !hash.bytes().all(|byte| byte.is_ascii_hexdigit())
|| hash.bytes().any(|byte| byte.is_ascii_uppercase()))
{
return Err(format!(
"source {} parent library must be lowercase SHA-256",
self.label
));
}
if previous.is_some_and(|value: &String| value >= hash) {
return Err(format!(
"source {} parent libraries must be sorted and unique",
self.label
));
}
previous = Some(hash);
}
Ok(())
}
@@ -732,13 +821,47 @@ fn source_index_row_from_canonical_json(line: &[u8]) -> Result<SourceIndexRow, S
air_sha256: extract_json_string(metadata, b"air_sha256")?,
stage: extract_json_string(metadata, b"stage")?,
entry: extract_json_string(metadata, b"entry")?,
lib_sha256: extract_json_string(metadata, b"lib_sha256")?,
lib_sha256s: extract_json_string_array_or_legacy_scalar(
metadata,
b"lib_sha256s",
b"lib_sha256",
)?,
label: extract_json_string(metadata, b"label")?,
source_offset: None,
source_length: None,
})
}
fn extract_json_string_array_or_legacy_scalar(
bytes: &[u8],
array_key: &[u8],
scalar_key: &[u8],
) -> Result<Vec<String>, String> {
let mut pattern = Vec::with_capacity(array_key.len() + 4);
pattern.push(b'"');
pattern.extend_from_slice(array_key);
pattern.extend_from_slice(b"\":[");
let Some(start) = memmem::find(bytes, &pattern).map(|offset| offset + pattern.len() - 1) else {
return extract_json_string(bytes, scalar_key).map(|value| vec![value]);
};
let end = bytes[start..]
.iter()
.position(|byte| *byte == b']')
.map(|offset| start + offset + 1)
.ok_or_else(|| {
format!(
"canonical source row has unterminated {}",
String::from_utf8_lossy(array_key)
)
})?;
serde_json::from_slice(&bytes[start..end]).map_err(|error| {
format!(
"canonical source row has invalid {}: {error}",
String::from_utf8_lossy(array_key)
)
})
}
fn extract_json_string(bytes: &[u8], key: &[u8]) -> Result<String, String> {
let mut pattern = Vec::with_capacity(key.len() + 4);
pattern.push(b'"');
@@ -785,6 +908,7 @@ fn extract_json_string(bytes: &[u8], key: &[u8]) -> Result<String, String> {
fn insert_source(
statement: &mut rusqlite::Statement<'_>,
membership_statement: &mut rusqlite::Statement<'_>,
source: &SourceIndexRow,
shard: Option<usize>,
) -> Result<(), String> {
@@ -799,6 +923,11 @@ fn insert_source(
source.source_length,
])
.map_err(|error| format!("index source: {error}"))?;
for library in &source.lib_sha256s {
membership_statement
.execute(params![source.air_sha256, library])
.map_err(|error| format!("index source parent library: {error}"))?;
}
Ok(())
}
@@ -825,6 +954,19 @@ fn ensure_source_location_columns(connection: &Connection) -> Result<(), String>
Ok(())
}
fn ensure_source_membership_table(connection: &Connection) -> Result<(), String> {
connection
.execute_batch(
"PRAGMA foreign_keys=ON;
CREATE TABLE IF NOT EXISTS source_library_memberships (
air_sha256 TEXT NOT NULL REFERENCES sources(air_sha256) ON DELETE CASCADE,
lib_sha256 TEXT NOT NULL,
PRIMARY KEY(air_sha256, lib_sha256)
);",
)
.map_err(|error| format!("upgrade source-membership index: {error}"))
}
fn ensure_candidate_fingerprint_column(connection: &Connection) -> Result<(), String> {
let mut statement = connection
.prepare("PRAGMA table_info(candidate_observations)")
@@ -863,6 +1005,7 @@ pub(crate) fn index_source_shard_locations(
let mut connection = Connection::open(index_path)
.map_err(|error| format!("open index {}: {error}", index_path.display()))?;
ensure_source_location_columns(&connection)?;
ensure_source_membership_table(&connection)?;
let transaction = connection
.transaction()
.map_err(|error| format!("begin source-location update: {error}"))?;
@@ -872,6 +1015,14 @@ pub(crate) fn index_source_shard_locations(
[shard],
)
.map_err(|error| format!("clear source locations for shard {shard}: {error}"))?;
transaction
.execute(
"DELETE FROM source_library_memberships WHERE air_sha256 IN (
SELECT air_sha256 FROM sources WHERE shard=?1
)",
[shard],
)
.map_err(|error| format!("clear source memberships for shard {shard}: {error}"))?;
{
let mut update = transaction
.prepare(
@@ -886,6 +1037,12 @@ pub(crate) fn index_source_shard_locations(
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)",
)
.map_err(|error| format!("prepare source-location insert: {error}"))?;
let mut insert_membership = transaction
.prepare(
"INSERT OR IGNORE INTO source_library_memberships (air_sha256, lib_sha256)
VALUES (?1, ?2)",
)
.map_err(|error| format!("prepare source-membership repair: {error}"))?;
read_source_index_shard(&path, |source| {
update
.execute(params![
@@ -898,7 +1055,7 @@ pub(crate) fn index_source_shard_locations(
shard,
])
.map_err(|error| format!("record source location: {error}"))?;
insert_source(&mut insert, &source, Some(shard))?;
insert_source(&mut insert, &mut insert_membership, &source, Some(shard))?;
Ok(())
})?;
}
@@ -1320,6 +1477,7 @@ mod tests {
initial_bytes_b64: Some("AAAAAA==".into()),
}],
argument_buffer_buffers: vec![],
device_buffer_arrays: vec![],
threadgroup_memory: vec![],
imageblock: None,
fragment_imageblock: None,
@@ -1445,14 +1603,14 @@ mod tests {
let mut source = public_sources().unwrap().into_iter().next().unwrap();
source.air_ll.push_str("\n; private index fixture\n");
source.air_sha256 = crate::hash::sha256_bytes(source.air_ll.as_bytes());
source.lib_sha256 = "owned-synthetic".into();
source.lib_sha256s = vec!["owned-synthetic".into()];
source.label = "private/before".into();
crate::source::write_source_shards(scratch.path(), [source.clone()]).unwrap();
let index = scratch.path().join("index.sqlite");
rebuild_index(scratch.path(), &index).unwrap();
source.label = "private/after-a-changed-shard".into();
source.lib_sha256 = "00".repeat(32);
source.lib_sha256s = vec!["00".repeat(32)];
crate::source::merge_source_shards(scratch.path(), [source.clone()]).unwrap();
let stats = sync_index_with_stats(scratch.path(), &index).unwrap();
assert_eq!(stats.source_shards_scanned, 1);
@@ -1483,16 +1641,31 @@ mod tests {
.air_ll
.push_str("\n; indexed merge handoff fixture\n");
source.air_sha256 = crate::hash::sha256_bytes(source.air_ll.as_bytes());
source.lib_sha256 = "owned-synthetic".into();
source.lib_sha256s = vec!["owned-synthetic".into()];
source.label = "private/before".into();
crate::source::write_source_shards(scratch.path(), [source.clone()]).unwrap();
let index = default_index_path(scratch.path());
rebuild_index(scratch.path(), &index).unwrap();
let connection = Connection::open(&index).unwrap();
connection
.execute(
"INSERT INTO cases (case_id, air_sha256, name, input_sha256) \
VALUES ('retained-case', ?1, 'retained', 'input')",
[&source.air_sha256],
)
.unwrap();
drop(connection);
source.label = "private/after-direct-handoff".into();
source.lib_sha256 = "00".repeat(32);
source.lib_sha256s = vec!["00".repeat(32)];
crate::source::merge_source_shards(scratch.path(), [source.clone()]).unwrap();
let connection = Connection::open(&index).unwrap();
connection
.execute("DELETE FROM cases WHERE case_id='retained-case'", [])
.unwrap();
drop(connection);
let stats = sync_index_with_stats(scratch.path(), &index).unwrap();
assert_eq!(stats.source_shards_scanned, 0);
assert_eq!(stats.source_bytes_scanned, 0);
@@ -1513,6 +1686,19 @@ mod tests {
assert_eq!(indexed.0, source.label);
assert!(indexed.1.is_some());
assert!(indexed.2.is_some());
assert_eq!(
connection
.prepare(
"SELECT lib_sha256 FROM source_library_memberships \
WHERE air_sha256=?1 ORDER BY lib_sha256",
)
.unwrap()
.query_map([&source.air_sha256], |row| row.get::<_, String>(0))
.unwrap()
.collect::<Result<Vec<_>, _>>()
.unwrap(),
vec!["00".repeat(32), "owned-synthetic".into()]
);
let read_stats = crate::source::for_each_indexed_source_analysis_with_stats(
scratch.path(),
&index,
@@ -1528,6 +1714,76 @@ mod tests {
check_index(scratch.path(), &index).unwrap();
}
#[test]
fn source_shard_handoff_removes_rows_absent_from_the_replacement() {
let scratch = ScratchDir::new("index-source-replacement").unwrap();
let mut retained = public_sources().unwrap().into_iter().next().unwrap();
retained.air_ll.push_str("\n; retained private fixture\n");
retained.air_sha256 = crate::hash::sha256_bytes(retained.air_ll.as_bytes());
retained.lib_sha256s = vec!["11".repeat(32), "22".repeat(32)];
retained.label = "private/retained".into();
let shard = crate::source::shard_index_for_hash(&retained.air_sha256).unwrap();
let mut stale = retained.clone();
for nonce in 0..u32::MAX {
stale.air_ll = format!("{}\n; stale private fixture {nonce}\n", retained.air_ll);
stale.air_sha256 = crate::hash::sha256_bytes(stale.air_ll.as_bytes());
if crate::source::shard_index_for_hash(&stale.air_sha256).unwrap() == shard {
break;
}
}
assert_ne!(stale.air_sha256, retained.air_sha256);
stale.lib_sha256s = vec!["33".repeat(32)];
stale.label = "private/stale".into();
crate::source::write_source_shards(scratch.path(), [retained.clone(), stale.clone()])
.unwrap();
let index = default_index_path(scratch.path());
rebuild_index(scratch.path(), &index).unwrap();
let source_path = crate::source::source_shard_path(scratch.path(), shard);
let encoded = format!(
"{}\n",
crate::jsonl::to_sorted_json_string(&retained).unwrap()
);
fs::write(&source_path, encoded.as_bytes()).unwrap();
record_source_shard_write(
scratch.path(),
shard,
&[crate::source::SourceIndexLocation {
air_sha256: retained.air_sha256.clone(),
stage: retained.stage.clone(),
entry: retained.entry.clone(),
label: retained.label.clone(),
lib_sha256s: retained.lib_sha256s.clone(),
offset: 0,
length: encoded.len().try_into().unwrap(),
}],
)
.unwrap();
let connection = Connection::open(&index).unwrap();
assert_eq!(
connection
.query_row(
"SELECT COUNT(*) FROM sources WHERE air_sha256=?1",
[&stale.air_sha256],
|row| row.get::<_, usize>(0),
)
.unwrap(),
0
);
assert_eq!(
connection
.query_row(
"SELECT COUNT(*) FROM source_library_memberships WHERE air_sha256=?1",
[&stale.air_sha256],
|row| row.get::<_, usize>(0),
)
.unwrap(),
0
);
check_index(scratch.path(), &index).unwrap();
}
#[test]
fn legacy_migration_and_lookup_never_open_an_unrelated_shard() {
let scratch = ScratchDir::new("index-lazy-locations").unwrap();
@@ -1536,7 +1792,7 @@ mod tests {
.air_ll
.push_str("\n; private lazy-location fixture\n");
source.air_sha256 = crate::hash::sha256_bytes(source.air_ll.as_bytes());
source.lib_sha256 = "owned-synthetic".into();
source.lib_sha256s = vec!["owned-synthetic".into()];
source.label = "private/lazy".into();
let source_shard = crate::source::shard_index_for_hash(&source.air_sha256).unwrap();
let mut other = source.clone();
+1
View File
@@ -15,6 +15,7 @@ pub mod jsonl;
pub mod library_module;
pub mod literal;
pub mod metal;
pub mod normalize;
pub mod observation;
pub mod observation_contract;
pub mod requirement;
+403 -25
View File
@@ -12,11 +12,13 @@ use crate::hash::sha256_bytes;
use crate::jsonl::to_sorted_json_string;
use crate::source::{shard_index_for_hash, shard_name};
use base64::Engine as _;
use rusqlite::{params, Connection, OptionalExtension};
use serde::{Deserialize, Serialize};
use std::collections::{BTreeMap, HashMap};
use std::collections::{BTreeMap, BTreeSet, HashMap};
use std::fs::{self, File};
use std::io::{BufRead, BufReader, Write};
use std::io::{BufRead, BufReader, Read, Seek, SeekFrom, Write};
use std::path::{Path, PathBuf};
use std::time::UNIX_EPOCH;
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
@@ -36,10 +38,22 @@ pub struct LibraryModuleMergeStats {
pub duplicates: usize,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct LibraryModuleIndexSyncStats {
pub shards_scanned: usize,
pub bytes_scanned: u64,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct LibraryModuleShardStamp {
size: u64,
modified_ns: u64,
}
/// Fully checked function-table dependencies for one authored entry point.
///
/// Case checking resolves these once by content hash and verifies that every implementation came
/// from the entry point's parent library. Executors consume this object directly, so they cannot
/// Case checking resolves these once by content hash and verifies that every implementation
/// defines the exact authored symbol. Executors consume this object directly, so they cannot
/// accidentally use a different module lookup or silently omit an authored table entry.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct ResolvedLinkedFunctions {
@@ -147,7 +161,6 @@ impl ResolvedLinkedFunctions {
pub fn resolve_linked_functions(
root: &Path,
case: &AuthoredCase,
parent_library_sha256: &str,
) -> Result<ResolvedLinkedFunctions, Vec<String>> {
let mut modules = HashMap::<String, Result<Option<LibraryModuleRow>, String>>::new();
let mut defined_functions = HashMap::<String, Vec<String>>::new();
@@ -163,7 +176,6 @@ pub fn resolve_linked_functions(
root,
"visible-function",
&case.visible_function_tables,
parent_library_sha256,
&mut modules,
&mut defined_functions,
&mut errors,
@@ -221,7 +233,6 @@ pub fn resolve_linked_functions(
root,
"intersection-function",
&linked_intersection,
parent_library_sha256,
&mut modules,
&mut defined_functions,
&mut errors,
@@ -346,7 +357,6 @@ fn resolve_table_kind(
root: &Path,
kind: &str,
tables: &[FunctionTableResource],
parent_library_sha256: &str,
modules: &mut HashMap<String, Result<Option<LibraryModuleRow>, String>>,
defined_functions: &mut HashMap<String, Vec<String>>,
errors: &mut Vec<String>,
@@ -375,20 +385,6 @@ fn resolve_table_kind(
return None;
}
};
if !module
.lib_sha256s
.iter()
.any(|hash| hash == parent_library_sha256)
{
errors.push(format!(
"{kind} table binding {} entry {} module {} was not harvested from entry library {}",
table.binding,
entry.index,
entry.module_sha256,
parent_library_sha256
));
return None;
}
let names = defined_functions
.entry(module.module_sha256.clone())
.or_insert_with(|| defined_function_names(&module.air_ll));
@@ -473,9 +469,21 @@ pub fn library_module_shard_path(root: &Path, shard: usize) -> PathBuf {
}
pub fn read_library_module_shard(path: &Path) -> Result<Vec<LibraryModuleRow>, String> {
let mut rows = Vec::new();
for_each_library_module_shard(path, |row| {
rows.push(row);
Ok(())
})?;
Ok(rows)
}
/// Stream fully validated dependency modules while retaining at most one decoded row at a time.
pub fn for_each_library_module_shard(
path: &Path,
mut consume: impl FnMut(LibraryModuleRow) -> Result<(), String>,
) -> Result<(), String> {
let expected = crate::source::shard_index_from_path(path)?;
let file = File::open(path).map_err(|error| format!("open {}: {error}", path.display()))?;
let mut rows = Vec::new();
for (line_index, line) in BufReader::new(file).lines().enumerate() {
let line =
line.map_err(|error| format!("read {}:{}: {error}", path.display(), line_index + 1))?;
@@ -497,9 +505,9 @@ pub fn read_library_module_shard(path: &Path) -> Result<Vec<LibraryModuleRow>, S
expected
));
}
rows.push(row);
consume(row)?;
}
Ok(rows)
Ok(())
}
/// Resolve one explicitly authored dependency by its content hash.
@@ -520,6 +528,323 @@ pub fn find_library_module(
.find(|row| row.module_sha256 == module_sha256))
}
/// Incrementally index retained dependency-module identities, library memberships, symbols, and
/// exact JSONL byte locations.
///
/// A missing index is an explicit one-time migration. After it is warm, unchanged module shards
/// are identified from their stamps and are not opened.
pub fn sync_library_module_index(
root: &Path,
index: &Path,
) -> Result<LibraryModuleIndexSyncStats, String> {
let mut connection = Connection::open(index)
.map_err(|error| format!("open index {}: {error}", index.display()))?;
connection
.execute_batch(
"PRAGMA foreign_keys=ON;
CREATE TABLE IF NOT EXISTS library_modules (
module_sha256 TEXT PRIMARY KEY,
shard INTEGER NOT NULL,
source_offset INTEGER NOT NULL,
source_length INTEGER NOT NULL
);
CREATE TABLE IF NOT EXISTS library_module_memberships (
module_sha256 TEXT NOT NULL REFERENCES library_modules(module_sha256) ON DELETE CASCADE,
lib_sha256 TEXT NOT NULL,
PRIMARY KEY(module_sha256, lib_sha256)
);
CREATE TABLE IF NOT EXISTS library_module_symbols (
module_sha256 TEXT NOT NULL REFERENCES library_modules(module_sha256) ON DELETE CASCADE,
symbol TEXT NOT NULL,
PRIMARY KEY(module_sha256, symbol)
);
CREATE TABLE IF NOT EXISTS indexed_library_module_shards (
shard INTEGER PRIMARY KEY,
size INTEGER NOT NULL,
modified_ns INTEGER NOT NULL
);
CREATE INDEX IF NOT EXISTS library_memberships_by_library
ON library_module_memberships(lib_sha256, module_sha256);
CREATE INDEX IF NOT EXISTS library_symbols_by_symbol
ON library_module_symbols(symbol, module_sha256);",
)
.map_err(|error| format!("upgrade library-module index schema: {error}"))?;
let paths = library_module_shard_paths(root)?;
let current_shards = paths
.iter()
.map(|path| crate::source::shard_index_from_path(path))
.collect::<Result<std::collections::HashSet<_>, _>>()?;
let transaction = connection
.transaction()
.map_err(|error| format!("begin library-module index sync: {error}"))?;
let tracked_shards = {
let mut statement = transaction
.prepare("SELECT shard FROM indexed_library_module_shards")
.map_err(|error| format!("prepare tracked library-module shards: {error}"))?;
let shards = statement
.query_map([], |row| row.get::<_, usize>(0))
.map_err(|error| format!("query tracked library-module shards: {error}"))?
.collect::<Result<std::collections::HashSet<_>, _>>()
.map_err(|error| format!("read tracked library-module shards: {error}"))?;
shards
};
for shard in tracked_shards.difference(&current_shards) {
transaction
.execute("DELETE FROM library_modules WHERE shard=?1", [shard])
.map_err(|error| format!("remove library-module shard {shard}: {error}"))?;
transaction
.execute(
"DELETE FROM indexed_library_module_shards WHERE shard=?1",
[shard],
)
.map_err(|error| format!("remove library-module shard stamp {shard}: {error}"))?;
}
let mut stats = LibraryModuleIndexSyncStats::default();
for path in paths {
let shard = crate::source::shard_index_from_path(&path)?;
let stamp = library_module_shard_stamp(&path)?;
let tracked = transaction
.query_row(
"SELECT size, modified_ns FROM indexed_library_module_shards WHERE shard=?1",
[shard],
|row| {
Ok(LibraryModuleShardStamp {
size: row.get(0)?,
modified_ns: row.get(1)?,
})
},
)
.optional()
.map_err(|error| format!("read library-module shard {shard} stamp: {error}"))?;
if tracked == Some(stamp) {
continue;
}
transaction
.execute("DELETE FROM library_modules WHERE shard=?1", [shard])
.map_err(|error| format!("replace library-module shard {shard}: {error}"))?;
index_library_module_shard(&transaction, &path, shard)?;
transaction
.execute(
"INSERT OR REPLACE INTO indexed_library_module_shards (shard, size, modified_ns)
VALUES (?1, ?2, ?3)",
params![shard, stamp.size, stamp.modified_ns],
)
.map_err(|error| format!("record library-module shard {shard}: {error}"))?;
stats.shards_scanned += 1;
stats.bytes_scanned = stats
.bytes_scanned
.checked_add(stamp.size)
.ok_or_else(|| "library-module shard byte count overflow".to_string())?;
}
transaction
.commit()
.map_err(|error| format!("commit library-module index sync: {error}"))?;
Ok(stats)
}
/// Resolve direct AIR visible-function references only when the retained module is unique across
/// every parent library of the entry AIR, including transitive dependency references.
pub fn resolve_indexed_visible_references(
root: &Path,
index: &Path,
entry_ll: &str,
parent_library_sha256s: &[String],
) -> Result<Option<Vec<ResolvedFunctionReference>>, String> {
let mut pending = metal2vulkan::linked_functions::visible_function_reference_symbols(entry_ll)?;
if pending.is_empty() {
return Ok(Some(Vec::new()));
}
let connection = Connection::open_with_flags(
index,
rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY | rusqlite::OpenFlags::SQLITE_OPEN_NO_MUTEX,
)
.map_err(|error| format!("open index {}: {error}", index.display()))?;
let mut resolved = BTreeMap::<String, ResolvedFunctionReference>::new();
while let Some(symbol) = pending.pop() {
if resolved.contains_key(&symbol) {
continue;
}
let hashes = indexed_modules_for_symbol(&connection, parent_library_sha256s, &symbol)?;
if hashes.len() != 1 {
return Ok(None);
}
let module = find_indexed_library_module(root, &connection, &hashes[0])?
.ok_or_else(|| format!("indexed library module {} is unavailable", hashes[0]))?;
pending.extend(
metal2vulkan::linked_functions::visible_function_reference_symbols(&module.air_ll)?,
);
resolved.insert(
symbol.clone(),
ResolvedFunctionReference {
function: symbol,
module,
},
);
}
Ok(Some(resolved.into_values().collect()))
}
fn indexed_modules_for_symbol(
connection: &Connection,
libraries: &[String],
symbol: &str,
) -> Result<Vec<String>, String> {
let mut statement = connection
.prepare(
"SELECT m.module_sha256
FROM library_module_memberships m
JOIN library_module_symbols s ON s.module_sha256=m.module_sha256
WHERE m.lib_sha256=?1 AND s.symbol=?2
ORDER BY m.module_sha256",
)
.map_err(|error| format!("prepare linked-symbol lookup: {error}"))?;
let mut hashes = BTreeSet::new();
for library in libraries {
let rows = statement
.query_map(params![library, symbol], |row| row.get(0))
.map_err(|error| format!("query linked symbol {symbol:?}: {error}"))?;
for hash in rows {
hashes.insert(hash.map_err(|error| format!("read linked symbol {symbol:?}: {error}"))?);
}
}
Ok(hashes.into_iter().collect())
}
fn find_indexed_library_module(
root: &Path,
connection: &Connection,
hash: &str,
) -> Result<Option<LibraryModuleRow>, String> {
let location = connection
.query_row(
"SELECT shard, source_offset, source_length FROM library_modules WHERE module_sha256=?1",
[hash],
|row| Ok((row.get::<_, usize>(0)?, row.get::<_, u64>(1)?, row.get::<_, usize>(2)?)),
)
.optional()
.map_err(|error| format!("query library module {hash}: {error}"))?;
let Some((shard, offset, length)) = location else {
return Ok(None);
};
let path = library_module_shard_path(root, shard);
let mut file =
File::open(&path).map_err(|error| format!("open {}: {error}", path.display()))?;
file.seek(SeekFrom::Start(offset))
.map_err(|error| format!("seek {}: {error}", path.display()))?;
let mut bytes = vec![0; length];
file.read_exact(&mut bytes)
.map_err(|error| format!("read {}: {error}", path.display()))?;
let row: LibraryModuleRow = serde_json::from_slice(&bytes)
.map_err(|error| format!("parse indexed library module {hash}: {error}"))?;
if row.module_sha256 != hash {
return Err(format!(
"indexed library-module location for {hash} contains {}",
row.module_sha256
));
}
Ok(Some(row))
}
fn library_module_shard_paths(root: &Path) -> Result<Vec<PathBuf>, String> {
let directory = library_modules_dir(root);
if !directory.is_dir() {
return Ok(Vec::new());
}
let mut paths = fs::read_dir(&directory)
.map_err(|error| format!("read {}: {error}", directory.display()))?
.filter_map(Result::ok)
.map(|entry| entry.path())
.filter(|path| {
path.extension()
.is_some_and(|extension| extension == "jsonl")
})
.collect::<Vec<_>>();
paths.sort();
Ok(paths)
}
fn library_module_shard_stamp(path: &Path) -> Result<LibraryModuleShardStamp, String> {
let metadata =
fs::metadata(path).map_err(|error| format!("read metadata {}: {error}", path.display()))?;
let modified_ns = metadata
.modified()
.map_err(|error| format!("read modification time {}: {error}", path.display()))?
.duration_since(UNIX_EPOCH)
.map_err(|error| format!("invalid modification time {}: {error}", path.display()))?
.as_nanos()
.try_into()
.map_err(|_| format!("modification time overflow for {}", path.display()))?;
Ok(LibraryModuleShardStamp {
size: metadata.len(),
modified_ns,
})
}
fn index_library_module_shard(
transaction: &rusqlite::Transaction<'_>,
path: &Path,
shard: usize,
) -> Result<(), String> {
let mut reader = BufReader::new(
File::open(path).map_err(|error| format!("open {}: {error}", path.display()))?,
);
let mut offset = 0u64;
let mut line = Vec::new();
loop {
line.clear();
let length = reader
.read_until(b'\n', &mut line)
.map_err(|error| format!("read {}: {error}", path.display()))?;
if length == 0 {
break;
}
let row_bytes = line.strip_suffix(b"\n").unwrap_or(&line);
if row_bytes.is_empty() {
offset += length as u64;
continue;
}
let row: LibraryModuleRow = serde_json::from_slice(row_bytes)
.map_err(|error| format!("parse {} at byte {offset}: {error}", path.display()))?;
row.validate()
.map_err(|error| format!("{} at byte {offset}: {error}", path.display()))?;
let actual = shard_index_for_hash(&row.module_sha256)?;
if actual != shard {
return Err(format!(
"library module {} belongs in shard {actual}, not {shard}",
row.module_sha256
));
}
transaction
.execute(
"INSERT INTO library_modules (module_sha256, shard, source_offset, source_length)
VALUES (?1, ?2, ?3, ?4)",
params![row.module_sha256, shard, offset, row_bytes.len()],
)
.map_err(|error| format!("index library module {}: {error}", row.module_sha256))?;
for library in &row.lib_sha256s {
transaction
.execute(
"INSERT INTO library_module_memberships (module_sha256, lib_sha256)
VALUES (?1, ?2)",
params![row.module_sha256, library],
)
.map_err(|error| format!("index library membership: {error}"))?;
}
for symbol in defined_function_names(&row.air_ll) {
transaction
.execute(
"INSERT INTO library_module_symbols (module_sha256, symbol) VALUES (?1, ?2)",
params![row.module_sha256, symbol],
)
.map_err(|error| format!("index library symbol: {error}"))?;
}
offset += length as u64;
}
Ok(())
}
pub fn defined_function_names(ll: &str) -> Vec<String> {
ll.lines()
.filter_map(|line| {
@@ -747,6 +1072,59 @@ mod tests {
);
}
#[test]
fn indexed_visible_references_resolve_across_all_entry_library_memberships() {
let scratch = ScratchDir::new("indexed-visible-reference").unwrap();
let entry_library = "11".repeat(32);
let dependency_library = "22".repeat(32);
let dependency = row("define void @linked() { ret void }\n", &dependency_library);
merge_library_module_shards(scratch.path(), [dependency.clone()]).unwrap();
let index = scratch.path().join("index.sqlite");
Connection::open(&index).unwrap();
let cold = sync_library_module_index(scratch.path(), &index).unwrap();
assert_eq!(cold.shards_scanned, 1);
let warm = sync_library_module_index(scratch.path(), &index).unwrap();
assert_eq!(warm, LibraryModuleIndexSyncStats::default());
let entry = "define void @main() { ret void }\n!air.visible_function_references = !{!0}\n!0 = !{!\"air.visible_function_reference\", ptr @linked.MTL_VISIBLE_FN_REF, !\"linked\"}\n";
let resolved = resolve_indexed_visible_references(
scratch.path(),
&index,
entry,
&[entry_library, dependency_library],
)
.unwrap()
.unwrap();
assert_eq!(resolved.len(), 1);
assert_eq!(resolved[0].function, "linked");
assert_eq!(resolved[0].module.module_sha256, dependency.module_sha256);
}
#[test]
fn indexed_visible_references_leave_ambiguous_definitions_for_authoring() {
let scratch = ScratchDir::new("ambiguous-visible-reference").unwrap();
let library = "11".repeat(32);
let first = row("define void @linked() { ret void }\n; first\n", &library);
let second = row("define void @linked() { ret void }\n; second\n", &library);
merge_library_module_shards(scratch.path(), [first, second]).unwrap();
let index = scratch.path().join("index.sqlite");
Connection::open(&index).unwrap();
sync_library_module_index(scratch.path(), &index).unwrap();
let entry = "define void @main() { ret void }\n!air.visible_function_references = !{!0}\n!0 = !{!\"air.visible_function_reference\", ptr @linked.MTL_VISIBLE_FN_REF, !\"linked\"}\n";
assert_eq!(
resolve_indexed_visible_references(
scratch.path(),
&index,
entry,
std::slice::from_ref(&library),
)
.unwrap(),
None
);
}
#[test]
fn module_requires_real_function_body_and_exact_identity() {
let mut module = row("declare void @visible()", &"11".repeat(32));
+71 -15
View File
@@ -23,6 +23,20 @@ pub struct LiteralArgumentBufferBuffer {
pub bytes: Vec<u8>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct LiteralDeviceBufferArray {
pub binding: u32,
pub length: u32,
pub elements: Vec<LiteralDeviceBufferArrayElement>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct LiteralDeviceBufferArrayElement {
pub index: u32,
pub role: ResourceRole,
pub bytes: Vec<u8>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct LiteralAccelerationStructure {
pub binding: u32,
@@ -65,6 +79,7 @@ pub struct LiteralArgumentBufferTexture {
pub struct LiteralTextureArray {
pub binding: u32,
pub elements: Vec<LiteralTexture>,
pub overrides_texture_at_base: bool,
}
#[derive(Clone, Debug, PartialEq, Eq)]
@@ -352,6 +367,26 @@ pub struct LiteralFunctionConstant {
pub bytes: Vec<u8>,
}
/// Decode only the authored function constants needed by product specialization.
///
/// Translation-only workers use this instead of materializing every execution resource.
pub fn function_constants(case: &AuthoredCase) -> Result<Vec<LiteralFunctionConstant>, String> {
case.function_constants
.iter()
.map(|constant| {
Ok(LiteralFunctionConstant {
index: constant.index,
scalar_type: constant.scalar_type,
lanes: constant.lanes,
bytes: decode(
&constant.bytes_b64,
&format!("function constant {}", constant.index),
)?,
})
})
.collect()
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct LiteralTessellation {
pub factors: Vec<crate::case::TessellationFactors>,
@@ -365,6 +400,7 @@ pub struct LiteralTessellation {
pub struct LiteralResources {
pub buffers: Vec<LiteralBuffer>,
pub argument_buffer_buffers: Vec<LiteralArgumentBufferBuffer>,
pub device_buffer_arrays: Vec<LiteralDeviceBufferArray>,
pub vertex_inputs: Vec<LiteralStageInput>,
pub kernel_stage_inputs: Vec<LiteralStageInput>,
pub acceleration_structure_shadows: Vec<LiteralAccelerationStructure>,
@@ -417,6 +453,38 @@ impl LiteralResources {
})
})
.collect::<Result<Vec<_>, String>>()?;
let device_buffer_arrays = case
.device_buffer_arrays
.iter()
.map(|array| {
let elements = array
.elements
.iter()
.map(|resource| {
let label = format!(
"device-buffer-array {} element {}",
array.binding, resource.index
);
let encoded = role_bytes(
resource.role,
resource.bytes_b64.as_deref(),
resource.initial_bytes_b64.as_deref(),
)
.ok_or_else(|| format!("{label} has no literal bytes"))?;
Ok(LiteralDeviceBufferArrayElement {
index: resource.index,
role: resource.role,
bytes: decode(encoded, &label)?,
})
})
.collect::<Result<Vec<_>, String>>()?;
Ok(LiteralDeviceBufferArray {
binding: array.binding,
length: array.length,
elements,
})
})
.collect::<Result<Vec<_>, String>>()?;
let acceleration_structure_shadows = case
.acceleration_structures
.iter()
@@ -529,24 +597,11 @@ impl LiteralResources {
Ok(LiteralTextureArray {
binding: array.binding,
elements,
overrides_texture_at_base: array.overrides_texture_at_base,
})
})
.collect::<Result<Vec<_>, String>>()?;
let function_constants = case
.function_constants
.iter()
.map(|constant| {
Ok(LiteralFunctionConstant {
index: constant.index,
scalar_type: constant.scalar_type,
lanes: constant.lanes,
bytes: decode(
&constant.bytes_b64,
&format!("function constant {}", constant.index),
)?,
})
})
.collect::<Result<Vec<_>, String>>()?;
let function_constants = function_constants(case)?;
let render_targets = case
.render_targets
.iter()
@@ -639,6 +694,7 @@ impl LiteralResources {
Ok(Self {
buffers,
argument_buffer_buffers,
device_buffer_arrays,
vertex_inputs,
kernel_stage_inputs,
acceleration_structure_shadows,
+348 -51
View File
@@ -7,7 +7,7 @@ use crate::store::CorpusStore;
use base64::Engine as _;
use std::path::Path;
pub const ORACLE_ABI: &str = "metal-literal-resources-v19";
pub const ORACLE_ABI: &str = "metal-literal-resources-v23";
pub const QUALIFICATION_RUNS: usize = 3;
pub fn qualify_case(
@@ -71,16 +71,6 @@ fn qualify_outputs(initial: &[u8], outputs: Vec<Vec<u8>>) -> Result<Vec<u8>, Str
initial.len()
));
}
if output
.iter()
.zip(initial.iter())
.any(|(actual, poison)| actual == poison)
{
return Err(
"Metal selected output retained one or more initial poison bytes; write qualification failed"
.into(),
);
}
Ok(output)
}
@@ -89,6 +79,7 @@ fn selected_initial_bytes(
resources: &LiteralResources,
) -> Result<Vec<u8>, String> {
match &case.output {
crate::case::OutputSelection::None => Ok(Vec::new()),
crate::case::OutputSelection::Buffer {
binding,
offset,
@@ -134,6 +125,30 @@ fn selected_initial_bytes(
.map(<[u8]>::to_vec)
.ok_or_else(|| "selected output range exceeds argument-buffer buffer".into())
}
crate::case::OutputSelection::DeviceBufferArrayElement {
binding,
element,
offset,
length,
} => {
let resource = resources
.device_buffer_arrays
.iter()
.find(|array| array.binding == *binding)
.and_then(|array| array.elements.iter().find(|item| item.index == *element))
.ok_or_else(|| {
format!("missing device-buffer-array binding {binding} element {element}")
})?;
let start = *offset as usize;
let end = start
.checked_add(*length as usize)
.ok_or_else(|| "selected output range overflow".to_string())?;
resource
.bytes
.get(start..end)
.map(<[u8]>::to_vec)
.ok_or_else(|| "selected output range exceeds device-buffer-array element".into())
}
crate::case::OutputSelection::Texture {
binding,
origin,
@@ -258,8 +273,8 @@ mod platform {
MTLIntersectionFunctionSignature, MTLIntersectionFunctionTable,
MTLIntersectionFunctionTableDescriptor, MTLLibrary, MTLLinkedFunctions, MTLLoadAction,
MTLOrigin, MTLPackedFloat3, MTLPackedFloat4x3, MTLPipelineOption, MTLPixelFormat,
MTLPrimitiveAccelerationStructureDescriptor, MTLPrimitiveType, MTLRegion,
MTLRenderCommandEncoder, MTLRenderPassDescriptor, MTLRenderPipelineDescriptor,
MTLPrimitiveAccelerationStructureDescriptor, MTLPrimitiveTopologyClass, MTLPrimitiveType,
MTLRegion, MTLRenderCommandEncoder, MTLRenderPassDescriptor, MTLRenderPipelineDescriptor,
MTLRenderPipelineState, MTLRenderStages, MTLResourceOptions, MTLSamplerAddressMode,
MTLSamplerDescriptor, MTLSamplerMinMagFilter, MTLSamplerMipFilter, MTLSamplerState,
MTLSize, MTLStageInputOutputDescriptor, MTLStencilDescriptor, MTLStencilOperation,
@@ -411,7 +426,9 @@ mod platform {
let pipeline = make_pipeline(device, &function, resources, reflection, &linked)?;
let metal_function_tables =
make_compute_function_tables(&pipeline, function_tables, &linked)?;
let buffers = make_buffers(device, resources, reflection)?;
let mut buffers = make_buffers(device, resources, reflection)?;
let device_buffer_array_elements =
append_device_buffer_arrays(device, resources, &mut buffers)?;
let argument_buffer_buffers = make_argument_buffer_buffers(device, resources)?;
let textures = make_textures(device, &context.queue, resources)?;
let texture_arrays = make_texture_arrays(device, &context.queue, resources)?;
@@ -533,7 +550,8 @@ mod platform {
&textures,
&texture_arrays,
&argument_buffer_textures,
MetalAttachments {
MetalOutputResources {
device_buffer_array_elements: &device_buffer_array_elements,
colors: &[],
depth_stencil: None,
fragment_imageblock: None,
@@ -558,7 +576,7 @@ mod platform {
let entry = NSString::from_str(&case.entry);
let function = make_function(&library, &entry, resources)?;
let linked = load_linked_functions(device, function_tables, resources)?;
let render_targets = make_render_targets(device, resources)?;
let render_targets = make_render_targets(device, resources, false)?;
let dispatch = case
.dispatch
.as_ref()
@@ -594,7 +612,9 @@ mod platform {
&linked,
)?;
let buffers = make_buffers(device, resources, reflection)?;
let mut buffers = make_buffers(device, resources, reflection)?;
let device_buffer_array_elements =
append_device_buffer_arrays(device, resources, &mut buffers)?;
let argument_buffer_buffers = make_argument_buffer_buffers(device, resources)?;
let textures = make_textures(device, &context.queue, resources)?;
let texture_arrays = make_texture_arrays(device, &context.queue, resources)?;
@@ -702,7 +722,8 @@ mod platform {
&textures,
&texture_arrays,
&argument_buffer_textures,
MetalAttachments {
MetalOutputResources {
device_buffer_array_elements: &device_buffer_array_elements,
colors: &render_targets,
depth_stencil: None,
fragment_imageblock: None,
@@ -964,6 +985,12 @@ fragment half4 metal2vulkan_tile_coverage_fragment() { return half4(0.0h); }
let entry = NSString::from_str(&case.entry);
let fragment = make_function(&fragment_library, &entry, resources)?;
let linked = load_linked_functions(device, function_tables, resources)?;
let layered_rendering = metal2vulkan::meta::parse_air_fragment_meta(&source.air_ll)
.is_some_and(|meta| {
meta.roles.iter().any(|(_, role)| {
matches!(role, metal2vulkan::meta::FragRole::RenderTargetArrayIndex)
})
});
let vertex_source = fragment_passthrough_msl(&source.air_ll)?;
let vertex_library = device
.newLibraryWithSource_options_error(&NSString::from_str(&vertex_source), None)
@@ -971,11 +998,17 @@ fragment half4 metal2vulkan_tile_coverage_fragment() { return half4(0.0h); }
let vertex = vertex_library
.newFunctionWithName(&NSString::from_str("metal2vulkan_fragment_vertex"))
.ok_or_else(|| "generated fragment companion has no vertex function".to_string())?;
let render_targets = make_render_targets(device, resources)?;
let depth_stencil = make_depth_stencil(device, resources)?;
let render_targets = make_render_targets(device, resources, layered_rendering)?;
let depth_stencil = make_depth_stencil(device, resources, layered_rendering)?;
let pipeline_descriptor = MTLRenderPipelineDescriptor::new();
pipeline_descriptor.setVertexFunction(Some(&vertex));
pipeline_descriptor.setFragmentFunction(Some(&fragment));
if let Some(draw) = &case.draw {
unsafe {
pipeline_descriptor
.setInputPrimitiveTopology(metal_primitive_topology_class(draw.primitive));
}
}
if let Some(linked) = &linked.descriptor {
pipeline_descriptor.setFragmentLinkedFunctions(Some(linked));
}
@@ -1012,7 +1045,9 @@ fragment half4 metal2vulkan_tile_coverage_fragment() { return half4(0.0h); }
&linked,
)?;
let buffers = make_buffers(device, resources, reflection)?;
let mut buffers = make_buffers(device, resources, reflection)?;
let device_buffer_array_elements =
append_device_buffer_arrays(device, resources, &mut buffers)?;
let argument_buffer_buffers = make_argument_buffer_buffers(device, resources)?;
let textures = make_textures(device, &context.queue, resources)?;
let texture_arrays = make_texture_arrays(device, &context.queue, resources)?;
@@ -1035,6 +1070,17 @@ fragment half4 metal2vulkan_tile_coverage_fragment() { return half4(0.0h); }
let depth_stencil_state = make_depth_stencil_state(device, reflection)?;
let acceleration_structures = make_acceleration_structures(device, &context.queue, case)?;
let pass = MTLRenderPassDescriptor::renderPassDescriptor();
if render_targets.is_empty() && depth_stencil.is_none() {
// Metal needs explicit raster dimensions when a fragment pass has no attachments.
// This executes a structurally output-free fragment without inventing a writable
// attachment or observable bytes.
pass.setDefaultRasterSampleCount(1);
pass.setRenderTargetWidth(1);
pass.setRenderTargetHeight(1);
}
if layered_rendering {
pass.setRenderTargetArrayLength(1);
}
let pass_attachments = pass.colorAttachments();
for (index, texture) in &render_targets {
let attachment = unsafe { pass_attachments.objectAtIndexedSubscript(*index as usize) };
@@ -1150,7 +1196,8 @@ fragment half4 metal2vulkan_tile_coverage_fragment() { return half4(0.0h); }
&textures,
&texture_arrays,
&argument_buffer_textures,
MetalAttachments {
MetalOutputResources {
device_buffer_array_elements: &device_buffer_array_elements,
colors: &render_targets,
depth_stencil: depth_stencil.as_ref(),
fragment_imageblock: fragment_imageblock.as_ref().and_then(|imageblock| {
@@ -1177,6 +1224,15 @@ fragment half4 metal2vulkan_tile_coverage_fragment() { return half4(0.0h); }
let entry = NSString::from_str(&case.entry);
let vertex = make_function(&vertex_library, &entry, resources)?;
let linked = load_linked_functions(device, function_tables, resources)?;
let layered_rendering = metal2vulkan::meta::parse_air_vertex_meta(&source.air_ll)
.is_some_and(|meta| {
meta.output_roles.iter().any(|role| {
matches!(
role,
metal2vulkan::meta::VertOutRole::RenderTargetArrayIndex
)
})
});
let fragment = case
.vertex_observation
.map(|_| {
@@ -1189,7 +1245,7 @@ fragment half4 metal2vulkan_tile_coverage_fragment() { return half4(0.0h); }
.ok_or_else(|| "generated vertex observer has no fragment function".to_string())
})
.transpose()?;
let mut render_targets = make_render_targets(device, resources)?;
let mut render_targets = make_render_targets(device, resources, layered_rendering)?;
if case.is_rasterization_disabled_vertex() {
// Metal still requires a render-pass attachment to create an encoder. Rasterization is
// disabled on the pipeline, so this private 1x1 sink is API scaffolding and cannot
@@ -1202,6 +1258,12 @@ fragment half4 metal2vulkan_tile_coverage_fragment() { return half4(0.0h); }
pipeline_descriptor.setFragmentFunction(fragment.as_deref());
pipeline_descriptor.setRasterizationEnabled(fragment.is_some());
pipeline_descriptor.setVertexDescriptor(Some(&vertex_inputs.descriptor));
if let Some(draw) = &case.draw {
unsafe {
pipeline_descriptor
.setInputPrimitiveTopology(metal_primitive_topology_class(draw.primitive));
}
}
if let Some(tessellation) = &resources.tessellation {
unsafe {
pipeline_descriptor
@@ -1237,7 +1299,9 @@ fragment half4 metal2vulkan_tile_coverage_fragment() { return half4(0.0h); }
&linked,
)?;
let buffers = make_buffers(device, resources, reflection)?;
let mut buffers = make_buffers(device, resources, reflection)?;
let device_buffer_array_elements =
append_device_buffer_arrays(device, resources, &mut buffers)?;
let argument_buffer_buffers = make_argument_buffer_buffers(device, resources)?;
let textures = make_textures(device, &context.queue, resources)?;
let texture_arrays = make_texture_arrays(device, &context.queue, resources)?;
@@ -1254,6 +1318,9 @@ fragment half4 metal2vulkan_tile_coverage_fragment() { return half4(0.0h); }
let samplers = make_samplers(device, case)?;
let acceleration_structures = make_acceleration_structures(device, &context.queue, case)?;
let pass = MTLRenderPassDescriptor::renderPassDescriptor();
if layered_rendering {
pass.setRenderTargetArrayLength(1);
}
let pass_attachments = pass.colorAttachments();
for (index, texture) in &render_targets {
let attachment = unsafe { pass_attachments.objectAtIndexedSubscript(*index as usize) };
@@ -1357,7 +1424,8 @@ fragment half4 metal2vulkan_tile_coverage_fragment() { return half4(0.0h); }
&textures,
&texture_arrays,
&argument_buffer_textures,
MetalAttachments {
MetalOutputResources {
device_buffer_array_elements: &device_buffer_array_elements,
colors: &render_targets,
depth_stencil: None,
fragment_imageblock: None,
@@ -1450,7 +1518,7 @@ fragment half4 metal2vulkan_tile_coverage_fragment() { return half4(0.0h); }
let distinct_float3 = air_ll
.lines()
.filter(|line| {
line.contains(r#"\"air.fragment_input\""#)
line.contains(r#""air.fragment_input""#)
&& line.contains("!\"air.arg_type_name\", !\"float3\"")
})
.count()
@@ -1473,12 +1541,20 @@ fragment half4 metal2vulkan_tile_coverage_fragment() { return half4(0.0h); }
.roles
.iter()
.any(|(_, role)| matches!(role, metal2vulkan::meta::FragRole::ViewportArrayIndex));
let has_layer = meta
.roles
.iter()
.any(|(_, role)| matches!(role, metal2vulkan::meta::FragRole::RenderTargetArrayIndex));
let mut fields = String::from(" float4 position [[position]];\n");
let mut assignments = String::from(" out.position = float4(p, 0.0, 1.0);\n");
if has_viewport {
fields.push_str(" uint viewport [[viewport_array_index]];\n");
assignments.push_str(" out.viewport = 0;\n");
}
if has_layer {
fields.push_str(" uint layer [[render_target_array_index]];\n");
assignments.push_str(" out.layer = 0;\n");
}
for (ordinal, location) in locations.into_iter().enumerate() {
let type_name = meta
.varying_type(location)
@@ -1584,6 +1660,90 @@ fragment half4 metal2vulkan_tile_coverage_fragment() { return half4(0.0h); }
}
}
fn metal_primitive_topology_class(
primitive: crate::case::Primitive,
) -> MTLPrimitiveTopologyClass {
match primitive {
crate::case::Primitive::Point => MTLPrimitiveTopologyClass::Point,
crate::case::Primitive::Line | crate::case::Primitive::LineStrip => {
MTLPrimitiveTopologyClass::Line
}
crate::case::Primitive::Triangle | crate::case::Primitive::TriangleStrip => {
MTLPrimitiveTopologyClass::Triangle
}
}
}
#[cfg(test)]
mod primitive_topology_tests {
use super::*;
#[test]
fn authored_draw_primitives_map_to_their_pipeline_topology_class() {
use crate::case::Primitive;
assert_eq!(
metal_primitive_topology_class(Primitive::Point),
MTLPrimitiveTopologyClass::Point
);
for primitive in [Primitive::Line, Primitive::LineStrip] {
assert_eq!(
metal_primitive_topology_class(primitive),
MTLPrimitiveTopologyClass::Line
);
}
for primitive in [Primitive::Triangle, Primitive::TriangleStrip] {
assert_eq!(
metal_primitive_topology_class(primitive),
MTLPrimitiveTopologyClass::Triangle
);
}
}
#[test]
fn fragment_companion_defines_requested_render_target_layer_zero() {
let ll = r#"
!air.fragment = !{!0}
!0 = !{ptr @frag, !1, !3}
!1 = !{!2}
!2 = !{!"air.render_target", i32 0, i32 0, !"air.arg_type_name", !"half4"}
!3 = !{!4}
!4 = !{i32 0, !"air.render_target_array_index", !"air.arg_type_name", !"ushort", !"air.arg_name", !"layer"}
"#;
let msl = fragment_passthrough_msl(ll).unwrap();
assert!(
msl.contains("uint layer [[render_target_array_index]];"),
"{msl}"
);
assert!(msl.contains("out.layer = 0;"), "{msl}");
}
#[test]
fn fragment_companion_separates_duplicate_float3_rsqrt_inputs() {
let ll = r#"
declare float @air.fast_rsqrt.f32(float)
define <4 x half> @frag(<3 x float> %a, <3 x float> %b) {
%delta = fsub <3 x float> %a, %b
ret <4 x half> zeroinitializer
}
!air.fragment = !{!0}
!0 = !{ptr @frag, !1, !3}
!1 = !{!2}
!2 = !{!"air.render_target", i32 0, i32 0, !"air.arg_type_name", !"half4"}
!3 = !{!4, !5}
!4 = !{i32 0, !"air.fragment_input", !"generated(a)", !"air.arg_type_name", !"float3", !"air.arg_name", !"a"}
!5 = !{i32 1, !"air.fragment_input", !"generated(b)", !"air.arg_type_name", !"float3", !"air.arg_name", !"b"}
"#;
let msl = fragment_passthrough_msl(ll).unwrap();
assert!(
msl.contains("float3(uv.x, uv.y, 0.5)") && msl.contains("float3(uv.x, uv.y, 1.0)"),
"{msl}"
);
}
}
fn load_library(
device: &ProtocolObject<dyn MTLDevice>,
source: &SourceRow,
@@ -2013,6 +2173,43 @@ fragment half4 metal2vulkan_tile_coverage_fragment() { return half4(0.0h); }
Ok(buffers)
}
type DeviceBufferArrayElement = ((u32, u32), Buffer);
fn append_device_buffer_arrays(
device: &ProtocolObject<dyn MTLDevice>,
resources: &LiteralResources,
buffers: &mut Vec<(u32, Buffer)>,
) -> Result<Vec<DeviceBufferArrayElement>, String> {
let mut nested = Vec::new();
for array in &resources.device_buffer_arrays {
for element in &array.elements {
let label = format!(
"device-buffer-array {} element {}",
array.binding, element.index
);
let pointer = NonNull::new(element.bytes.as_ptr().cast_mut().cast::<c_void>())
.ok_or_else(|| format!("{label} bytes pointer is null"))?;
let buffer = unsafe {
device.newBufferWithBytes_length_options(
pointer,
element.bytes.len(),
MTLResourceOptions::StorageModeShared,
)
}
.ok_or_else(|| format!("create Metal {label}"))?;
let binding = array.binding.checked_add(element.index).ok_or_else(|| {
format!(
"device-buffer-array {} element {} binding overflows",
array.binding, element.index
)
})?;
buffers.push((binding, buffer.clone()));
nested.push(((array.binding, element.index), buffer));
}
}
Ok(nested)
}
fn make_pipeline(
device: &ProtocolObject<dyn MTLDevice>,
function: &ProtocolObject<dyn MTLFunction>,
@@ -2365,17 +2562,25 @@ fragment half4 metal2vulkan_tile_coverage_fragment() { return half4(0.0h); }
fn make_render_targets(
device: &ProtocolObject<dyn MTLDevice>,
resources: &LiteralResources,
layered: bool,
) -> Result<Vec<(u32, Texture)>, String> {
resources
.render_targets
.iter()
.map(|resource| {
let descriptor = MTLTextureDescriptor::new();
descriptor.setTextureType(MTLTextureType::Type2D);
descriptor.setTextureType(if layered {
MTLTextureType::Type2DArray
} else {
MTLTextureType::Type2D
});
descriptor.setPixelFormat(metal_pixel_format(resource.format));
unsafe {
descriptor.setWidth(resource.dimensions[0] as usize);
descriptor.setHeight(resource.dimensions[1] as usize);
if layered {
descriptor.setArrayLength(1);
}
}
descriptor.setStorageMode(MTLStorageMode::Shared);
descriptor.setUsage(MTLTextureUsage::RenderTarget);
@@ -2385,7 +2590,11 @@ fragment half4 metal2vulkan_tile_coverage_fragment() { return half4(0.0h); }
upload_texture(
&texture,
&format!("render target {}", resource.index),
TextureType::D2,
if layered {
TextureType::D2Array
} else {
TextureType::D2
},
[resource.dimensions[0], resource.dimensions[1], 1],
1,
resource.format,
@@ -2426,7 +2635,8 @@ fragment half4 metal2vulkan_tile_coverage_fragment() { return half4(0.0h); }
}
#[derive(Clone, Copy)]
struct MetalAttachments<'a> {
struct MetalOutputResources<'a> {
device_buffer_array_elements: &'a [DeviceBufferArrayElement],
colors: &'a [(u32, Texture)],
depth_stencil: Option<&'a DepthStencilTexture>,
fragment_imageblock: Option<(&'a Buffer, [u32; 2], usize)>,
@@ -2435,17 +2645,25 @@ fragment half4 metal2vulkan_tile_coverage_fragment() { return half4(0.0h); }
fn make_depth_stencil(
device: &ProtocolObject<dyn MTLDevice>,
resources: &LiteralResources,
layered: bool,
) -> Result<Option<DepthStencilTexture>, String> {
let Some(resource) = &resources.depth_stencil else {
return Ok(None);
};
let make_aspect = |format, bytes: &[u8], pixel_size| -> Result<Texture, String> {
let descriptor = MTLTextureDescriptor::new();
descriptor.setTextureType(MTLTextureType::Type2D);
descriptor.setTextureType(if layered {
MTLTextureType::Type2DArray
} else {
MTLTextureType::Type2D
});
descriptor.setPixelFormat(format);
unsafe {
descriptor.setWidth(resource.dimensions[0] as usize);
descriptor.setHeight(resource.dimensions[1] as usize);
if layered {
descriptor.setArrayLength(1);
}
}
descriptor.setStorageMode(MTLStorageMode::Shared);
descriptor.setUsage(MTLTextureUsage::RenderTarget);
@@ -2784,6 +3002,7 @@ fragment half4 metal2vulkan_tile_coverage_fragment() { return half4(0.0h); }
TextureFormat::R16Float => ("half", "half", "value", false),
TextureFormat::R16Uint => ("ushort", "uint", "uint(value)", false),
TextureFormat::Rg16Float => ("half2", "half2", "value", false),
TextureFormat::Rg32Float => ("float2", "float2", "value", false),
TextureFormat::Rgba16Float => ("half4", "half4", "value", false),
TextureFormat::Rgba16Uint => ("ushort4", "uint4", "uint4(value)", false),
TextureFormat::R32Uint => ("uint", "uint", "value", false),
@@ -3140,6 +3359,7 @@ fragment {result_type} metal2vulkan_literal_fragment(
TextureFormat::R16Float => MTLPixelFormat::R16Float,
TextureFormat::R16Uint => MTLPixelFormat::R16Uint,
TextureFormat::Rg16Float => MTLPixelFormat::RG16Float,
TextureFormat::Rg32Float => MTLPixelFormat::RG32Float,
TextureFormat::Rgba16Float => MTLPixelFormat::RGBA16Float,
TextureFormat::Rgba16Uint => MTLPixelFormat::RGBA16Uint,
TextureFormat::R32Uint => MTLPixelFormat::R32Uint,
@@ -3388,11 +3608,13 @@ fragment {result_type} metal2vulkan_literal_fragment(
textures: &[(u32, Texture)],
texture_arrays: &[TextureArray],
argument_buffer_textures: &[ArgumentBufferTexture],
attachments: MetalAttachments<'_>,
output_resources: MetalOutputResources<'_>,
) -> Result<Vec<u8>, String> {
let render_targets = attachments.colors;
let depth_stencil = attachments.depth_stencil;
let device_buffer_array_elements = output_resources.device_buffer_array_elements;
let render_targets = output_resources.colors;
let depth_stencil = output_resources.depth_stencil;
match case.output {
OutputSelection::None => Ok(Vec::new()),
OutputSelection::Buffer {
binding,
offset,
@@ -3438,6 +3660,32 @@ fragment {result_type} metal2vulkan_literal_fragment(
Ok(std::slice::from_raw_parts(pointer, length).to_vec())
}
}
OutputSelection::DeviceBufferArrayElement {
binding,
element,
offset,
length,
} => {
let buffer = device_buffer_array_elements
.iter()
.find_map(|((owner, index), buffer)| {
(*owner == binding && *index == element).then_some(buffer)
})
.ok_or_else(|| {
format!(
"output device-buffer-array {binding} element {element} was not bound"
)
})?;
let start = offset as usize;
let length = length as usize;
if start.saturating_add(length) > buffer.length() {
return Err("selected output exceeds Metal device-buffer-array element".into());
}
unsafe {
let pointer = buffer.contents().as_ptr().cast::<u8>().add(start);
Ok(std::slice::from_raw_parts(pointer, length).to_vec())
}
}
OutputSelection::Texture {
binding,
origin,
@@ -3589,7 +3837,7 @@ fragment {result_type} metal2vulkan_literal_fragment(
origin, dimensions, ..
} => {
let (buffer, source_dimensions, pixel_size) =
attachments.fragment_imageblock.ok_or_else(|| {
output_resources.fragment_imageblock.ok_or_else(|| {
"selected Metal fragment imageblock output was not resolved".to_string()
})?;
let bytes = unsafe {
@@ -3707,7 +3955,7 @@ mod tests {
use super::*;
#[test]
fn qualification_requires_three_identical_full_poison_overwrites() {
fn qualification_requires_three_identical_outputs_and_accepts_identity() {
let initial = [0xab, 0xab, 0xab, 0xab];
let output = vec![42, 0, 0, 0];
assert_eq!(
@@ -3724,12 +3972,55 @@ mod tests {
)
.unwrap_err()
.contains("nondeterministic"));
assert!(qualify_outputs(
&initial,
vec![initial.to_vec(), initial.to_vec(), initial.to_vec()]
assert_eq!(
qualify_outputs(
&initial,
vec![initial.to_vec(), initial.to_vec(), initial.to_vec()]
)
.unwrap(),
initial
);
}
#[cfg(target_os = "macos")]
#[test]
fn attachmentless_fragment_executes_without_invented_output() {
use crate::library_module::ResolvedLinkedFunctions;
use crate::source::SourceRow;
let air_ll = crate::case::ATTACHMENTLESS_FRAGMENT_AIR;
let source = SourceRow {
air_sha256: crate::hash::sha256_bytes(air_ll.as_bytes()),
stage: "Fragment".into(),
entry: "fragment_no_writes".into(),
air_ll: air_ll.into(),
blob_b64: Some(
base64::engine::general_purpose::STANDARD
.encode(compile_metal_fixture("fragment_no_writes")),
),
lib_sha256s: vec!["10".repeat(32)],
label: "test/fragment-no-writes.air".into(),
};
let case = crate::case::attachmentless_fragment_test_case(
source.air_sha256.clone(),
source.entry.clone(),
);
let reflection = metal2vulkan::reflect_sanitized(
&source.air_ll,
metal2vulkan::passes::Stage::Fragment,
metal2vulkan::passes::TransformOptions::default(),
)
.unwrap_err()
.contains("poison"));
.unwrap();
let resources = LiteralResources::prepare(&case).unwrap();
assert!(platform::execute(
&case,
&source,
&resources,
&reflection,
&ResolvedLinkedFunctions::default(),
)
.unwrap()
.is_empty());
}
#[cfg(target_os = "macos")]
@@ -3752,7 +4043,7 @@ mod tests {
base64::engine::general_purpose::STANDARD
.encode(compile_metal_fixture("vertex_narrow_attributes")),
),
lib_sha256: "11".repeat(32),
lib_sha256s: vec!["11".repeat(32)],
label: "test/vertex-side-effect.air".into(),
};
let case = AuthoredCase {
@@ -3768,6 +4059,7 @@ mod tests {
initial_bytes_b64: Some("q6urqw==".into()),
}],
argument_buffer_buffers: vec![],
device_buffer_arrays: vec![],
threadgroup_memory: vec![],
imageblock: None,
fragment_imageblock: None,
@@ -3853,7 +4145,7 @@ mod tests {
base64::engine::general_purpose::STANDARD
.encode(compile_metal_fixture("fragment_depth_stencil")),
),
lib_sha256: "22".repeat(32),
lib_sha256s: vec!["22".repeat(32)],
label: "test/fragment-depth-stencil.air".into(),
};
let case = crate::case::combined_depth_stencil_test_case(
@@ -3896,7 +4188,7 @@ mod tests {
base64::engine::general_purpose::STANDARD
.encode(compile_metal_fixture("kernel_vector_function_constant")),
),
lib_sha256: "33".repeat(32),
lib_sha256s: vec!["33".repeat(32)],
label: "test/kernel-vector-function-constant.air".into(),
};
let case = crate::case::vector_function_constant_test_case(
@@ -3959,7 +4251,7 @@ declare { <3 x float> } @control.MTL_CONTROL_POINT_FN(i32, ptr) section "air.ext
base64::engine::general_purpose::STANDARD
.encode(compile_metal_fixture("tessellation_literal")),
),
lib_sha256: "11".repeat(32),
lib_sha256s: vec!["11".repeat(32)],
label: "test/tessellation-literal.air".into(),
};
let case = AuthoredCase {
@@ -3970,6 +4262,7 @@ declare { <3 x float> } @control.MTL_CONTROL_POINT_FN(i32, ptr) section "air.ext
stage: Stage::Vertex,
buffers: vec![],
argument_buffer_buffers: vec![],
device_buffer_arrays: vec![],
threadgroup_memory: vec![],
imageblock: None,
fragment_imageblock: None,
@@ -4081,7 +4374,7 @@ entry:
entry: "kernel_visible_function_table_word".into(),
air_ll: air_ll.into(),
blob_b64: Some(base64::engine::general_purpose::STANDARD.encode(entry_blob)),
lib_sha256: "11".repeat(32),
lib_sha256s: vec!["11".repeat(32)],
label: "test/kernel-visible-function-table.air".into(),
};
let case = AuthoredCase {
@@ -4097,6 +4390,7 @@ entry:
initial_bytes_b64: Some("q6urqw==".into()),
}],
argument_buffer_buffers: vec![],
device_buffer_arrays: vec![],
threadgroup_memory: vec![],
imageblock: None,
fragment_imageblock: None,
@@ -4143,7 +4437,7 @@ entry:
module_sha256,
air_ll: module_ll.into(),
blob_b64: base64::engine::general_purpose::STANDARD.encode(helper_blob),
lib_sha256s: vec![source.lib_sha256.clone()],
lib_sha256s: source.lib_sha256s.clone(),
label: "test/visible-function-add-one.air".into(),
};
let function_tables = ResolvedLinkedFunctions {
@@ -4196,7 +4490,7 @@ entry:
base64::engine::general_purpose::STANDARD
.encode(compile_metal_fixture("kernel_instance_as_intersect")),
),
lib_sha256: "11".repeat(32),
lib_sha256s: vec!["11".repeat(32)],
label: "test/kernel-instance-as-intersect.air".into(),
};
let signature = vec![
@@ -4219,6 +4513,7 @@ entry:
),
}],
argument_buffer_buffers: vec![],
device_buffer_arrays: vec![],
threadgroup_memory: vec![],
imageblock: None,
fragment_imageblock: None,
@@ -4308,7 +4603,7 @@ entry:
base64::engine::general_purpose::STANDARD
.encode(compile_metal_fixture("fragment_custom_imageblock")),
),
lib_sha256: "12".repeat(32),
lib_sha256s: vec!["12".repeat(32)],
label: "test/fragment-custom-imageblock.air".into(),
};
let case = crate::case::fragment_imageblock_test_case(
@@ -4372,7 +4667,7 @@ entry:
blob_b64: Some(base64::engine::general_purpose::STANDARD.encode(
compile_metal_fixture("kernel_argument_buffer_intersection_table"),
)),
lib_sha256: "11".repeat(32),
lib_sha256s: vec!["11".repeat(32)],
label: "test/kernel-argument-buffer-intersection-table.air".into(),
};
let signature = vec![
@@ -4403,6 +4698,7 @@ entry:
},
],
argument_buffer_buffers: vec![],
device_buffer_arrays: vec![],
threadgroup_memory: vec![],
imageblock: None,
fragment_imageblock: None,
@@ -4518,7 +4814,7 @@ declare void @air.store.implicit_imageblock.v4f16(<4 x half>, i32, <2 x i16>, i3
base64::engine::general_purpose::STANDARD
.encode(compile_metal_fixture("kernel_implicit_imageblock_half4")),
),
lib_sha256: "11".repeat(32),
lib_sha256s: vec!["11".repeat(32)],
label: "test/kernel-implicit-imageblock-half4.air".into(),
};
let initial = [0x00, 0x3c, 0x00, 0x40, 0x00, 0x42, 0x00, 0x44];
@@ -4537,6 +4833,7 @@ declare void @air.store.implicit_imageblock.v4f16(<4 x half>, i32, <2 x i16>, i3
),
}],
argument_buffer_buffers: vec![],
device_buffer_arrays: vec![],
threadgroup_memory: vec![],
imageblock: Some(ImageblockResource {
dimensions: [16, 16],
@@ -4623,7 +4920,7 @@ declare void @air.store.implicit_imageblock.v4f16(<4 x half>, i32, <2 x i16>, i3
base64::engine::general_purpose::STANDARD
.encode(compile_metal_fixture("kernel_implicit_imageblock_half2")),
),
lib_sha256: "11".repeat(32),
lib_sha256s: vec!["11".repeat(32)],
label: "test/kernel-implicit-imageblock-half2.air".into(),
};
let case = crate::case::narrow_implicit_imageblock_test_case(
+810
View File
@@ -0,0 +1,810 @@
//! Explicit, recoverable migration from legacy sanitized AIR identities to the current contract.
use crate::case::{AuthoredCase, IntersectionFunctionTableEntry};
use crate::hash::sha256_bytes;
use crate::jsonl::to_sorted_json_string;
use crate::library_module::{self, LibraryModuleRow};
use crate::observation::Backend;
use crate::source::{self, SourceRow, SHARD_COUNT};
use crate::store::CorpusStore;
use rusqlite::{params, Connection, OptionalExtension, Transaction};
use std::collections::{BTreeMap, HashMap};
use std::fs::{self, File};
use std::io::{BufWriter, Write};
use std::path::{Path, PathBuf};
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct NormalizationStats {
pub source_rows_before: usize,
pub source_rows_after: usize,
pub module_rows_before: usize,
pub module_rows_after: usize,
pub cases_rewritten: usize,
pub cases_deduplicated: usize,
pub reviews_superseded: usize,
pub observations_invalidated: usize,
pub observations_deduplicated: usize,
}
struct PreparedDirectory(PathBuf);
impl Drop for PreparedDirectory {
fn drop(&mut self) {
let _ = fs::remove_dir_all(&self.0);
}
}
/// Normalize every private AIR identity and all committed references in one recoverable publish.
pub fn normalize_air_identities(root: &Path) -> Result<NormalizationStats, String> {
let store = CorpusStore::new(root);
store.recover_transactions()?;
let prepared_path = root.join(format!(".normalize-air.{}", std::process::id()));
if prepared_path.exists() {
fs::remove_dir_all(&prepared_path)
.map_err(|error| format!("remove stale {}: {error}", prepared_path.display()))?;
}
fs::create_dir_all(&prepared_path)
.map_err(|error| format!("create {}: {error}", prepared_path.display()))?;
let prepared = PreparedDirectory(prepared_path);
let database = prepared.0.join("identities.sqlite");
let mut connection = Connection::open(&database)
.map_err(|error| format!("open {}: {error}", database.display()))?;
connection
.execute_batch(
"PRAGMA journal_mode=DELETE;
PRAGMA synchronous=FULL;
CREATE TABLE sources (
hash TEXT PRIMARY KEY, stage TEXT NOT NULL, entry TEXT NOT NULL,
air_ll TEXT NOT NULL, blob_b64 TEXT, label TEXT NOT NULL
);
CREATE TABLE source_memberships (
hash TEXT NOT NULL, library TEXT NOT NULL, PRIMARY KEY(hash, library)
);
CREATE TABLE modules (
hash TEXT PRIMARY KEY, air_ll TEXT NOT NULL, blob_b64 TEXT NOT NULL,
label TEXT NOT NULL
);
CREATE TABLE module_memberships (
hash TEXT NOT NULL, library TEXT NOT NULL, PRIMARY KEY(hash, library)
);",
)
.map_err(|error| format!("create normalization database: {error}"))?;
let mut stats = NormalizationStats::default();
let mut source_map = HashMap::new();
let mut module_map = HashMap::new();
ingest_sources(root, &mut connection, &mut source_map, &mut stats)?;
ingest_modules(root, &mut connection, &mut module_map, &mut stats)?;
let old_cases = store.read_all_cases_for_identity_migration()?;
let old_metal = store.read_metal_for_identity_migration()?;
let old_moltenvk = store.read_candidates_for_identity_migration(Backend::Moltenvk)?;
let old_vulkan = store.read_candidates_for_identity_migration(Backend::Vulkan)?;
let old_reviews = store.read_reviews()?;
let (cases, case_map) = remap_cases(old_cases, &source_map, &module_map, &mut stats)?;
let case_airs = cases
.iter()
.map(|case| case.air_sha256.as_str())
.collect::<std::collections::HashSet<_>>();
let reviews = remap_reviews(old_reviews, &source_map, &case_airs, &mut stats)?;
let mut files = write_normalized_air(&prepared.0, &connection, &mut stats)?;
files.extend(write_aligned_rows(
&prepared.0,
"cases",
cases,
|row: &AuthoredCase| &row.air_sha256,
)?);
files.extend(write_aligned_rows(
&prepared.0,
"reviews",
reviews,
|row: &crate::review::ReviewNote| &row.air_sha256,
)?);
let observations_before = old_metal.len() + old_moltenvk.len() + old_vulkan.len();
let metal = old_metal
.into_iter()
.filter(|row| {
case_map
.get(&row.case_id)
.is_some_and(|new| new == &row.case_id)
})
.collect::<Vec<_>>();
let moltenvk = old_moltenvk
.into_iter()
.filter(|row| {
case_map
.get(&row.case_id)
.is_some_and(|new| new == &row.case_id)
})
.collect::<Vec<_>>();
let vulkan = old_vulkan
.into_iter()
.filter(|row| {
case_map
.get(&row.case_id)
.is_some_and(|new| new == &row.case_id)
})
.collect::<Vec<_>>();
stats.observations_invalidated =
observations_before - metal.len() - moltenvk.len() - vulkan.len();
let (metal, metal_deduplicated) = deduplicate_exact_rows(
metal,
|row| (row.case_id.clone(), row.environment_id.clone()),
"Metal observation",
)?;
let (moltenvk, moltenvk_deduplicated) = deduplicate_exact_rows(
moltenvk,
|row| (row.case_id.clone(), row.environment_id.clone()),
"MoltenVK observation",
)?;
let (vulkan, vulkan_deduplicated) = deduplicate_exact_rows(
vulkan,
|row| (row.case_id.clone(), row.environment_id.clone()),
"Vulkan observation",
)?;
stats.observations_deduplicated =
metal_deduplicated + moltenvk_deduplicated + vulkan_deduplicated;
files.extend(write_aligned_rows(
&prepared.0,
"observations/metal",
metal,
|row: &crate::observation::MetalObservation| &row.air_sha256,
)?);
files.extend(write_aligned_rows(
&prepared.0,
"observations/moltenvk",
moltenvk,
|row: &crate::observation::CandidateObservation| &row.air_sha256,
)?);
files.extend(write_aligned_rows(
&prepared.0,
"observations/vulkan",
vulkan,
|row: &crate::observation::CandidateObservation| &row.air_sha256,
)?);
drop(connection);
let mut deletions = Vec::new();
files.retain(|(target, prepared)| {
let empty = fs::metadata(prepared).is_ok_and(|metadata| metadata.len() == 0);
if empty {
let _ = fs::remove_file(prepared);
deletions.push(target.clone());
}
!empty
});
store.commit_prepared_files_and_deletions(files, deletions)?;
crate::index::rebuild_index(root, &crate::index::default_index_path(root))?;
Ok(stats)
}
fn ingest_sources(
root: &Path,
connection: &mut Connection,
mapping: &mut HashMap<String, String>,
stats: &mut NormalizationStats,
) -> Result<(), String> {
for shard in 0..SHARD_COUNT {
let path = source::source_shard_path(root, shard);
if !path.is_file() {
continue;
}
let transaction = connection
.transaction()
.map_err(|error| format!("begin source normalization: {error}"))?;
source::for_each_source_shard(&path, |mut row| {
stats.source_rows_before += 1;
let old = row.air_sha256.clone();
row.air_ll = metal2vulkan::tools::sanitize_ll_text_with_datalayout(&row.air_ll).0;
row.air_sha256 = sha256_bytes(row.air_ll.as_bytes());
mapping.insert(old, row.air_sha256.clone());
insert_source(&transaction, &row)
})?;
transaction
.commit()
.map_err(|error| format!("commit source normalization: {error}"))?;
}
Ok(())
}
fn insert_source(transaction: &Transaction<'_>, row: &SourceRow) -> Result<(), String> {
let existing = transaction
.query_row(
"SELECT stage, entry, air_ll, blob_b64, label FROM sources WHERE hash=?1",
[&row.air_sha256],
|record| {
Ok((
record.get::<_, String>(0)?,
record.get::<_, String>(1)?,
record.get::<_, String>(2)?,
record.get::<_, Option<String>>(3)?,
record.get::<_, String>(4)?,
))
},
)
.optional()
.map_err(|error| format!("query normalized source {}: {error}", row.air_sha256))?;
if let Some((stage, entry, air_ll, blob, label)) = existing {
if (stage.as_str(), entry.as_str(), air_ll.as_str())
!= (row.stage.as_str(), row.entry.as_str(), row.air_ll.as_str())
{
return Err(format!("canonical source collision {}", row.air_sha256));
}
let preferred_blob =
if source::source_blob_is_preferred(blob.as_deref(), row.blob_b64.as_deref()) {
row.blob_b64.as_ref()
} else {
blob.as_ref()
};
transaction
.execute(
"UPDATE sources SET blob_b64=?2, label=?3 WHERE hash=?1",
params![row.air_sha256, preferred_blob, label.min(row.label.clone())],
)
.map_err(|error| format!("merge normalized source {}: {error}", row.air_sha256))?;
} else {
transaction
.execute(
"INSERT INTO sources VALUES (?1, ?2, ?3, ?4, ?5, ?6)",
params![
row.air_sha256,
row.stage,
row.entry,
row.air_ll,
row.blob_b64,
row.label
],
)
.map_err(|error| format!("insert normalized source {}: {error}", row.air_sha256))?;
}
for library in &row.lib_sha256s {
transaction
.execute(
"INSERT OR IGNORE INTO source_memberships VALUES (?1, ?2)",
params![row.air_sha256, library],
)
.map_err(|error| format!("merge source membership: {error}"))?;
}
Ok(())
}
fn ingest_modules(
root: &Path,
connection: &mut Connection,
mapping: &mut HashMap<String, String>,
stats: &mut NormalizationStats,
) -> Result<(), String> {
for shard in 0..SHARD_COUNT {
let path = library_module::library_module_shard_path(root, shard);
if !path.is_file() {
continue;
}
let transaction = connection
.transaction()
.map_err(|error| format!("begin module normalization: {error}"))?;
library_module::for_each_library_module_shard(&path, |mut row| {
stats.module_rows_before += 1;
let old = row.module_sha256.clone();
row.air_ll = metal2vulkan::tools::sanitize_ll_text_with_datalayout(&row.air_ll).0;
row.module_sha256 = sha256_bytes(row.air_ll.as_bytes());
mapping.insert(old, row.module_sha256.clone());
insert_module(&transaction, &row)
})?;
transaction
.commit()
.map_err(|error| format!("commit module normalization: {error}"))?;
}
Ok(())
}
fn insert_module(transaction: &Transaction<'_>, row: &LibraryModuleRow) -> Result<(), String> {
let existing = transaction
.query_row(
"SELECT air_ll, blob_b64, label FROM modules WHERE hash=?1",
[&row.module_sha256],
|record| {
Ok((
record.get::<_, String>(0)?,
record.get::<_, String>(1)?,
record.get::<_, String>(2)?,
))
},
)
.optional()
.map_err(|error| format!("query normalized module {}: {error}", row.module_sha256))?;
if let Some((air_ll, blob, label)) = existing {
if air_ll != row.air_ll {
return Err(format!("canonical module collision {}", row.module_sha256));
}
transaction
.execute(
"UPDATE modules SET blob_b64=?2, label=?3 WHERE hash=?1",
params![
row.module_sha256,
blob.min(row.blob_b64.clone()),
label.min(row.label.clone())
],
)
.map_err(|error| format!("merge normalized module {}: {error}", row.module_sha256))?;
} else {
transaction
.execute(
"INSERT INTO modules VALUES (?1, ?2, ?3, ?4)",
params![row.module_sha256, row.air_ll, row.blob_b64, row.label],
)
.map_err(|error| format!("insert normalized module {}: {error}", row.module_sha256))?;
}
for library in &row.lib_sha256s {
transaction
.execute(
"INSERT OR IGNORE INTO module_memberships VALUES (?1, ?2)",
params![row.module_sha256, library],
)
.map_err(|error| format!("merge module membership: {error}"))?;
}
Ok(())
}
fn remap_cases(
cases: Vec<AuthoredCase>,
source_map: &HashMap<String, String>,
module_map: &HashMap<String, String>,
stats: &mut NormalizationStats,
) -> Result<(Vec<AuthoredCase>, HashMap<String, String>), String> {
let mut identities = BTreeMap::<String, AuthoredCase>::new();
let mut case_map = HashMap::new();
for mut case in cases {
let old_case_id = case.case_id.clone();
if let Some(hash) = source_map.get(&case.air_sha256) {
case.air_sha256 = hash.clone();
}
for reference in &mut case.visible_function_references {
remap_module_hash(&mut reference.module_sha256, module_map);
}
for table in &mut case.visible_function_tables {
for entry in &mut table.entries {
remap_module_hash(&mut entry.module_sha256, module_map);
}
}
for table in case
.intersection_function_tables
.iter_mut()
.map(|table| &mut table.entries)
.chain(
case.argument_buffer_intersection_function_tables
.iter_mut()
.map(|table| &mut table.entries),
)
{
for entry in table {
if let IntersectionFunctionTableEntry::Linked { module_sha256, .. } = entry {
remap_module_hash(module_sha256, module_map);
}
}
}
case.case_id = case.computed_case_id()?;
case_map.insert(old_case_id.clone(), case.case_id.clone());
if old_case_id != case.case_id {
stats.cases_rewritten += 1;
}
match identities.get_mut(&case.case_id) {
Some(existing) => {
existing.name = existing.name.clone().min(case.name);
existing.rationale = merge_annotation(
"rationale",
&existing.rationale,
&case.rationale,
&case.case_id,
)?;
existing.authored_by = merge_annotation(
"authored_by",
&existing.authored_by,
&case.authored_by,
&case.case_id,
)?;
stats.cases_deduplicated += 1;
}
None => {
identities.insert(case.case_id.clone(), case);
}
}
}
let mut slots = BTreeMap::<(String, String), String>::new();
let mut cases = identities.into_values().collect::<Vec<_>>();
for case in &cases {
let key = (case.air_sha256.clone(), case.name.clone());
if let Some(existing) = slots.insert(key, case.case_id.clone()) {
return Err(format!(
"normalization gives case name {:?} conflicting semantics {} and {}",
case.name, existing, case.case_id
));
}
}
cases.sort_by(|left, right| {
left.air_sha256
.cmp(&right.air_sha256)
.then_with(|| left.name.cmp(&right.name))
});
Ok((cases, case_map))
}
fn merge_annotation(
field: &str,
current: &Option<String>,
candidate: &Option<String>,
case_id: &str,
) -> Result<Option<String>, String> {
match (current, candidate) {
(Some(current), Some(candidate)) if current != candidate => Err(format!(
"duplicate semantic case {case_id} has conflicting {field} annotations"
)),
(Some(current), _) => Ok(Some(current.clone())),
(None, Some(candidate)) => Ok(Some(candidate.clone())),
(None, None) => Ok(None),
}
}
fn deduplicate_exact_rows<T, K>(
rows: Vec<T>,
key: impl Fn(&T) -> K,
label: &str,
) -> Result<(Vec<T>, usize), String>
where
T: PartialEq,
K: Ord + std::fmt::Debug,
{
let mut unique = BTreeMap::new();
let mut duplicates = 0;
for row in rows {
let key = key(&row);
match unique.get(&key) {
Some(existing) if existing == &row => duplicates += 1,
Some(_) => return Err(format!("conflicting {label} slot {key:?}")),
None => {
unique.insert(key, row);
}
}
}
Ok((unique.into_values().collect(), duplicates))
}
fn remap_module_hash(hash: &mut String, mapping: &HashMap<String, String>) {
if let Some(canonical) = mapping.get(hash) {
hash.clone_from(canonical);
}
}
fn remap_reviews(
reviews: Vec<crate::review::ReviewNote>,
source_map: &HashMap<String, String>,
case_airs: &std::collections::HashSet<&str>,
stats: &mut NormalizationStats,
) -> Result<Vec<crate::review::ReviewNote>, String> {
let mut rows = BTreeMap::new();
for mut review in reviews {
if let Some(hash) = source_map.get(&review.air_sha256) {
review.air_sha256 = hash.clone();
}
if case_airs.contains(review.air_sha256.as_str()) {
stats.reviews_superseded += 1;
continue;
}
match rows.get(&review.air_sha256) {
Some(existing) if existing == &review => {}
Some(_) => {
return Err(format!(
"normalization gives AIR {} conflicting review notes",
review.air_sha256
));
}
None => {
rows.insert(review.air_sha256.clone(), review);
}
}
}
Ok(rows.into_values().collect())
}
fn write_normalized_air(
prepared: &Path,
connection: &Connection,
stats: &mut NormalizationStats,
) -> Result<Vec<(PathBuf, PathBuf)>, String> {
let mut files = Vec::new();
let mut source_writers = prepared_shard_writers(prepared, "local/sources", &mut files)?;
let mut source_memberships = connection
.prepare("SELECT library FROM source_memberships WHERE hash=?1 ORDER BY library")
.map_err(|error| format!("prepare normalized source memberships: {error}"))?;
let mut sources = connection
.prepare("SELECT hash, stage, entry, air_ll, blob_b64, label FROM sources ORDER BY hash")
.map_err(|error| format!("prepare normalized sources: {error}"))?;
let rows = sources
.query_map([], |row| {
Ok((
row.get::<_, String>(0)?,
row.get::<_, String>(1)?,
row.get::<_, String>(2)?,
row.get::<_, String>(3)?,
row.get::<_, Option<String>>(4)?,
row.get::<_, String>(5)?,
))
})
.map_err(|error| format!("query normalized sources: {error}"))?;
for row in rows {
let (hash, stage, entry, air_ll, blob_b64, label) =
row.map_err(|error| format!("read normalized source: {error}"))?;
let lib_sha256s = source_memberships
.query_map([&hash], |row| row.get(0))
.map_err(|error| format!("query source memberships: {error}"))?
.collect::<Result<Vec<String>, _>>()
.map_err(|error| format!("read source memberships: {error}"))?;
let row = SourceRow {
air_sha256: hash.clone(),
stage,
entry,
air_ll,
blob_b64,
lib_sha256s,
label,
};
row.validate()?;
write_json_line(
&mut source_writers[source::shard_index_for_hash(&hash)?],
&row,
)?;
stats.source_rows_after += 1;
}
finish_writers(&mut source_writers)?;
let mut module_writers = prepared_shard_writers(prepared, "local/library-modules", &mut files)?;
let mut module_memberships = connection
.prepare("SELECT library FROM module_memberships WHERE hash=?1 ORDER BY library")
.map_err(|error| format!("prepare normalized module memberships: {error}"))?;
let mut modules = connection
.prepare("SELECT hash, air_ll, blob_b64, label FROM modules ORDER BY hash")
.map_err(|error| format!("prepare normalized modules: {error}"))?;
let rows = modules
.query_map([], |row| {
Ok((
row.get::<_, String>(0)?,
row.get::<_, String>(1)?,
row.get::<_, String>(2)?,
row.get::<_, String>(3)?,
))
})
.map_err(|error| format!("query normalized modules: {error}"))?;
for row in rows {
let (hash, air_ll, blob_b64, label) =
row.map_err(|error| format!("read normalized module: {error}"))?;
let lib_sha256s = module_memberships
.query_map([&hash], |row| row.get(0))
.map_err(|error| format!("query module memberships: {error}"))?
.collect::<Result<Vec<String>, _>>()
.map_err(|error| format!("read module memberships: {error}"))?;
let row = LibraryModuleRow {
module_sha256: hash.clone(),
air_ll,
blob_b64,
lib_sha256s,
label,
};
row.validate()?;
write_json_line(
&mut module_writers[source::shard_index_for_hash(&hash)?],
&row,
)?;
stats.module_rows_after += 1;
}
finish_writers(&mut module_writers)?;
Ok(files)
}
fn write_aligned_rows<T: serde::Serialize>(
prepared: &Path,
relative_dir: &str,
rows: Vec<T>,
hash: impl Fn(&T) -> &String,
) -> Result<Vec<(PathBuf, PathBuf)>, String> {
let mut buckets = (0..SHARD_COUNT)
.map(|_| Vec::new())
.collect::<Vec<Vec<String>>>();
for row in rows {
let shard = source::shard_index_for_hash(hash(&row))?;
buckets[shard].push(
to_sorted_json_string(&row)
.map_err(|error| format!("serialize aligned row: {error}"))?,
);
}
let mut files = Vec::new();
let mut writers = prepared_shard_writers(prepared, relative_dir, &mut files)?;
for (writer, lines) in writers.iter_mut().zip(&mut buckets) {
lines.sort();
for line in lines {
writeln!(writer, "{line}")
.map_err(|error| format!("write prepared {relative_dir}: {error}"))?;
}
}
finish_writers(&mut writers)?;
Ok(files)
}
fn prepared_shard_writers(
prepared: &Path,
relative_dir: &str,
files: &mut Vec<(PathBuf, PathBuf)>,
) -> Result<Vec<BufWriter<File>>, String> {
let directory = prepared.join("files").join(relative_dir);
fs::create_dir_all(&directory)
.map_err(|error| format!("create {}: {error}", directory.display()))?;
(0..SHARD_COUNT)
.map(|shard| {
let name = source::shard_name(shard);
let path = directory.join(&name);
let file = File::create(&path)
.map_err(|error| format!("create {}: {error}", path.display()))?;
files.push((PathBuf::from(relative_dir).join(name), path));
Ok(BufWriter::new(file))
})
.collect()
}
fn write_json_line(
writer: &mut BufWriter<File>,
row: &impl serde::Serialize,
) -> Result<(), String> {
let line = to_sorted_json_string(row).map_err(|error| format!("serialize row: {error}"))?;
writeln!(writer, "{line}").map_err(|error| format!("write normalized row: {error}"))
}
fn finish_writers(writers: &mut [BufWriter<File>]) -> Result<(), String> {
for writer in writers {
writer
.flush()
.map_err(|error| format!("flush normalized shard: {error}"))?;
writer
.get_ref()
.sync_all()
.map_err(|error| format!("fsync normalized shard: {error}"))?;
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use crate::case::LinkedFunctionResource;
use crate::observation::{MetalObservation, MetalStatus};
use crate::ScratchDir;
#[test]
fn normalization_deduplicates_air_and_invalidates_changed_evidence_atomically() {
let scratch = ScratchDir::new("normalize-air-identities").unwrap();
let root = scratch.path();
let canonical_entry = crate::case::ATTACHMENTLESS_FRAGMENT_AIR;
let entry_a = format!("; ModuleID = '/scratch/a.air'\n{canonical_entry}");
let entry_b = format!("; ModuleID = '/scratch/b.air'\n{canonical_entry}");
let source_a = source_row(&entry_a, "11", "YQ==");
let source_b = source_row(&entry_b, "22", "Yg==");
source::write_source_shards(root, [source_a.clone(), source_b.clone()]).unwrap();
let canonical_module = "define void @linked() { ret void }\n";
let module_a = module_row(
&format!("; ModuleID = '/scratch/a-linked.air'\n{canonical_module}"),
"11",
"YQ==",
);
let module_b = module_row(
&format!("; ModuleID = '/scratch/b-linked.air'\n{canonical_module}"),
"22",
"Yg==",
);
library_module::merge_library_module_shards(root, [module_a.clone(), module_b.clone()])
.unwrap();
let store = CorpusStore::new(root);
let mut case_a = crate::case::attachmentless_fragment_test_case(
source_a.air_sha256.clone(),
"fragment_no_writes".into(),
);
case_a.visible_function_references = vec![LinkedFunctionResource {
module_sha256: module_a.module_sha256.clone(),
function: "linked".into(),
}];
case_a.case_id = case_a.computed_case_id().unwrap();
let old_case_id = case_a.case_id.clone();
store.put_case(case_a.clone()).unwrap();
let mut case_b = case_a.clone();
case_b.air_sha256 = source_b.air_sha256.clone();
case_b.visible_function_references[0].module_sha256 = module_b.module_sha256.clone();
case_b.name = "alternate-evidence-name".into();
case_b.case_id = case_b.computed_case_id().unwrap();
store.put_case(case_b).unwrap();
let empty_hash = sha256_bytes(&[]);
store
.upsert_metal(MetalObservation {
case_id: old_case_id,
air_sha256: source_a.air_sha256.clone(),
input_sha256: case_a.computed_input_sha256().unwrap(),
metal_output_sha256: empty_hash,
output_b64: String::new(),
environment_id: "test-metal".into(),
environment: serde_json::json!({}),
oracle_abi: "test-v1".into(),
status: MetalStatus::Qualified,
})
.unwrap();
crate::index::rebuild_index(root, &crate::index::default_index_path(root)).unwrap();
let stats = normalize_air_identities(root).unwrap();
assert_eq!(stats.source_rows_before, 2);
assert_eq!(stats.source_rows_after, 1);
assert_eq!(stats.module_rows_before, 2);
assert_eq!(stats.module_rows_after, 1);
assert_eq!(stats.cases_rewritten, 2);
assert_eq!(stats.cases_deduplicated, 1);
assert_eq!(stats.observations_invalidated, 1);
let canonical_entry =
metal2vulkan::tools::sanitize_ll_text_with_datalayout(canonical_entry).0;
let canonical_entry_hash = sha256_bytes(canonical_entry.as_bytes());
let sources = source::read_source_shard(&source::source_shard_path(
root,
source::shard_index_for_hash(&canonical_entry_hash).unwrap(),
))
.unwrap();
let source = sources
.iter()
.find(|row| row.air_sha256 == canonical_entry_hash)
.unwrap();
assert_eq!(source.lib_sha256s, vec!["11".repeat(32), "22".repeat(32)]);
assert!(source.blob_b64.is_some());
let canonical_module_hash = sha256_bytes(canonical_module.as_bytes());
let module = library_module::find_library_module(root, &canonical_module_hash)
.unwrap()
.unwrap();
assert_eq!(module.lib_sha256s, vec!["11".repeat(32), "22".repeat(32)]);
let cases = store.read_all_cases().unwrap();
assert_eq!(cases.len(), 1);
assert_eq!(cases[0].name, "alternate-evidence-name");
assert_eq!(cases[0].air_sha256, canonical_entry_hash);
assert_eq!(
cases[0].visible_function_references[0].module_sha256,
canonical_module_hash
);
assert!(store.read_metal().unwrap().is_empty());
crate::index::check_index(root, &crate::index::default_index_path(root)).unwrap();
let second = normalize_air_identities(root).unwrap();
assert_eq!(second.source_rows_before, 1);
assert_eq!(second.source_rows_after, 1);
assert_eq!(second.module_rows_before, 1);
assert_eq!(second.module_rows_after, 1);
assert_eq!(second.cases_rewritten, 0);
assert_eq!(second.cases_deduplicated, 0);
assert_eq!(second.observations_invalidated, 0);
}
fn source_row(air_ll: &str, library_byte: &str, blob: &str) -> SourceRow {
SourceRow {
air_sha256: sha256_bytes(air_ll.as_bytes()),
stage: "Fragment".into(),
entry: "fragment_no_writes".into(),
air_ll: air_ll.into(),
blob_b64: Some(blob.into()),
lib_sha256s: vec![library_byte.repeat(32)],
label: format!("local/{library_byte}.ll"),
}
}
fn module_row(air_ll: &str, library_byte: &str, blob: &str) -> LibraryModuleRow {
LibraryModuleRow {
module_sha256: sha256_bytes(air_ll.as_bytes()),
air_ll: air_ll.into(),
blob_b64: blob.into(),
lib_sha256s: vec![library_byte.repeat(32)],
label: format!("local/library-module/{library_byte}.ll"),
}
}
}
+43 -6
View File
@@ -87,9 +87,6 @@ impl MetalObservation {
let output = base64::engine::general_purpose::STANDARD
.decode(&self.output_b64)
.map_err(|error| format!("invalid Metal output_b64: {error}"))?;
if output.is_empty() {
return Err("Metal output_b64 must not be empty".into());
}
let computed = sha256_bytes(&output);
if computed != self.metal_output_sha256 {
return Err(format!(
@@ -147,9 +144,6 @@ impl CandidateObservation {
let output = base64::engine::general_purpose::STANDARD
.decode(&self.output_b64)
.map_err(|error| format!("invalid candidate output_b64: {error}"))?;
if output.is_empty() {
return Err("candidate output_b64 must not be empty".into());
}
let computed = sha256_bytes(&output);
if computed != self.candidate_output_sha256 {
return Err(format!(
@@ -224,6 +218,7 @@ mod tests {
initial_bytes_b64: Some("AAAAAA==".into()),
}],
argument_buffer_buffers: vec![],
device_buffer_arrays: vec![],
threadgroup_memory: vec![],
imageblock: None,
fragment_imageblock: None,
@@ -383,4 +378,46 @@ mod tests {
.unwrap_err()
.contains("hash mismatch"));
}
#[test]
fn canonical_empty_observation_payload_is_hash_checked() {
let case = case();
let empty_sha256 = sha256_bytes(&[]);
let metal = MetalObservation {
case_id: case.case_id.clone(),
air_sha256: case.air_sha256.clone(),
input_sha256: case.computed_input_sha256().unwrap(),
metal_output_sha256: empty_sha256.clone(),
output_b64: String::new(),
environment_id: "metal-env".into(),
environment: serde_json::json!({}),
oracle_abi: "oracle-v1".into(),
status: MetalStatus::Qualified,
};
assert!(metal.validate_content().is_ok());
let input_sha256 = case.computed_input_sha256().unwrap();
let mut candidate = CandidateObservation {
case_id: case.case_id,
air_sha256: case.air_sha256,
input_sha256,
golden_output_sha256: empty_sha256.clone(),
spv_sha256: "33".repeat(32),
translator_fingerprint: "55".repeat(32),
candidate_output_sha256: empty_sha256,
output_b64: String::new(),
backend: Backend::Vulkan,
environment_id: "vk-env".into(),
environment: serde_json::json!({}),
executor_abi: "executor-v1".into(),
comparison: ComparisonResult::Exact,
status: CandidateStatus::Match,
};
assert!(candidate.validate_content().is_ok());
candidate.candidate_output_sha256 = "00".repeat(32);
assert!(candidate
.validate_content()
.unwrap_err()
.contains("hash mismatch"));
}
}
+216 -34
View File
@@ -16,6 +16,7 @@ pub const CORPUS_DIR_ENV: &str = "METAL2VULKAN_CORPUS_DIR";
pub struct SourceMergeStats {
pub affected_shards: usize,
pub inserted: usize,
pub merged_memberships: usize,
pub replaced: usize,
pub duplicates: usize,
}
@@ -37,6 +38,7 @@ pub(crate) struct SourceIndexLocation {
pub stage: String,
pub entry: String,
pub label: String,
pub lib_sha256s: Vec<String>,
pub offset: i64,
pub length: i64,
}
@@ -50,7 +52,11 @@ pub struct SourceRow {
pub air_ll: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub blob_b64: Option<String>,
pub lib_sha256: String,
#[serde(
alias = "lib_sha256",
deserialize_with = "deserialize_library_memberships"
)]
pub lib_sha256s: Vec<String>,
pub label: String,
}
@@ -60,7 +66,11 @@ struct AnalysisRow {
stage: String,
entry: String,
air_ll: String,
lib_sha256: String,
#[serde(
alias = "lib_sha256",
deserialize_with = "deserialize_library_memberships"
)]
lib_sha256s: Vec<String>,
label: String,
}
@@ -99,18 +109,28 @@ impl SourceRow {
if self.label.trim().is_empty() {
return Err("source label must not be empty".into());
}
if self.lib_sha256 != "owned-synthetic"
&& (self.lib_sha256.len() != 64
|| !self.lib_sha256.bytes().all(|byte| byte.is_ascii_hexdigit())
|| self
.lib_sha256
.bytes()
.any(|byte| byte.is_ascii_uppercase()))
{
return Err(format!(
"source {} lib_sha256 must be lowercase SHA-256",
self.label
));
if self.lib_sha256s.is_empty() {
return Err(format!("source {} has no parent library", self.label));
}
let mut previous = None;
for hash in &self.lib_sha256s {
if hash != "owned-synthetic"
&& (hash.len() != 64
|| !hash.bytes().all(|byte| byte.is_ascii_hexdigit())
|| hash.bytes().any(|byte| byte.is_ascii_uppercase()))
{
return Err(format!(
"source {} parent library must be lowercase SHA-256",
self.label
));
}
if previous.is_some_and(|value: &String| value >= hash) {
return Err(format!(
"source {} parent libraries must be sorted and unique",
self.label
));
}
previous = Some(hash);
}
if let Some(blob) = &self.blob_b64 {
let decoded = base64::engine::general_purpose::STANDARD
@@ -124,6 +144,23 @@ impl SourceRow {
}
}
fn deserialize_library_memberships<'de, D>(deserializer: D) -> Result<Vec<String>, D::Error>
where
D: serde::Deserializer<'de>,
{
#[derive(Deserialize)]
#[serde(untagged)]
enum Memberships {
One(String),
Many(Vec<String>),
}
Ok(match Memberships::deserialize(deserializer)? {
Memberships::One(hash) => vec![hash],
Memberships::Many(hashes) => hashes,
})
}
pub fn corpus_root() -> PathBuf {
std::env::var_os(CORPUS_DIR_ENV)
.map(PathBuf::from)
@@ -232,6 +269,51 @@ pub fn indexed_source_hashes(root: &Path) -> Result<std::collections::HashSet<St
Ok(hashes)
}
/// Load indexed parent-library memberships without opening source storage.
///
/// A legacy index can return no memberships for an existing AIR identity. Harvest treats that as
/// unknown and merges the rediscovered row through its exact hash-derived shard, which fills the
/// compact membership facts without a corpus scan.
pub fn indexed_source_memberships(
root: &Path,
) -> Result<std::collections::HashMap<String, std::collections::HashSet<String>>, String> {
let index = root.join(".index.sqlite");
if !index.is_file() {
return Ok(std::collections::HashMap::new());
}
let connection = rusqlite::Connection::open(&index)
.map_err(|error| format!("open source index {}: {error}", index.display()))?;
connection
.execute_batch(
"PRAGMA foreign_keys=ON;
CREATE TABLE IF NOT EXISTS source_library_memberships (
air_sha256 TEXT NOT NULL REFERENCES sources(air_sha256) ON DELETE CASCADE,
lib_sha256 TEXT NOT NULL,
PRIMARY KEY(air_sha256, lib_sha256)
);",
)
.map_err(|error| format!("upgrade source-membership index: {error}"))?;
let mut statement = connection
.prepare("SELECT air_sha256, lib_sha256 FROM source_library_memberships")
.map_err(|error| format!("prepare indexed source memberships: {error}"))?;
let mut memberships =
std::collections::HashMap::<String, std::collections::HashSet<String>>::new();
let rows = statement
.query_map([], |row| {
Ok((row.get::<_, String>(0)?, row.get::<_, String>(1)?))
})
.map_err(|error| format!("query indexed source memberships: {error}"))?;
for row in rows {
let (air_sha256, lib_sha256) =
row.map_err(|error| format!("read indexed source membership: {error}"))?;
memberships
.entry(air_sha256)
.or_default()
.insert(lib_sha256);
}
Ok(memberships)
}
pub fn write_source_shards(
root: &Path,
rows: impl IntoIterator<Item = SourceRow>,
@@ -290,19 +372,38 @@ pub fn merge_source_shards(
.map(|row| (row.air_sha256.clone(), row))
.collect::<std::collections::BTreeMap<_, _>>();
let mut changed = false;
for row in new_rows {
match by_hash.get(&row.air_sha256) {
for mut row in new_rows {
match by_hash.get_mut(&row.air_sha256) {
None => {
stats.inserted += 1;
changed = true;
by_hash.insert(row.air_sha256.clone(), row);
}
Some(previous) if row.lib_sha256 < previous.lib_sha256 => {
stats.replaced += 1;
changed = true;
by_hash.insert(row.air_sha256.clone(), row);
Some(previous) => {
let before = previous.lib_sha256s.len();
previous.lib_sha256s.append(&mut row.lib_sha256s);
previous.lib_sha256s.sort();
previous.lib_sha256s.dedup();
let added_memberships = previous.lib_sha256s.len() - before;
stats.merged_memberships += added_memberships;
let blob_changed = source_blob_is_preferred(
previous.blob_b64.as_deref(),
row.blob_b64.as_deref(),
);
if blob_changed {
previous.blob_b64 = row.blob_b64;
}
let label_changed = row.label < previous.label;
if label_changed {
previous.label = row.label;
}
if added_memberships > 0 || blob_changed || label_changed {
stats.replaced += usize::from(blob_changed || label_changed);
changed = true;
} else {
stats.duplicates += 1;
}
}
Some(_) => stats.duplicates += 1,
}
}
if !changed {
@@ -315,6 +416,15 @@ pub fn merge_source_shards(
Ok(stats)
}
/// Return whether a candidate optional AIR blob preserves more deterministic source information.
pub fn source_blob_is_preferred(current: Option<&str>, candidate: Option<&str>) -> bool {
match (current, candidate) {
(None, Some(_)) => true,
(Some(current), Some(candidate)) => candidate < current,
(None, None) | (Some(_), None) => false,
}
}
fn write_source_bucket(
root: &Path,
index: usize,
@@ -343,6 +453,7 @@ fn write_source_bucket(
stage: row.stage.clone(),
entry: row.entry.clone(),
label: row.label.clone(),
lib_sha256s: row.lib_sha256s.clone(),
offset: offset
.try_into()
.map_err(|_| format!("source offset in {} is too large", path.display()))?,
@@ -399,9 +510,21 @@ fn sync_directory(path: &Path) -> Result<(), String> {
}
pub fn read_source_shard(path: &Path) -> Result<Vec<SourceRow>, String> {
let mut rows = Vec::new();
for_each_source_shard(path, |row| {
rows.push(row);
Ok(())
})?;
Ok(rows)
}
/// Stream fully validated source rows while retaining at most one decoded row at a time.
pub fn for_each_source_shard(
path: &Path,
mut consume: impl FnMut(SourceRow) -> Result<(), String>,
) -> Result<(), String> {
let expected_shard = shard_index_from_path(path)?;
let file = File::open(path).map_err(|error| format!("open {}: {error}", path.display()))?;
let mut rows = Vec::new();
for (index, line) in BufReader::new(file).lines().enumerate() {
let line =
line.map_err(|error| format!("read {}:{}: {error}", path.display(), index + 1))?;
@@ -423,9 +546,9 @@ pub fn read_source_shard(path: &Path) -> Result<Vec<SourceRow>, String> {
expected_shard
));
}
rows.push(row);
consume(row)?;
}
Ok(rows)
Ok(())
}
/// Stream the authoring-relevant projection of a canonical harvested shard.
@@ -655,7 +778,7 @@ fn analysis_source_from_json(bytes: &[u8], expected_shard: usize) -> Result<Sour
entry: row.entry,
air_ll: row.air_ll,
blob_b64: None,
lib_sha256: row.lib_sha256,
lib_sha256s: row.lib_sha256s,
label: row.label,
})
}
@@ -840,7 +963,7 @@ fn public_source_row(path: PathBuf) -> Result<SourceRow, String> {
entry,
air_ll,
blob_b64: None,
lib_sha256: "owned-synthetic".into(),
lib_sha256s: vec!["owned-synthetic".into()],
label: format!(
"public/{}",
path.file_name()
@@ -917,7 +1040,7 @@ mod tests {
entry: "main".into(),
air_ll: ll.into(),
blob_b64: Some("YmxvYg==".into()),
lib_sha256: "22".repeat(32),
lib_sha256s: vec!["22".repeat(32)],
label: "local/test.ll".into(),
};
write_source_shards(scratch.path(), [row.clone()]).unwrap();
@@ -946,7 +1069,7 @@ mod tests {
let mut selected = public_sources().unwrap().remove(0);
selected.air_ll.push_str("\n; selected private source\n");
selected.air_sha256 = sha256_bytes(selected.air_ll.as_bytes());
selected.lib_sha256 = "22".repeat(32);
selected.lib_sha256s = vec!["22".repeat(32)];
selected.label = "local/selected.ll".into();
let selected_shard = shard_index_for_hash(&selected.air_sha256).unwrap();
let mut unrelated = selected.clone();
@@ -966,14 +1089,15 @@ mod tests {
let unreadable_canonical_data = vec![b'x'; unrelated_bytes.len()];
fs::write(&unrelated_path, &unreadable_canonical_data).unwrap();
selected.lib_sha256 = "11".repeat(32);
selected.lib_sha256s = vec!["11".repeat(32)];
let stats = merge_source_shards(scratch.path(), [selected.clone()]).unwrap();
assert_eq!(
stats,
SourceMergeStats {
affected_shards: 1,
inserted: 0,
replaced: 1,
merged_memberships: 1,
replaced: 0,
duplicates: 0,
}
);
@@ -985,8 +1109,8 @@ mod tests {
read_source_shard(&source_shard_path(scratch.path(), selected_shard))
.unwrap()
.remove(0)
.lib_sha256,
selected.lib_sha256
.lib_sha256s,
vec!["11".repeat(32), "22".repeat(32)]
);
}
@@ -1015,6 +1139,37 @@ mod tests {
);
}
#[test]
fn indexed_parent_libraries_are_compact_and_legacy_safe() {
let scratch = ScratchDir::new("source-library-memberships").unwrap();
let index = scratch.path().join(".index.sqlite");
let hash = "11".repeat(32);
let connection = rusqlite::Connection::open(&index).unwrap();
connection
.execute_batch("CREATE TABLE sources (air_sha256 TEXT PRIMARY KEY);")
.unwrap();
connection
.execute("INSERT INTO sources VALUES (?1)", [&hash])
.unwrap();
drop(connection);
assert!(indexed_source_memberships(scratch.path())
.unwrap()
.is_empty());
let connection = rusqlite::Connection::open(&index).unwrap();
connection
.execute(
"INSERT INTO source_library_memberships VALUES (?1, ?2)",
rusqlite::params![hash, "22".repeat(32)],
)
.unwrap();
drop(connection);
assert_eq!(
indexed_source_memberships(scratch.path()).unwrap()[&hash],
["22".repeat(32)].into_iter().collect()
);
}
#[test]
fn duplicate_merge_does_not_replace_an_unchanged_shard_file() {
use std::os::unix::fs::MetadataExt as _;
@@ -1023,7 +1178,7 @@ mod tests {
let mut row = public_sources().unwrap().remove(0);
row.air_ll.push_str("\n; duplicate no-rewrite fixture\n");
row.air_sha256 = sha256_bytes(row.air_ll.as_bytes());
row.lib_sha256 = "11".repeat(32);
row.lib_sha256s = vec!["11".repeat(32)];
row.label = "local/duplicate.ll".into();
write_source_shards(scratch.path(), [row.clone()]).unwrap();
let path = source_shard_path(
@@ -1039,6 +1194,33 @@ mod tests {
assert_eq!(fs::metadata(path).unwrap().ino(), inode);
}
#[test]
fn duplicate_merge_preserves_an_available_original_blob() {
let scratch = ScratchDir::new("source-blob-preservation").unwrap();
let mut row = public_sources().unwrap().remove(0);
row.air_ll
.push_str("\n; source blob preservation fixture\n");
row.air_sha256 = sha256_bytes(row.air_ll.as_bytes());
row.lib_sha256s = vec!["11".repeat(32)];
row.label = "local/blob.ll".into();
row.blob_b64 = None;
write_source_shards(scratch.path(), [row.clone()]).unwrap();
row.blob_b64 = Some("YmxvYg==".into());
let stats = merge_source_shards(scratch.path(), [row.clone()]).unwrap();
assert_eq!(stats.replaced, 1);
assert_eq!(
read_source_shard(&source_shard_path(
scratch.path(),
shard_index_for_hash(&row.air_sha256).unwrap(),
))
.unwrap()
.remove(0)
.blob_b64,
row.blob_b64
);
}
#[test]
fn public_source_lookup_survives_an_unrelated_private_bucket_file() {
let scratch = ScratchDir::new("public-source-fallback").unwrap();
@@ -1067,7 +1249,7 @@ mod tests {
entry: "main".into(),
air_ll: ll.into(),
blob_b64: None,
lib_sha256: "22".repeat(32),
lib_sha256s: vec!["22".repeat(32)],
label: "local/test.ll".into(),
};
let actual = shard_index_for_hash(&row.air_sha256).unwrap();
+341 -14
View File
@@ -1,4 +1,4 @@
use crate::case::AuthoredCase;
use crate::case::{AuthoredCase, OutputSelection};
use crate::jsonl::to_sorted_json_string;
use crate::observation::{Backend, CandidateObservation, MetalObservation};
use crate::review::ReviewNote;
@@ -31,6 +31,8 @@ struct TransactionManifest {
struct TransactionEntry {
staged: String,
target: String,
#[serde(default)]
delete: bool,
}
impl CorpusStore {
@@ -82,12 +84,52 @@ impl CorpusStore {
Ok(rows)
}
/// Read structurally valid legacy cases while deferring uniqueness to an identity migration.
pub(crate) fn read_all_cases_for_identity_migration(
&self,
) -> Result<Vec<AuthoredCase>, String> {
let mut rows = Vec::new();
for path in shard_paths(&self.root.join("cases"))? {
let expected = shard_index_from_path(&path)?;
for row in read_jsonl_if_exists::<AuthoredCase>(&path)? {
row.validate_literal_resources()
.map_err(|errors| format!("case {}: {}", row.case_id, errors.join("; ")))?;
let computed = row.computed_case_id()?;
if computed != row.case_id {
return Err(format!(
"case {} identity mismatch: computed {computed}",
row.case_id
));
}
let actual = shard_index_for_hash(&row.air_sha256)?;
if actual != expected {
return Err(format!(
"case {} is in shard {}, expected {}",
row.case_id, expected, actual
));
}
rows.push(row);
}
}
Ok(rows)
}
pub fn read_case_shard(&self, index: usize) -> Result<Vec<AuthoredCase>, String> {
let rows = read_jsonl_if_exists(&self.root.join("cases").join(shard_name(index)))?;
validate_cases(&rows, Some(index))?;
Ok(rows)
}
/// Read authored cases for one AIR identity from only its hash-derived case shard.
pub fn find_cases_for_air(&self, air_sha256: &str) -> Result<Vec<AuthoredCase>, String> {
let shard = shard_index_for_hash(air_sha256)?;
Ok(self
.read_case_shard(shard)?
.into_iter()
.filter(|case| case.air_sha256 == air_sha256)
.collect())
}
pub fn find_case(&self, case_id: &str) -> Result<Option<AuthoredCase>, String> {
Ok(self
.read_all_cases()?
@@ -320,7 +362,13 @@ impl CorpusStore {
self.recover_transactions()?;
row.validate_content()?;
let index = shard_index_for_hash(&row.air_sha256)?;
self.validate_observation_case(index, &row.case_id, &row.air_sha256, &row.input_sha256)?;
self.validate_observation_case(
index,
&row.case_id,
&row.air_sha256,
&row.input_sha256,
&row.output_b64,
)?;
let relative = PathBuf::from("observations/metal").join(shard_name(index));
let mut rows: Vec<MetalObservation> = read_jsonl_if_exists(&self.root.join(&relative))?;
validate_aligned_observation_rows(&rows, index)?;
@@ -341,7 +389,13 @@ impl CorpusStore {
self.recover_transactions()?;
row.validate_content()?;
let index = shard_index_for_hash(&row.air_sha256)?;
self.validate_observation_case(index, &row.case_id, &row.air_sha256, &row.input_sha256)?;
self.validate_observation_case(
index,
&row.case_id,
&row.air_sha256,
&row.input_sha256,
&row.output_b64,
)?;
let relative = PathBuf::from("observations")
.join(row.backend.directory())
.join(shard_name(index));
@@ -371,6 +425,7 @@ impl CorpusStore {
case_id: &str,
air_sha256: &str,
input_sha256: &str,
output_b64: &str,
) -> Result<(), String> {
let case = self
.read_case_shard(index)?
@@ -389,20 +444,31 @@ impl CorpusStore {
"observation input {input_sha256} does not match case input {expected}"
));
}
validate_observation_output(&case, output_b64)?;
Ok(())
}
pub fn read_metal(&self) -> Result<Vec<MetalObservation>, String> {
let rows: Vec<MetalObservation> =
read_aligned_observations(&self.root.join("observations/metal"))?;
self.validate_observation_cases(
rows.iter()
.map(|row| (&row.case_id, &row.air_sha256, &row.input_sha256)),
)?;
self.validate_observation_cases(rows.iter().map(|row| {
(
&row.case_id,
&row.air_sha256,
&row.input_sha256,
&row.output_b64,
)
}))?;
reject_duplicate_metal_slots(&rows)?;
Ok(rows)
}
pub(crate) fn read_metal_for_identity_migration(
&self,
) -> Result<Vec<MetalObservation>, String> {
read_aligned_observations(&self.root.join("observations/metal"))
}
pub fn read_candidates(&self, backend: Backend) -> Result<Vec<CandidateObservation>, String> {
let rows: Vec<CandidateObservation> =
read_aligned_observations(&self.root.join("observations").join(backend.directory()))?;
@@ -416,24 +482,43 @@ impl CorpusStore {
));
}
}
self.validate_observation_cases(
rows.iter()
.map(|row| (&row.case_id, &row.air_sha256, &row.input_sha256)),
)?;
self.validate_observation_cases(rows.iter().map(|row| {
(
&row.case_id,
&row.air_sha256,
&row.input_sha256,
&row.output_b64,
)
}))?;
reject_duplicate_candidate_slots(&rows)?;
Ok(rows)
}
pub(crate) fn read_candidates_for_identity_migration(
&self,
backend: Backend,
) -> Result<Vec<CandidateObservation>, String> {
let rows: Vec<CandidateObservation> =
read_aligned_observations(&self.root.join("observations").join(backend.directory()))?;
if rows.iter().any(|row| row.backend != backend) {
return Err(format!(
"candidate observation is stored outside its {} directory",
backend.directory()
));
}
Ok(rows)
}
fn validate_observation_cases<'a>(
&self,
rows: impl IntoIterator<Item = (&'a String, &'a String, &'a String)>,
rows: impl IntoIterator<Item = (&'a String, &'a String, &'a String, &'a String)>,
) -> Result<(), String> {
let cases = self.read_all_cases()?;
let cases = cases
.iter()
.map(|case| (case.case_id.as_str(), case))
.collect::<std::collections::HashMap<_, _>>();
for (case_id, air_sha256, input_sha256) in rows {
for (case_id, air_sha256, input_sha256, output_b64) in rows {
let case = cases
.get(case_id.as_str())
.ok_or_else(|| format!("observation references unknown case_id {case_id}"))?;
@@ -449,6 +534,7 @@ impl CorpusStore {
"observation input {input_sha256} does not match case input {expected}"
));
}
validate_observation_output(case, output_b64)?;
}
Ok(())
}
@@ -480,6 +566,7 @@ impl CorpusStore {
.to_str()
.ok_or_else(|| format!("non-UTF-8 target {}", target.display()))?
.into(),
delete: false,
});
}
let manifest = TransactionManifest { entries };
@@ -495,6 +582,88 @@ impl CorpusStore {
sync_directory(&transaction)?;
apply_transaction(&transaction, &self.root, &manifest)
}
/// Atomically publish already-prepared files through the corpus recovery protocol.
///
/// Callers can stream large replacements to files under the corpus filesystem instead of
/// retaining their bytes in memory. Targets must be relative corpus paths. Once this returns,
/// each prepared file has been consumed.
pub(crate) fn commit_prepared_files_and_deletions(
&self,
files: impl IntoIterator<Item = (PathBuf, PathBuf)>,
deletions: impl IntoIterator<Item = PathBuf>,
) -> Result<(), String> {
self.recover_transactions()?;
let nonce = SystemTime::now()
.duration_since(UNIX_EPOCH)
.map_err(|error| format!("system clock: {error}"))?
.as_nanos();
let transaction = self
.root
.join(".transactions")
.join(format!("{}-{nonce}", std::process::id()));
fs::create_dir_all(&transaction)
.map_err(|error| format!("create {}: {error}", transaction.display()))?;
let mut entries = Vec::new();
let mut targets = HashSet::new();
for (index, (target, prepared)) in files.into_iter().enumerate() {
validate_transaction_target(&target)?;
if !targets.insert(target.clone()) {
return Err(format!("duplicate transaction target {}", target.display()));
}
let staged = format!("file-{index:03}");
let staged_path = transaction.join(&staged);
fs::rename(&prepared, &staged_path).map_err(|error| {
format!(
"move prepared {} to {}: {error}",
prepared.display(),
staged_path.display()
)
})?;
File::open(&staged_path)
.and_then(|file| file.sync_all())
.map_err(|error| format!("fsync {}: {error}", staged_path.display()))?;
entries.push(TransactionEntry {
staged,
target: target
.to_str()
.ok_or_else(|| format!("non-UTF-8 target {}", target.display()))?
.into(),
delete: false,
});
}
for target in deletions {
validate_transaction_target(&target)?;
if !targets.insert(target.clone()) {
return Err(format!("duplicate transaction target {}", target.display()));
}
entries.push(TransactionEntry {
staged: String::new(),
target: target
.to_str()
.ok_or_else(|| format!("non-UTF-8 target {}", target.display()))?
.into(),
delete: true,
});
}
if entries.is_empty() {
fs::remove_dir(&transaction)
.map_err(|error| format!("remove {}: {error}", transaction.display()))?;
return Ok(());
}
let manifest = TransactionManifest { entries };
let manifest_path = transaction.join("manifest.json");
let manifest_bytes = serde_json::to_vec(&manifest)
.map_err(|error| format!("serialize transaction: {error}"))?;
let mut file = File::create(&manifest_path)
.map_err(|error| format!("create {}: {error}", manifest_path.display()))?;
file.write_all(&manifest_bytes)
.map_err(|error| format!("write {}: {error}", manifest_path.display()))?;
file.sync_all()
.map_err(|error| format!("fsync {}: {error}", manifest_path.display()))?;
sync_directory(&transaction)?;
apply_transaction(&transaction, &self.root, &manifest)
}
}
fn apply_transaction(
@@ -503,8 +672,18 @@ fn apply_transaction(
manifest: &TransactionManifest,
) -> Result<(), String> {
for entry in &manifest.entries {
let staged = transaction.join(&entry.staged);
let target = root.join(&entry.target);
if entry.delete {
if target.exists() {
fs::remove_file(&target)
.map_err(|error| format!("delete {}: {error}", target.display()))?;
if let Some(parent) = target.parent() {
sync_directory(parent)?;
}
}
continue;
}
let staged = transaction.join(&entry.staged);
if !staged.exists() {
if target.exists() {
continue;
@@ -537,6 +716,20 @@ fn apply_transaction(
Ok(())
}
fn validate_transaction_target(target: &Path) -> Result<(), String> {
if target.is_absolute()
|| target
.components()
.any(|component| !matches!(component, std::path::Component::Normal(_)))
{
return Err(format!(
"transaction target must be a relative corpus path: {}",
target.display()
));
}
Ok(())
}
fn sync_directory(path: &Path) -> Result<(), String> {
let file = OpenOptions::new()
.read(true)
@@ -650,6 +843,18 @@ fn validate_aligned_observation_rows<T: AlignedObservation>(
Ok(())
}
fn validate_observation_output(case: &AuthoredCase, output_b64: &str) -> Result<(), String> {
let expects_empty = matches!(&case.output, OutputSelection::None);
if output_b64.is_empty() != expects_empty {
return Err(if expects_empty {
"output.kind none requires an exact empty observation".into()
} else {
"an exact empty observation requires output.kind none".into()
});
}
Ok(())
}
fn reject_duplicate_metal_slots(rows: &[MetalObservation]) -> Result<(), String> {
let mut slots = std::collections::HashSet::new();
for row in rows {
@@ -754,6 +959,7 @@ mod tests {
initial_bytes_b64: Some(initial.into()),
}],
argument_buffer_buffers: vec![],
device_buffer_arrays: vec![],
threadgroup_memory: vec![],
imageblock: None,
fragment_imageblock: None,
@@ -792,6 +998,32 @@ mod tests {
case
}
#[test]
fn exact_air_case_lookup_does_not_open_unrelated_case_shards() {
let scratch = ScratchDir::new("exact-air-case-lookup").unwrap();
let store = CorpusStore::new(scratch.path());
let first = make_case("first", "q6urqw==");
let mut unrelated = make_case("unrelated", "u7u7uw==");
unrelated.air_sha256 = "22".repeat(32);
unrelated.case_id = unrelated.computed_case_id().unwrap();
store.put_case(first.clone()).unwrap();
store.put_case(unrelated.clone()).unwrap();
let unrelated_shard = shard_index_for_hash(&unrelated.air_sha256).unwrap();
fs::write(
scratch
.path()
.join("cases")
.join(shard_name(unrelated_shard)),
b"not json\n",
)
.unwrap();
assert_eq!(
store.find_cases_for_air(&first.air_sha256).unwrap(),
[first]
);
}
fn candidate(
case: &AuthoredCase,
backend: Backend,
@@ -900,6 +1132,58 @@ mod tests {
);
}
#[test]
fn empty_observation_is_coupled_to_none_output_selection() {
let scratch = ScratchDir::new("store-empty-observation").unwrap();
let store = CorpusStore::new(scratch.path());
let mut empty_case = make_case("empty", "AAAAAA==");
empty_case.buffers.clear();
empty_case.output = OutputSelection::None;
empty_case.case_id = empty_case.computed_case_id().unwrap();
store.put_case(empty_case.clone()).unwrap();
let empty_sha256 = crate::hash::sha256_bytes(&[]);
let empty_metal = MetalObservation {
case_id: empty_case.case_id.clone(),
air_sha256: empty_case.air_sha256.clone(),
input_sha256: empty_case.computed_input_sha256().unwrap(),
metal_output_sha256: empty_sha256.clone(),
output_b64: String::new(),
environment_id: "env".into(),
environment: serde_json::json!({}),
oracle_abi: "v1".into(),
status: MetalStatus::Qualified,
};
store.upsert_metal(empty_metal.clone()).unwrap();
assert_eq!(store.read_metal().unwrap(), vec![empty_metal]);
let mut nonempty_for_none = candidate(&empty_case, Backend::Vulkan, "vk-env");
nonempty_for_none.golden_output_sha256 = nonempty_for_none.candidate_output_sha256.clone();
assert!(store
.upsert_candidate(nonempty_for_none)
.unwrap_err()
.contains("requires an exact empty observation"));
let nonempty_case = make_case("nonempty", "AAAAAA==");
store.put_case(nonempty_case.clone()).unwrap();
let nonempty_input_sha256 = nonempty_case.computed_input_sha256().unwrap();
let empty_for_buffer = MetalObservation {
case_id: nonempty_case.case_id.clone(),
air_sha256: nonempty_case.air_sha256,
input_sha256: nonempty_input_sha256,
metal_output_sha256: empty_sha256,
output_b64: String::new(),
environment_id: "env".into(),
environment: serde_json::json!({}),
oracle_abi: "v1".into(),
status: MetalStatus::Qualified,
};
assert!(store
.upsert_metal(empty_for_buffer)
.unwrap_err()
.contains("requires output.kind none"));
}
#[test]
fn deleting_named_case_cascades_only_its_evidence() {
let scratch = ScratchDir::new("store-delete").unwrap();
@@ -941,6 +1225,7 @@ mod tests {
entries: vec![TransactionEntry {
staged: "file-000".into(),
target: "cases/recovered.txt".into(),
delete: false,
}],
})
.unwrap(),
@@ -955,6 +1240,48 @@ mod tests {
assert!(!transaction.exists());
}
#[test]
fn prepared_files_publish_through_the_recoverable_transaction() {
let scratch = ScratchDir::new("store-prepared-files").unwrap();
let store = CorpusStore::new(scratch.path());
let prepared_dir = scratch.path().join("prepared");
fs::create_dir(&prepared_dir).unwrap();
let first = prepared_dir.join("first");
let second = prepared_dir.join("second");
fs::write(&first, b"first replacement").unwrap();
fs::write(&second, b"second replacement").unwrap();
store
.commit_prepared_files_and_deletions(
[
(PathBuf::from("local/first"), first.clone()),
(PathBuf::from("cases/second"), second.clone()),
],
std::iter::empty(),
)
.unwrap();
assert_eq!(
fs::read(scratch.path().join("local/first")).unwrap(),
b"first replacement"
);
assert_eq!(
fs::read(scratch.path().join("cases/second")).unwrap(),
b"second replacement"
);
assert!(!first.exists());
assert!(!second.exists());
assert!(fs::read_dir(scratch.path().join(".transactions"))
.unwrap()
.next()
.is_none());
store
.commit_prepared_files_and_deletions(std::iter::empty(), [PathBuf::from("local/first")])
.unwrap();
assert!(!scratch.path().join("local/first").exists());
}
#[test]
fn canonical_readers_reject_misaligned_case_and_observation_rows() {
let case_scratch = ScratchDir::new("misaligned-case").unwrap();
+295 -28
View File
@@ -4,16 +4,20 @@
//! the current translator. A final current-fingerprint sweep remains available to prove that later
//! fixes did not regress earlier successes.
use crate::observation::TRANSLATOR_FINGERPRINT;
use rusqlite::{params, Connection, Transaction};
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;
use std::path::Path;
const TRANSLATION_AUDIT_FINGERPRINT: &str = env!("METAL2VULKAN_TRANSLATION_AUDIT_FINGERPRINT");
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum SelectionMode {
Discovery,
CurrentFingerprint,
RetryCurrentFailures,
RetryHistoricalLinkage,
MissingTierCensus,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
@@ -40,6 +44,8 @@ pub struct TranslationAuditResult {
pub status: TranslationAuditStatus,
pub failure_shape: Option<String>,
pub detail: Option<String>,
#[serde(default)]
pub adopted_tier: Option<String>,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
@@ -62,6 +68,23 @@ pub fn select_translation_audit_batch(
) -> Result<Vec<String>, String> {
let connection = open(index)?;
ensure_table(&connection)?;
let prioritize_failures = after.is_none() && mode != SelectionMode::RetryCurrentFailures;
let sql = selection_sql(mode, prioritize_failures);
let mut statement = connection
.prepare(&sql)
.map_err(|error| format!("prepare translation-audit selection: {error}"))?;
let hashes = statement
.query_map(
params![TRANSLATION_AUDIT_FINGERPRINT, after, limit as i64],
|row| row.get::<_, String>(0),
)
.map_err(|error| format!("query translation-audit selection: {error}"))?
.collect::<Result<Vec<_>, _>>()
.map_err(|error| format!("read translation-audit selection: {error}"))?;
Ok(hashes)
}
fn selection_sql(mode: SelectionMode, prioritize_failures: bool) -> String {
let predicate = match mode {
SelectionMode::Discovery => {
"NOT EXISTS (
@@ -86,30 +109,40 @@ pub fn select_translation_audit_batch(
AND a.status='failed'
)"
}
SelectionMode::RetryHistoricalLinkage => {
"NOT EXISTS (
SELECT 1 FROM translation_audit current
WHERE current.air_sha256=s.air_sha256
AND current.translator_fingerprint=?1
) AND EXISTS (
SELECT 1 FROM translation_audit old
WHERE old.air_sha256=s.air_sha256
AND old.status='authored_linkage_required'
)"
}
SelectionMode::MissingTierCensus => {
"NOT EXISTS (
SELECT 1 FROM translation_audit a
WHERE a.air_sha256=s.air_sha256
AND a.translator_fingerprint=?1
AND a.adopted_tier IS NOT NULL
)"
}
};
let sql = format!(
let order = if prioritize_failures {
"CASE WHEN s.air_sha256 IN (
SELECT old.air_sha256 FROM translation_audit old WHERE old.status='failed'
) THEN 0 ELSE 1 END,
s.air_sha256"
} else {
"s.air_sha256"
};
format!(
"SELECT s.air_sha256 FROM sources s WHERE {predicate}
AND (?2 IS NULL OR s.air_sha256 > ?2)
ORDER BY
CASE WHEN ?2 IS NULL AND EXISTS (
SELECT 1 FROM translation_audit old
WHERE old.air_sha256=s.air_sha256 AND old.status='failed'
) THEN 0 ELSE 1 END,
s.air_sha256
ORDER BY {order}
LIMIT ?3"
);
let mut statement = connection
.prepare(&sql)
.map_err(|error| format!("prepare translation-audit selection: {error}"))?;
let hashes = statement
.query_map(
params![TRANSLATOR_FINGERPRINT, after, limit as i64],
|row| row.get::<_, String>(0),
)
.map_err(|error| format!("query translation-audit selection: {error}"))?
.collect::<Result<Vec<_>, _>>()
.map_err(|error| format!("read translation-audit selection: {error}"))?;
Ok(hashes)
)
}
pub fn write_translation_audit_results(
@@ -132,7 +165,9 @@ pub fn translation_audit_summary(index: &Path) -> Result<TranslationAuditSummary
ensure_table(&connection)?;
let count = |sql: &str| -> Result<usize, String> {
connection
.query_row(sql, [TRANSLATOR_FINGERPRINT], |row| row.get::<_, usize>(0))
.query_row(sql, [TRANSLATION_AUDIT_FINGERPRINT], |row| {
row.get::<_, usize>(0)
})
.map_err(|error| format!("query translation-audit summary: {error}"))
};
let total_sources = count("SELECT count(*) FROM sources WHERE ?1 IS NOT NULL")?;
@@ -155,7 +190,7 @@ pub fn translation_audit_summary(index: &Path) -> Result<TranslationAuditSummary
.query_row(
"SELECT count(*) FROM sources s JOIN translation_audit a USING (air_sha256)
WHERE a.translator_fingerprint=?1 AND a.status=?2",
params![TRANSLATOR_FINGERPRINT, status],
params![TRANSLATION_AUDIT_FINGERPRINT, status],
|row| row.get::<_, usize>(0),
)
.map_err(|error| format!("query translation-audit status {status}: {error}"))
@@ -172,6 +207,26 @@ pub fn translation_audit_summary(index: &Path) -> Result<TranslationAuditSummary
})
}
pub fn translation_tier_summary(index: &Path) -> Result<BTreeMap<String, usize>, String> {
let connection = open(index)?;
ensure_table(&connection)?;
let mut statement = connection
.prepare(
"SELECT adopted_tier, count(*) FROM translation_audit
WHERE translator_fingerprint=?1 AND adopted_tier IS NOT NULL
GROUP BY adopted_tier ORDER BY adopted_tier",
)
.map_err(|error| format!("prepare translation tier summary: {error}"))?;
let summary = statement
.query_map([TRANSLATION_AUDIT_FINGERPRINT], |row| {
Ok((row.get::<_, String>(0)?, row.get::<_, usize>(1)?))
})
.map_err(|error| format!("query translation tier summary: {error}"))?
.collect::<Result<BTreeMap<_, _>, _>>()
.map_err(|error| format!("read translation tier summary: {error}"))?;
Ok(summary)
}
fn open(index: &Path) -> Result<Connection, String> {
Connection::open(index).map_err(|error| format!("open index {}: {error}", index.display()))
}
@@ -187,12 +242,32 @@ fn ensure_table(connection: &Connection) -> Result<(), String> {
)),
failure_shape TEXT,
detail TEXT,
adopted_tier TEXT,
PRIMARY KEY(air_sha256, translator_fingerprint)
);
CREATE INDEX IF NOT EXISTS translation_audit_current_status
ON translation_audit(translator_fingerprint, status);",
)
.map_err(|error| format!("create translation-audit cache: {error}"))
.map_err(|error| format!("create translation-audit cache: {error}"))?;
let has_adopted_tier = connection
.prepare("PRAGMA table_info(translation_audit)")
.and_then(|mut statement| {
statement
.query_map([], |row| row.get::<_, String>(1))?
.collect::<Result<Vec<_>, _>>()
})
.map_err(|error| format!("inspect translation-audit schema: {error}"))?
.iter()
.any(|column| column == "adopted_tier");
if !has_adopted_tier {
connection
.execute(
"ALTER TABLE translation_audit ADD COLUMN adopted_tier TEXT",
[],
)
.map_err(|error| format!("add translation-audit adopted tier: {error}"))?;
}
Ok(())
}
fn write_results(
@@ -202,22 +277,28 @@ fn write_results(
let mut insert = transaction
.prepare(
"INSERT INTO translation_audit
(air_sha256, translator_fingerprint, status, failure_shape, detail)
VALUES (?1, ?2, ?3, ?4, ?5)
(air_sha256, translator_fingerprint, status, failure_shape, detail, adopted_tier)
VALUES (?1, ?2, ?3, ?4, ?5, ?6)
ON CONFLICT(air_sha256, translator_fingerprint) DO UPDATE SET
status=excluded.status,
failure_shape=excluded.failure_shape,
detail=excluded.detail",
detail=excluded.detail,
adopted_tier=CASE
WHEN excluded.adopted_tier IS NOT NULL THEN excluded.adopted_tier
WHEN excluded.status=translation_audit.status THEN translation_audit.adopted_tier
ELSE NULL
END",
)
.map_err(|error| format!("prepare translation-audit update: {error}"))?;
for result in results {
insert
.execute(params![
result.air_sha256,
TRANSLATOR_FINGERPRINT,
TRANSLATION_AUDIT_FINGERPRINT,
result.status.as_str(),
result.failure_shape,
result.detail,
result.adopted_tier,
])
.map_err(|error| {
format!(
@@ -258,12 +339,14 @@ mod tests {
status: TranslationAuditStatus::Translated,
failure_shape: None,
detail: None,
adopted_tier: Some("default".into()),
},
TranslationAuditResult {
air_sha256: "b".into(),
status: TranslationAuditStatus::Failed,
failure_shape: Some("shape".into()),
detail: Some("detail".into()),
adopted_tier: Some("fallback".into()),
},
],
)
@@ -306,6 +389,39 @@ mod tests {
);
}
#[test]
fn historical_failure_priority_is_materialized_once_per_selection() {
let (_scratch, index) = index();
let connection = Connection::open(&index).unwrap();
ensure_table(&connection).unwrap();
let explain = format!(
"EXPLAIN QUERY PLAN {}",
selection_sql(SelectionMode::CurrentFingerprint, true)
);
let details = connection
.prepare(&explain)
.unwrap()
.query_map(
params![TRANSLATION_AUDIT_FINGERPRINT, None::<&str>, 10],
|row| row.get::<_, String>(3),
)
.unwrap()
.collect::<Result<Vec<_>, _>>()
.unwrap();
assert!(details
.iter()
.any(|detail| detail.contains("LIST SUBQUERY")));
assert_eq!(
details
.iter()
.filter(|detail| detail.contains("CORRELATED SCALAR SUBQUERY"))
.count(),
1,
"{details:?}"
);
}
#[test]
fn retry_current_failures_selects_only_failed_current_rows() {
let (_scratch, index) = index();
@@ -317,12 +433,14 @@ mod tests {
status: TranslationAuditStatus::Translated,
failure_shape: None,
detail: None,
adopted_tier: Some("default".into()),
},
TranslationAuditResult {
air_sha256: "b".into(),
status: TranslationAuditStatus::Failed,
failure_shape: Some("shape".into()),
detail: Some("detail".into()),
adopted_tier: Some("fallback".into()),
},
],
)
@@ -334,4 +452,153 @@ mod tests {
["b"]
);
}
#[test]
fn retry_historical_linkage_is_resumable_under_the_current_fingerprint() {
let (_scratch, index) = index();
let connection = Connection::open(&index).unwrap();
ensure_table(&connection).unwrap();
connection
.execute_batch(
"INSERT INTO translation_audit
(air_sha256, translator_fingerprint, status, failure_shape, detail)
VALUES
('a', 'old-fingerprint', 'authored_linkage_required', NULL, NULL),
('b', 'old-fingerprint', 'translated', NULL, NULL);",
)
.unwrap();
assert_eq!(
select_translation_audit_batch(
&index,
SelectionMode::RetryHistoricalLinkage,
None,
10,
)
.unwrap(),
["a"]
);
write_translation_audit_results(
&index,
&[TranslationAuditResult {
air_sha256: "a".into(),
status: TranslationAuditStatus::AuthoredLinkageRequired,
failure_shape: None,
detail: None,
adopted_tier: None,
}],
)
.unwrap();
assert!(select_translation_audit_batch(
&index,
SelectionMode::RetryHistoricalLinkage,
None,
10,
)
.unwrap()
.is_empty());
}
#[test]
fn tier_census_selects_only_current_rows_without_a_tier_and_summarizes_them() {
let (_scratch, index) = index();
write_translation_audit_results(
&index,
&[
TranslationAuditResult {
air_sha256: "a".into(),
status: TranslationAuditStatus::Translated,
failure_shape: None,
detail: None,
adopted_tier: Some("default".into()),
},
TranslationAuditResult {
air_sha256: "b".into(),
status: TranslationAuditStatus::Translated,
failure_shape: None,
detail: None,
adopted_tier: None,
},
],
)
.unwrap();
assert_eq!(
select_translation_audit_batch(&index, SelectionMode::MissingTierCensus, None, 10)
.unwrap(),
["b", "c"]
);
assert_eq!(
translation_tier_summary(&index).unwrap(),
BTreeMap::from([("default".to_string(), 1)])
);
}
#[test]
fn existing_translation_audit_table_migrates_adopted_tier_in_place() {
let scratch = ScratchDir::new("translation-audit-tier-migration").unwrap();
let index = scratch.path().join("index.sqlite");
let connection = Connection::open(&index).unwrap();
connection
.execute_batch(
"CREATE TABLE translation_audit (
air_sha256 TEXT NOT NULL,
translator_fingerprint TEXT NOT NULL,
status TEXT NOT NULL,
failure_shape TEXT,
detail TEXT,
PRIMARY KEY(air_sha256, translator_fingerprint)
);",
)
.unwrap();
ensure_table(&connection).unwrap();
let columns = connection
.prepare("PRAGMA table_info(translation_audit)")
.unwrap()
.query_map([], |row| row.get::<_, String>(1))
.unwrap()
.collect::<Result<Vec<_>, _>>()
.unwrap();
assert!(columns.iter().any(|column| column == "adopted_tier"));
}
#[test]
fn unchanged_status_preserves_measured_tier_but_changed_status_clears_it() {
let (_scratch, index) = index();
let result = |status, adopted_tier| TranslationAuditResult {
air_sha256: "a".into(),
status,
failure_shape: None,
detail: None,
adopted_tier,
};
write_translation_audit_results(
&index,
&[result(
TranslationAuditStatus::Translated,
Some("default".into()),
)],
)
.unwrap();
write_translation_audit_results(
&index,
&[result(TranslationAuditStatus::Translated, None)],
)
.unwrap();
assert_eq!(
translation_tier_summary(&index).unwrap(),
BTreeMap::from([("default".to_string(), 1)])
);
write_translation_audit_results(&index, &[result(TranslationAuditStatus::Failed, None)])
.unwrap();
assert!(translation_tier_summary(&index).unwrap().is_empty());
assert_eq!(
select_translation_audit_batch(&index, SelectionMode::MissingTierCensus, None, 10)
.unwrap(),
["a", "b", "c"]
);
}
}
+118 -7
View File
@@ -7,7 +7,7 @@ use serde::{Deserialize, Serialize};
use std::collections::{BTreeMap, HashMap, HashSet};
use std::path::Path;
pub const ANALYZER_ABI: &str = "structural-triage-v36";
pub const ANALYZER_ABI: &str = "structural-triage-v38";
const RESOURCE_KINDS: [&str; 13] = [
"air.buffer",
@@ -125,6 +125,20 @@ impl VisibleFunctionTableAudit {
.any(|kind| kind.contains(".unsupported_"))
|| self.table_operands.contains_key("derived")
}
/// Whether exact authored table contents are a semantic input to this source.
///
/// A dead lookup has no observable table dependency. Queries, calls, nullness/sentinel probes,
/// and helper-threaded callbacks do; they can be specialized exactly only after the caller
/// supplies the table size and populated linked modules.
pub fn requires_authored_linkage(&self) -> bool {
!self.has_unsupported_use()
&& (!self.queries.is_empty()
|| self
.lookup_uses
.keys()
.any(|kind| !kind.ends_with(".unused")))
}
}
/// Select sources from the versioned triage cache by an exact tooling requirement.
@@ -949,23 +963,52 @@ fn ray_call_arguments(instruction: &str) -> Option<Vec<&str>> {
pub fn audit_visible_function_tables(source: &SourceRow) -> VisibleFunctionTableAudit {
let entry_parameters = entry_parameter_values(&source.air_ll, &source.entry);
let table_flow = visible_table_parameter_flow(source);
let defined_functions = defined_function_globals(&source.air_ll);
let mut result = VisibleFunctionTableAudit::default();
let mut pointers = HashMap::<String, VisiblePointerTrace>::new();
let mut sentinel_integers = HashMap::<String, VisiblePointerTrace>::new();
let mut lookups = Vec::<VisibleLookup>::new();
let mut current_function = None::<String>;
for line in source.air_ll.lines() {
let trimmed = line.trim_start();
if trimmed.starts_with("define ") || trimmed == "}" {
if trimmed.starts_with("define ") {
current_function = definition_global(trimmed);
pointers.clear();
sentinel_integers.clear();
continue;
}
if trimmed == "}" {
current_function = None;
pointers.clear();
sentinel_integers.clear();
continue;
}
let rooted_tables = current_function
.as_ref()
.and_then(|function| table_flow.get(function));
let in_entry = current_function
.as_deref()
.is_some_and(|function| function_matches_entry(function, &source.entry));
if trimmed.contains("call ") && trimmed.contains("@air.get_size_visible_function_table(") {
record_table_query(&mut result, "size", trimmed, &entry_parameters);
record_table_query(
&mut result,
"size",
trimmed,
&entry_parameters,
rooted_tables,
in_entry,
);
}
if trimmed.contains("call ") && trimmed.contains("@air.is_null_visible_function_table(") {
record_table_query(&mut result, "is_null", trimmed, &entry_parameters);
record_table_query(
&mut result,
"is_null",
trimmed,
&entry_parameters,
rooted_tables,
in_entry,
);
}
let Some((defined, instruction)) = trimmed.split_once(" = ") else {
@@ -996,8 +1039,10 @@ pub fn audit_visible_function_tables(source: &SourceRow) -> VisibleFunctionTable
continue;
}
let table = audit_value_operand(arguments[0]);
let table_kind = if entry_parameters.contains(table) {
let table_kind = if in_entry && entry_parameters.contains(table) {
"direct_entry_parameter"
} else if rooted_tables.is_some_and(|tables| tables.contains(table)) {
"threaded_entry_parameter"
} else {
"derived"
};
@@ -1159,13 +1204,17 @@ fn record_table_query(
query: &str,
instruction: &str,
entry_parameters: &HashSet<String>,
rooted_tables: Option<&HashSet<String>>,
in_entry: bool,
) {
let table_kind = audit_call_arguments(instruction)
.and_then(|arguments| arguments.first().copied())
.map(audit_value_operand)
.map_or("malformed", |table| {
if entry_parameters.contains(table) {
if in_entry && entry_parameters.contains(table) {
"direct_entry_parameter"
} else if rooted_tables.is_some_and(|tables| tables.contains(table)) {
"threaded_entry_parameter"
} else {
"derived"
}
@@ -1344,6 +1393,52 @@ fn entry_parameter_values(ll: &str, entry: &str) -> HashSet<String> {
.collect()
}
fn visible_table_parameter_flow(source: &SourceRow) -> HashMap<String, HashSet<String>> {
let roots = match source.stage.as_str() {
"Kernel" => metal2vulkan::meta::parse_air_kernel_meta(&source.air_ll)
.into_iter()
.flat_map(|meta| meta.roles)
.filter_map(|(index, role)| {
matches!(role, metal2vulkan::meta::KernRole::VisibleFunctionTable(_))
.then_some(index)
})
.collect::<Vec<_>>(),
"Vertex" => metal2vulkan::meta::parse_air_vertex_meta(&source.air_ll)
.into_iter()
.flat_map(|meta| meta.roles)
.filter_map(|(index, role)| {
matches!(role, metal2vulkan::meta::VertRole::VisibleFunctionTable(_))
.then_some(index)
})
.collect::<Vec<_>>(),
"Fragment" => metal2vulkan::meta::parse_air_fragment_meta(&source.air_ll)
.into_iter()
.flat_map(|meta| meta.roles)
.filter_map(|(index, role)| {
matches!(role, metal2vulkan::meta::FragRole::VisibleFunctionTable(_))
.then_some(index)
})
.collect::<Vec<_>>(),
_ => Vec::new(),
};
metal2vulkan::linked_functions::trace_visible_function_table_parameters(
&source.air_ll,
&source.entry,
&roots,
)
.unwrap_or_default()
}
fn definition_global(line: &str) -> Option<String> {
let at = line.find('@')?;
let open = line[at..].find('(')? + at;
Some(line[at..open].trim_end().to_string())
}
fn function_matches_entry(global: &str, entry: &str) -> bool {
global == format!("@{entry}") || global == format!("@\"{}\"", entry.replace('"', "\\22"))
}
fn audit_call_arguments(instruction: &str) -> Option<Vec<&str>> {
let open = instruction.find('(')?;
let close = audit_matching_paren(instruction, open)?;
@@ -1421,7 +1516,7 @@ mod tests {
entry: "main".into(),
air_ll: ll.into(),
blob_b64: None,
lib_sha256: "22".repeat(32),
lib_sha256s: vec!["22".repeat(32)],
label: "local/test.ll".into(),
}
}
@@ -1469,6 +1564,7 @@ mod tests {
);
let result = classify(&row);
assert!(result.tooling_requirements.is_empty());
assert!(!audit_visible_function_tables(&row).requires_authored_linkage());
}
#[test]
@@ -1481,6 +1577,7 @@ mod tests {
assert_eq!(audit.lookup_uses["constant.null_compare"], 1);
assert_eq!(audit.table_operands["direct_entry_parameter"], 1);
assert!(!audit.has_unsupported_use());
assert!(audit.requires_authored_linkage());
}
#[test]
@@ -1492,6 +1589,7 @@ mod tests {
assert_eq!(audit.lookup_uses["dynamic.direct_call"], 1);
assert_eq!(audit.lookup_uses["dynamic.unsupported_select"], 1);
assert!(audit.has_unsupported_use());
assert!(!audit.requires_authored_linkage());
assert_eq!(
classify(&row).tooling_requirements,
[ToolingRequirement::VisibleFunctionTable]
@@ -1586,6 +1684,19 @@ declare void @air.set_buffer_intersection_function_table.p1i8(ptr addrspace(1),
assert!(!audit.has_unsupported_use());
}
#[test]
fn visible_table_audit_traces_the_table_through_an_internal_helper() {
let row = source(
"define void @main(ptr addrspace(1) %table, i32 %slot) {\nentry:\n %value = call i32 @invoke(ptr addrspace(1) %table, i32 %slot)\n ret void\n}\ndefine internal i32 @invoke(ptr addrspace(1) %functions, i32 %slot) {\nentry:\n %f = call ptr @air.get_function_pointer_visible_function_table(ptr addrspace(1) %functions, i32 %slot)\n %value = call i32 %f()\n ret i32 %value\n}\ndeclare ptr @air.get_function_pointer_visible_function_table(ptr addrspace(1), i32)\n!air.kernel = !{!0}\n!0 = !{ptr @main, !1, !2}\n!1 = !{}\n!2 = !{!3}\n!3 = !{i32 0, !\"air.visible_function_table\", !\"air.location_index\", i32 1, i32 1, !\"air.read\"}",
);
let audit = audit_visible_function_tables(&row);
assert_eq!(audit.table_operands["threaded_entry_parameter"], 1);
assert_eq!(audit.lookup_uses["dynamic.direct_call"], 1);
assert!(!audit.has_unsupported_use());
assert!(audit.requires_authored_linkage());
assert!(classify(&row).tooling_requirements.is_empty());
}
#[test]
fn cached_requirement_selection_never_reads_source_bodies() {
let scratch = ScratchDir::new("triage-requirement-selection").unwrap();