From a5e01c3f0e0d4cf3bc91b697ce5366ddcf59c955 Mon Sep 17 00:00:00 2001 From: Anees Iqbal Date: Mon, 31 Aug 2026 16:08:04 +0300 Subject: [PATCH] Take five more emission decisions off hash-map iteration order A kernel with an unbound buffer parameter translated to different bytes on almost every run. Its loads from the absent resource each become a copy of that type's null, and the nulls were minted by iterating a HashSet of the load result types -- so three loads of three distinct types came out in one of six orders. tests/deterministic_output.rs has the reduced kernel, plus a probe asserting it still reaches that rewrite, so the test cannot quietly start passing over nothing. Auditing the rest of the pipeline for the same shape -- a hash collection whose iteration order decides what gets minted or pushed -- found four more: native/psb.rs OpTypePointer per memory-view pointee native/rewrites.rs wrapper struct + pointer + decoration per candidate pointer type passes/.../texture_array.rs one access-chain id per bound handle, and the dead-root list passes/.../selected_load.rs OpDecorate ArrayStride per pointer type Each now walks the module's own instruction stream instead, which makes the order a property of the input. src/emission_order.rs holds that idiom in one place so the correct spelling is the short one, and says which collection each kind of question wants: a HashSet is still right for pure membership, where nothing is ever iterated. Verified over 900 local-corpus sources: 820 translated, 0 varied across four in-process translations each. Before these fixes the same sweep found 24 varying inputs in its first 400. The cross-stage fixture sweep is new and is what made the reduction findable: determinism has to hold for whatever stage the caller passes, and translating each fixture at all three reaches paths the declared stage never does -- a parameter the declared stage binds to a descriptor is an unbound Private placeholder under another. --- src/emission_order.rs | 63 ++++++++++ src/lib.rs | 1 + src/native/psb.rs | 29 +++-- src/native/rewrites.rs | 15 ++- .../resources/rewrites/private_atomics.rs | 29 +++-- src/passes/resources/selected_load.rs | 17 ++- src/passes/resources/texture_array.rs | 26 +++- tests/deterministic_output.rs | 113 ++++++++++++++++++ 8 files changed, 253 insertions(+), 40 deletions(-) create mode 100644 src/emission_order.rs diff --git a/src/emission_order.rs b/src/emission_order.rs new file mode 100644 index 000000000..3dc866e9b --- /dev/null +++ b/src/emission_order.rs @@ -0,0 +1,63 @@ +//! Encounter-ordered deduplication for collections that decide what the module looks like. +//! +//! Any decision the emitter makes while walking a set — which id to mint first, which decoration to +//! push next — becomes part of the output bytes. A `HashSet`/`HashMap` has no order to walk: Rust +//! seeds every map's hasher separately, so the same input yields a different permutation on every +//! run and the translator silently produces a semantically identical module with different bytes. +//! That breaks content-hash caching, the validation ladder's SHA-256 comparison, and the ability to +//! reproduce a bug report from the module that caused it. +//! +//! The fix is always the same shape: gather in the order the module's own instruction stream +//! presents the elements, and drop repeats. That order is a property of the input, so it is the same +//! on every run and on every machine. [`dedup_in_encounter_order`] is that idiom in one place, so +//! the correct spelling is shorter than the incorrect one. +//! +//! Use this — not a `HashSet` — whenever the collected elements go on to mint ids, push +//! instructions, or push annotations. A `HashSet` is still right for pure membership questions, +//! where nothing is ever iterated. + +use std::collections::HashSet; +use std::hash::Hash; + +/// The distinct elements of `items`, in the order they were first produced. +/// +/// The `HashSet` here only answers "have I seen this?", which is order-free; the returned `Vec` +/// carries the encounter order the caller must emit in. +pub(crate) fn dedup_in_encounter_order( + items: impl IntoIterator, +) -> Vec { + let mut seen = HashSet::new(); + items + .into_iter() + .filter(|item| seen.insert(*item)) + .collect() +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn first_occurrence_wins_and_repeats_are_dropped() { + assert_eq!( + dedup_in_encounter_order([7u32, 3, 7, 9, 3, 3, 1]), + vec![7, 3, 9, 1] + ); + } + + #[test] + fn an_empty_input_collects_to_nothing() { + assert!(dedup_in_encounter_order(std::iter::empty::()).is_empty()); + } + + /// The point of the helper: the result must not depend on how the elements hash. Building the + /// same elements through many independently seeded `HashSet`s and re-deduping must reproduce the + /// input order every time, which a `HashSet`-collected pipeline would not. + #[test] + fn the_order_is_the_inputs_order_not_a_hash_order() { + let items: Vec = (0..64).map(|i| i * 7 + 1).collect(); + for _ in 0..64 { + assert_eq!(dedup_in_encounter_order(items.iter().copied()), items); + } + } +} diff --git a/src/lib.rs b/src/lib.rs index a289dd35b..5a93598b2 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -19,6 +19,7 @@ pub mod air_intrinsics; pub mod as_shadow; mod construction; +mod emission_order; mod emit_sidecar; pub mod env_vars; mod fc_air_specialize; diff --git a/src/native/psb.rs b/src/native/psb.rs index 2ab0145da..3a9ae2c33 100644 --- a/src/native/psb.rs +++ b/src/native/psb.rs @@ -943,15 +943,21 @@ fn rewrite_cross_binding_pointer_merges_inner( .all_inst_iter() .filter_map(|instruction| Some((instruction.result_id?, instruction.clone()))) .collect::>(); - let mut memory_view_pointees = HashSet::new(); - for function in &module.functions { - for block in &function.blocks { - for instruction in &block.instructions { + // Each pointee here mints one `OpTypePointer`, so this order is the order those declarations + // land in the module. It has to come from the instruction stream, not from a `HashSet`, or the + // same input assembles to different bytes on every run. + let memory_view_pointees = crate::emission_order::dedup_in_encounter_order( + module + .functions + .iter() + .flat_map(|function| &function.blocks) + .flat_map(|block| &block.instructions) + .filter_map(|instruction| { let Some(Operand::IdRef(pointer)) = instruction.operands.first() else { - continue; + return None; }; if !closure.contains(pointer) { - continue; + return None; } let accessed_type = match instruction.class.opcode { Op::Load => instruction.result_type, @@ -968,12 +974,11 @@ fn rewrite_cross_binding_pointer_merges_inner( .get(pointer) .and_then(|ty| ptr_info(*ty)) .map(|(_, pointee)| pointee); - if accessed_type != pointer_pointee { - memory_view_pointees.extend(accessed_type); - } - } - } - } + (accessed_type != pointer_pointee) + .then_some(accessed_type) + .flatten() + }), + ); for pointee in memory_view_pointees { if psb_ptr.contains_key(&pointee) { continue; diff --git a/src/native/rewrites.rs b/src/native/rewrites.rs index 162cd7d7a..a734bb13b 100644 --- a/src/native/rewrites.rs +++ b/src/native/rewrites.rs @@ -443,11 +443,16 @@ pub(crate) fn construct_physical_atomic_pointer_lvalues_module(module: &mut Modu return false; } - let candidate_pointer_types = candidates - .iter() - .flatten() - .map(|(_, _, pointer_type, _)| *pointer_type) - .collect::>(); + // Each candidate pointer type mints a wrapper struct, a wrapper pointer, and a decoration + // below, so this order is the order those declarations and annotations land in the module. + // `candidates` is built by walking the functions in order, which makes the result a property of + // the input; a `HashSet` here would make it a property of the run. + let candidate_pointer_types = crate::emission_order::dedup_in_encounter_order( + candidates + .iter() + .flatten() + .map(|(_, _, pointer_type, _)| *pointer_type), + ); let pointer_pointees = module .types_global_values .iter() diff --git a/src/passes/resources/rewrites/private_atomics.rs b/src/passes/resources/rewrites/private_atomics.rs index 07c8bbc89..242d867cb 100644 --- a/src/passes/resources/rewrites/private_atomics.rs +++ b/src/passes/resources/rewrites/private_atomics.rs @@ -1,6 +1,7 @@ //! Private-resource atomic lowering and shared raw-access analysis. use super::*; +use crate::emission_order::dedup_in_encounter_order; use crate::passes::access::direct_scalar_width; /// Replace direct loads from an absent-resource Private root with the root's exact zero value. @@ -90,22 +91,24 @@ pub(in crate::passes) fn rewrite_private_zero_root_loads(ctx: &mut Ctx, roots: & changed |= roots.insert(id); } } - let mut result_types = HashSet::new(); - for function in &ctx.module.functions { - for block in &function.blocks { - for instruction in &block.instructions { - if instruction.class.opcode == Op::Load + // `ctx.const_null` mints one global per distinct result type, so the order these types are + // visited is the order the `OpConstantNull` declarations appear in the emitted module. Walking + // the module's own instruction stream makes that order a property of the input; collecting the + // types into a `HashSet` first made it a property of that run's hasher seed. + let result_types = dedup_in_encounter_order( + ctx.module + .functions + .iter() + .flat_map(|function| &function.blocks) + .flat_map(|block| &block.instructions) + .filter(|instruction| { + instruction.class.opcode == Op::Load && instruction.operands.first().is_some_and( |operand| matches!(operand, Operand::IdRef(id) if roots.contains(id)), ) - { - if let Some(result_type) = instruction.result_type { - result_types.insert(result_type); - } - } - } - } - } + }) + .filter_map(|instruction| instruction.result_type), + ); let nulls = result_types .into_iter() .map(|ty| (ty, ctx.const_null(ty))) diff --git a/src/passes/resources/selected_load.rs b/src/passes/resources/selected_load.rs index 8cc8b12c7..6b088eb18 100644 --- a/src/passes/resources/selected_load.rs +++ b/src/passes/resources/selected_load.rs @@ -24,7 +24,10 @@ struct EmitState<'a> { globals: &'a mut Vec, constants: &'a mut HashMap, unsigned_ints: &'a mut HashMap, - pointer_strides: &'a mut HashMap, + /// `(pointer type, element stride)` in the order the rewrite first needed each type. Every + /// entry becomes one `OpDecorate ArrayStride` below, so this has to be an ordered list: a + /// `HashMap` here made the annotation block come out in a different order on every run. + pointer_strides: &'a mut Vec<(Word, u32)>, next_id: &'a mut Word, } @@ -234,7 +237,7 @@ pub(in crate::passes) fn materialize_interface_selected_loads(module: &mut Modul .flatten() }) .collect::>(); - let mut pointer_strides = HashMap::new(); + let mut pointer_strides: Vec<(Word, u32)> = Vec::new(); for function in &mut module.functions { for block in &mut function.blocks { let old = block.instructions.clone(); @@ -374,9 +377,15 @@ fn emit_arm_load( let source_bits = scalar_bits(types, arm.pointee)?; let value_bits = scalar_bits(types, value_ty)?; let units = value_bits / source_bits; - state + if !state .pointer_strides - .insert(arm.pointer_ty, source_bits / 8); + .iter() + .any(|(pointer_ty, _)| *pointer_ty == arm.pointer_ty) + { + state + .pointer_strides + .push((arm.pointer_ty, source_bits / 8)); + } let mut assembled = None; for unit in 0..units { let index = constant(uint, unit, state.globals, state.constants, state.next_id); diff --git a/src/passes/resources/texture_array.rs b/src/passes/resources/texture_array.rs index 64e496583..3b0b20df6 100644 --- a/src/passes/resources/texture_array.rs +++ b/src/passes/resources/texture_array.rs @@ -138,6 +138,11 @@ pub(crate) fn materialize_texture_array_loads(ctx: &mut Ctx, entry_idx: usize) { let mut candidates: Vec<(Word, Word)> = Vec::new(); let mut table_candidates = Vec::new(); let mut handles: HashMap = HashMap::new(); + // The rewrite below mints one access-chain id per bound handle and the removal transaction + // collects one dead root per handle, so both must visit the handles in the order the + // instruction stream produced them. `handles` answers "which array element is this?" and is + // never iterated; `handle_order` carries the order. + let mut handle_order: Vec = Vec::new(); let mut handle_preludes: HashMap> = HashMap::new(); let mut seen: std::collections::HashSet = std::collections::HashSet::new(); for blk in &ctx.module.functions[entry_idx].blocks { @@ -161,11 +166,15 @@ pub(crate) fn materialize_texture_array_loads(ctx: &mut Ctx, entry_idx: usize) { continue; } if let Some(&(arrayvar, idx)) = dynamic_handles.get(handle) { - handles.insert(*handle, (arrayvar, idx)); + if handles.insert(*handle, (arrayvar, idx)).is_none() { + handle_order.push(*handle); + } continue; } if let Some(&(arrayvar, idx)) = fixed_handles.get(handle) { - handles.insert(*handle, (arrayvar, idx)); + if handles.insert(*handle, (arrayvar, idx)).is_none() { + handle_order.push(*handle); + } continue; } if let Some((arrayvar, selector, entries)) = local_table_handles.get(handle).cloned() { @@ -187,12 +196,16 @@ pub(crate) fn materialize_texture_array_loads(ctx: &mut Ctx, entry_idx: usize) { } for (handle, ptr) in candidates { if let Some((arrayvar, idx)) = resolve_array_element(ctx, &defs, ptr) { - handles.insert(handle, (arrayvar, idx)); + if handles.insert(handle, (arrayvar, idx)).is_none() { + handle_order.push(handle); + } } } for (handle, arrayvar, selector, entries) in table_candidates { if let Some((idx, prelude)) = descriptor_table_index(ctx, selector, &entries) { - handles.insert(handle, (arrayvar, idx)); + if handles.insert(handle, (arrayvar, idx)).is_none() { + handle_order.push(handle); + } handle_preludes.insert(handle, prelude); } } @@ -205,7 +218,8 @@ pub(crate) fn materialize_texture_array_loads(ctx: &mut Ctx, entry_idx: usize) { let mut new_access_chains: HashMap = HashMap::new(); // handle -> access-chain inst let mut retyped_load_ptr: HashMap = HashMap::new(); // handle -> (image_ty, p) let mut dead_roots: Vec = Vec::new(); - for (&handle, &(arrayvar, idx)) in &handles { + for &handle in &handle_order { + let (arrayvar, idx) = handles[&handle]; if !defs.contains_key(&handle) { continue; } @@ -250,7 +264,7 @@ pub(crate) fn materialize_texture_array_loads(ctx: &mut Ctx, entry_idx: usize) { // root. Include the bound descriptor variable itself so the transaction also reaches parallel // stale projections which no longer feed the rewritten handle load. Newly constructed descriptor // accesses share the root but remain live through their image loads and are therefore retained. - dead_roots.extend(handles.values().map(|(arrayvar, _)| *arrayvar)); + dead_roots.extend(handle_order.iter().map(|handle| handles[handle].0)); // Opaque pointer loads that the generic emitter cannot type are represented by a Private // placeholder variable. Such an id has no function instruction to retype, so materialize the diff --git a/tests/deterministic_output.rs b/tests/deterministic_output.rs index e892b4425..63b0962cd 100644 --- a/tests/deterministic_output.rs +++ b/tests/deterministic_output.rs @@ -127,6 +127,87 @@ fn a_device_address_kernel_translates_to_the_same_bytes_every_time() { ); } +/// A kernel whose only resource parameter is never bound. +/// +/// Without `!air.kernel` metadata naming it, `%u` has no descriptor to bind to, so the pipeline +/// re-classes it into a null-initialized Private placeholder root and rewrites every load from it +/// into a copy of that type's zero. One `OpConstantNull` is minted per distinct load result type, +/// and the order they are minted in is the order they are declared in the module. +/// +/// That order used to come from a `HashSet` of the result types, so this kernel's three nulls came +/// out in a different permutation on every run. Three distinct load types make an accidental +/// agreement between two runs a one-in-six event, which `RUNS` repetitions drive to nothing. +const UNBOUND_BUFFER_KERNEL: &str = r#" +target triple = "air64_v28-apple-macosx26.5.0" + +%Uniforms = type { <2 x float>, <3 x float>, <4 x float> } + +define void @k(ptr addrspace(1) %out, ptr addrspace(2) %u) { +entry: + %p2 = getelementptr inbounds %Uniforms, ptr addrspace(2) %u, i64 0, i32 0 + %v2 = load <2 x float>, ptr addrspace(2) %p2 + %p3 = getelementptr inbounds %Uniforms, ptr addrspace(2) %u, i64 0, i32 1 + %v3 = load <3 x float>, ptr addrspace(2) %p3 + %p4 = getelementptr inbounds %Uniforms, ptr addrspace(2) %u, i64 0, i32 2 + %v4 = load <4 x float>, ptr addrspace(2) %p4 + %a = fadd <2 x float> %v2, %v2 + %b = fadd <3 x float> %v3, %v3 + %c = fadd <4 x float> %v4, %v4 + %s0 = extractelement <2 x float> %a, i64 0 + %s1 = extractelement <3 x float> %b, i64 0 + %s2 = extractelement <4 x float> %c, i64 0 + %t0 = fadd float %s0, %s1 + %t1 = fadd float %t0, %s2 + store float %t1, ptr addrspace(1) %out + ret void +} +"#; + +/// The zero-root rewrite is the path this test exists for; assert the module really takes it, so a +/// change that starts binding `%u` cannot leave the test below passing over nothing. +#[test] +fn the_unbound_buffer_kernel_really_zeroes_its_absent_resource() { + let bytes = translate_sanitized_native( + UNBOUND_BUFFER_KERNEL, + Stage::Kernel, + &scratch("unbound-buffer-probe"), + ) + .expect("the unbound-buffer kernel translates"); + let text = metal2vulkan::disassemble(&bytes).expect("disassemble"); + // Each rewritten load is an `OpCopyObject` of an `OpConstantNull` — three loads, three distinct + // types, so three nulls minted in one pass. (The module declares a fourth null elsewhere, as the + // initializer of the Private placeholder variable itself, which this rewrite does not mint.) + let nulls = text + .lines() + .filter_map(|line| line.split_once(" = OpConstantNull")) + .map(|(id, _)| id.trim().to_string()) + .collect::>(); + let copied_nulls = text + .lines() + .filter(|line| line.contains("OpCopyObject")) + .filter(|line| { + nulls + .iter() + .any(|null| line.split_whitespace().any(|word| word == null)) + }) + .count(); + assert_eq!( + copied_nulls, 3, + "expected the absent resource's three distinct load types to each become a copy of that \ + type's null, got {copied_nulls}; the determinism test below no longer covers the mint \ + order it was written for\n{text}" + ); +} + +#[test] +fn an_unbound_buffer_kernel_translates_to_the_same_bytes_every_time() { + assert_deterministic( + "the unbound-buffer kernel", + UNBOUND_BUFFER_KERNEL, + Stage::Kernel, + ); +} + /// The same contract across every committed fixture, so an emission decision that starts following /// iteration order anywhere in the pipeline fails here rather than in a consumer's cache. #[test] @@ -155,6 +236,38 @@ fn every_public_fixture_translates_to_the_same_bytes_every_time() { ); } +/// Determinism does not depend on the stage being the one the AIR declares. +/// +/// `translate_sanitized_native` takes the stage as a parameter, so the stage is an input like any +/// other and the output has to be a function of it. Translating each fixture at every stage reaches +/// pipeline paths the declared stage never does — a buffer parameter that the declared stage binds +/// to a descriptor becomes an unbound Private placeholder under another, which is exactly the +/// rewrite the kernel above was reduced from. Anything that does not translate under a given stage +/// is skipped: this test is about byte stability, not about which stages accept which module. +#[test] +fn every_public_fixture_is_stable_under_every_stage_it_translates_under() { + let mut checked = 0; + for path in public_fixtures() { + let source = std::fs::read_to_string(&path).expect("read fixture"); + let name = path + .file_name() + .map(|name| name.to_string_lossy().into_owned()) + .unwrap_or_default(); + for stage in [Stage::Vertex, Stage::Fragment, Stage::Kernel] { + let label = format!("{name}-{stage:?}"); + if translate_sanitized_native(&source, stage, &scratch(&label)).is_err() { + continue; + } + assert_deterministic(&label, &source, stage); + checked += 1; + } + } + assert!( + checked >= 30, + "only {checked} fixture/stage pairs translated, so this swept almost nothing" + ); +} + /// The stage the AIR declares. The library's `detect_stage` sanitizes from a file path; these /// fixtures are already sanitized text, and they name their stage the same way. fn stage_of(source: &str) -> Option {