diff --git a/docs/TODO.txt b/docs/TODO.txt index e975fce8c..2122639bb 100644 --- a/docs/TODO.txt +++ b/docs/TODO.txt @@ -353,3 +353,9 @@ [ ] Guard or stride the 65,535 * 1024 (~64 MiB/uint8 row) gridDim.y ceiling in ignition/components/state.py row kernels. + +[ ] Measure the unresolved kernel-argument diagnostic on a four-GPU DeepSeek + V4.1 export (issue #266) and an eight-GPU W4A8 MoE export, recording + per-rank aligned occurrence and distinct-address counts. Close when both + exports have run on four-GPU and eight-GPU hardware and the per-rank + counts and printed per-kernel examples have been reviewed. diff --git a/docs/runtime-core-design.md b/docs/runtime-core-design.md index 2b2c86c35..d9d1246d4 100644 --- a/docs/runtime-core-design.md +++ b/docs/runtime-core-design.md @@ -151,7 +151,11 @@ conversions, inline assembly, or opaque calls retain conservative argument scanning. Untyped structs, tensor maps, globals, and integer/byte storage without a numeric role are scanned for address candidates. This can retain false positives and retains complete backing segments, including unused bytes within -a reachable segment. The preparation metadata does not enter the serving index. +a reachable segment. Argument-relative 8-byte-aligned kernel-argument values +inside the recorded address envelope that resolve to no active recorded +allocation (a gap between allocations or an inactive range) are reported on +stderr per rank as a non-blocking diagnostic without retaining inactive storage. +The preparation metadata does not enter the serving index. Omitted arena allocations keep their virtual ranges reserved and physically unmapped, so an unexpected access faults instead of reaching another allocation. @@ -344,7 +348,9 @@ compresses, hashes, and syncs each rank's archive before publication. Native stderr rows omit the Flare banner. Rank-zero capture reports storage clearing, graph inspection and serialization, module/global capture, storage scans, -weight materialization, and frontend assets. Coordinators report export peer waits, +weight materialization, and frontend assets. Each rank also writes a bounded +stderr summary when kernel-argument reachability scanning finds aligned +unresolved address candidates. Coordinators report export peer waits, rank transfers, and preparation-resource release before publication. Publication reports payload assembly, validation, frontend verification, each rank's executable compression and installation, each rank's data verification and diff --git a/heliopause/src/export/capture.rs b/heliopause/src/export/capture.rs index 05b39bdce..6a382a736 100644 --- a/heliopause/src/export/capture.rs +++ b/heliopause/src/export/capture.rs @@ -3256,7 +3256,7 @@ pub(crate) fn capture_rank( &indices, &request.events, )?; - reach.graph(&nodes, &kernels)?; + reach.graph(&graph.name, &nodes, &kernels)?; let file = format!("graph-{index}.bin"); let path = stage.path.join(&file); let mut writer = BufWriter::new(File::create(&path)?); @@ -3291,6 +3291,9 @@ pub(crate) fn capture_rank( "{} graphs, {graph_bytes} bytes", request.graphs.len() )); + for line in reach.unresolved_report(&output.index.ranks[0].functions) { + eprintln!("export: rank {}: {line}", request.rank); + } let module_phase = progress.phase("Capture compiled modules and globals", None); let mut module_bytes = 0u64; let mut downloader = Downloader::new(&cuda)?; diff --git a/heliopause/src/export/reachability.rs b/heliopause/src/export/reachability.rs index 94d3cfaa3..9584162b7 100644 --- a/heliopause/src/export/reachability.rs +++ b/heliopause/src/export/reachability.rs @@ -42,6 +42,39 @@ pub(crate) fn subtract_ranges(start: u64, end: u64, excluded: &[(u64, u64)]) -> spans } +/// An 8-byte-aligned kernel argument value inside the recorded address envelope +/// that resolves to no active recorded allocation (a gap between allocations or +/// an inactive range). Such a value may be a stale pointer or a numeric constant; +/// argument typing cannot yet distinguish the two, so export reports these for +/// operator review. +pub(crate) struct UnresolvedCandidate { + pub graph: String, + pub node: usize, + pub function: usize, + pub argument: usize, + pub offset: usize, +} + +struct UnresolvedEntry { + first: UnresolvedCandidate, + order: usize, + occurrences: usize, +} + +/// The call site a kernel argument blob was scanned for. Every occurrence of +/// the same argument bytes is recorded separately so a report can name the +/// graph, node, kernel, and parameter that carried an unresolved candidate. +pub(crate) struct Site<'a> { + pub graph: &'a str, + pub node: usize, + pub function: usize, + pub argument: usize, +} + +/// The number of distinct addresses shown in a rank's report. The examples +/// retain the first call site for each address in graph and node order. +const UNRESOLVED_EXAMPLES: usize = 10; + pub(crate) struct Reachability { allocations: HashMap, intervals: Vec<(u64, u64, String)>, @@ -49,7 +82,8 @@ pub(crate) struct Reachability { inactive: Vec<(u64, u64)>, pub(crate) reached: HashSet, pending: VecDeque, - blobs: HashSet<(Vec, Vec<(usize, usize)>)>, + blobs: HashMap<(Vec, Vec<(usize, usize)>), Vec<(usize, u64)>>, + unresolved: HashMap, tail: Option<(String, u64, Vec)>, } @@ -74,7 +108,8 @@ impl Reachability { inactive: merge_ranges(inactive.to_vec()), reached: HashSet::new(), pending: VecDeque::new(), - blobs: HashSet::new(), + blobs: HashMap::new(), + unresolved: HashMap::new(), tail: None, }; this.intervals.sort_unstable(); @@ -115,10 +150,13 @@ impl Reachability { Ok(()) } - pub(crate) fn pointer(&mut self, value: u64) -> ExportResult<()> { + /// Retains the live recorded allocation containing `value`. Returns `true` + /// only when `value` resolves to a live allocation; inactive ranges and + /// gaps between allocations both return `false` without retaining storage. + fn candidate(&mut self, value: u64) -> ExportResult { let inactive = self.inactive.partition_point(|&(start, _)| start <= value); if inactive > 0 && value < self.inactive[inactive - 1].1 { - return Ok(()); + return Ok(false); } let index = self .intervals @@ -126,12 +164,39 @@ impl Reachability { if index > 0 && value < self.intervals[index - 1].1 { let name = self.intervals[index - 1].2.clone(); self.reference(&name)?; + return Ok(true); + } + Ok(false) + } + + fn record_unresolved( + unresolved: &mut HashMap, + misses: &[(usize, u64)], + site: &Site, + ) { + for &(offset, address) in misses { + let order = unresolved.len(); + unresolved + .entry(address) + .and_modify(|entry| entry.occurrences += 1) + .or_insert_with(|| UnresolvedEntry { + first: UnresolvedCandidate { + graph: site.graph.to_owned(), + node: site.node, + function: site.function, + argument: site.argument, + offset, + }, + order, + occurrences: 1, + }); } - Ok(()) } - pub(crate) fn blob(&mut self, data: &[u8], numeric: &[(usize, usize)]) -> ExportResult<()> { - if !self.blobs.insert((data.to_vec(), numeric.to_vec())) { + fn blob(&mut self, data: &[u8], numeric: &[(usize, usize)], site: &Site) -> ExportResult<()> { + let key = (data.to_vec(), numeric.to_vec()); + if let Some(misses) = self.blobs.get(&key) { + Self::record_unresolved(&mut self.unresolved, misses, site); return Ok(()); } let excluded = merge_ranges( @@ -140,30 +205,148 @@ impl Reachability { .map(|&(start, end)| (start as u64, end as u64)) .collect(), ); + let mut misses = Vec::new(); for (start, end) in subtract_ranges(0, data.len() as u64, &excluded) { - self.scan(&data[start as usize..end as usize])?; + self.scan( + &data[start as usize..end as usize], + start as usize, + Some(&mut misses), + )?; } + Self::record_unresolved(&mut self.unresolved, &misses, site); + self.blobs.insert(key, misses); Ok(()) } - fn scan(&mut self, data: &[u8]) -> ExportResult<()> { + pub(crate) fn unresolved_count(&self) -> usize { + self.unresolved + .values() + .map(|entry| entry.occurrences) + .sum() + } + + pub(crate) fn unresolved_unique_addresses(&self) -> usize { + self.unresolved.len() + } + + /// Lines describing the unresolved candidates: a summary line, one line per + /// distinct address up to the example limit (prioritizing one example per + /// distinct kernel symbol before backfilling in encounter order), and a + /// trailing line when more distinct addresses were recorded than shown. The + /// caller supplies the recorded functions and adds the export prefix. + pub(crate) fn unresolved_report(&self, functions: &[wire::Function]) -> Vec { + let mut lines = Vec::new(); + let occurrences = self.unresolved_count(); + if occurrences == 0 { + return lines; + } + lines.push(format!( + "kernel argument scan: {} and {} fall inside the recorded address envelope but \ + resolve to no active recorded allocation (gap or inactive range), so each may be a \ + stale pointer or a numeric constant", + with_count(occurrences, "occurrence", "occurrences"), + with_count( + self.unresolved_unique_addresses(), + "distinct address", + "distinct addresses" + ), + )); + let mut examples: Vec<_> = self.unresolved.iter().collect(); + examples.sort_unstable_by_key(|(_, entry)| entry.order); + let limit = UNRESOLVED_EXAMPLES.min(examples.len()); + let mut selected = Vec::with_capacity(limit); + let mut chosen = vec![false; examples.len()]; + let mut seen_symbols = HashSet::with_capacity(limit); + for (index, &(_, entry)) in examples.iter().enumerate() { + if selected.len() == limit { + break; + } + let symbol_key = functions + .get(entry.first.function) + .map_or(Err(entry.first.function), |function| { + Ok(function.symbol.as_str()) + }); + if seen_symbols.insert(symbol_key) { + selected.push(index); + chosen[index] = true; + } + } + for (index, already) in chosen.iter().enumerate() { + if selected.len() == limit { + break; + } + if !already { + selected.push(index); + } + } + selected.sort_unstable(); + let mut shown_occurrences = 0usize; + for index in &selected { + let (address, entry) = examples[*index]; + let address = *address; + shown_occurrences += entry.occurrences; + let candidate = &entry.first; + let function = functions.get(candidate.function); + lines.push(format!( + " graph {:?} node {} kernel {} ({}), argument {}, offset {}: {address:#x} ({})", + candidate.graph, + candidate.node, + function.map_or("unknown", |function| function.symbol.as_str()), + function.map_or("unknown", |function| function.module.as_str()), + candidate.argument, + candidate.offset, + with_count(entry.occurrences, "occurrence", "occurrences"), + )); + } + if examples.len() > selected.len() { + let hidden_addresses = examples.len() - selected.len(); + let hidden_occurrences = occurrences - shown_occurrences; + lines.push(format!( + " … {} ({}) not shown", + with_count( + hidden_addresses, + "more distinct address", + "more distinct addresses" + ), + with_count(hidden_occurrences, "occurrence", "occurrences"), + )); + } + lines + } + + fn scan( + &mut self, + data: &[u8], + base: usize, + mut misses: Option<&mut Vec<(usize, u64)>>, + ) -> ExportResult<()> { if self.intervals.is_empty() { return Ok(()); } let floor = self.intervals[0].0; let ceiling = self.intervals.last().unwrap().1; - for bytes in data.windows(8) { + for (offset, bytes) in data.windows(8).enumerate() { let pointer = u64::from_le_bytes(bytes.try_into().unwrap()); - if pointer >= floor && pointer < ceiling { - self.pointer(pointer)?; + if pointer >= floor + && pointer < ceiling + && !self.candidate(pointer)? + && let Some(misses) = misses.as_deref_mut() + && (base + offset).is_multiple_of(8) + { + misses.push((base + offset, pointer)); } } Ok(()) } - pub(crate) fn graph(&mut self, nodes: &[wire::Node], kernels: &[Kernel]) -> ExportResult<()> { + pub(crate) fn graph( + &mut self, + name: &str, + nodes: &[wire::Node], + kernels: &[Kernel], + ) -> ExportResult<()> { use wire::node::Operation; - for node in nodes { + for (node_index, node) in nodes.iter().enumerate() { match node .operation .as_ref() @@ -176,7 +359,9 @@ impl Reachability { if node.arguments.len() != kernel.arguments.len() { return Err(invalid("kernel argument count differs from its function")); } - for (blob, argument) in node.arguments.iter().zip(&kernel.arguments) { + for (position, (blob, argument)) in + node.arguments.iter().zip(&kernel.arguments).enumerate() + { for relocation in &blob.relocations { self.reference( &relocation @@ -186,7 +371,16 @@ impl Reachability { .allocation, )?; } - self.blob(&blob.data, &argument.numeric)?; + self.blob( + &blob.data, + &argument.numeric, + &Site { + graph: name, + node: node_index, + function: node.function as usize, + argument: position, + }, + )?; } for attribute in &node.attributes { if let Some(value) = &attribute.value { @@ -239,11 +433,15 @@ impl Reachability { .checked_add(data.len() as u64) .ok_or_else(|| invalid("allocation scan extent overflow"))?; for (start, stop) in subtract_ranges(address, end, &self.numeric) { - self.scan(&data[(start - address) as usize..(stop - address) as usize])?; + self.scan( + &data[(start - address) as usize..(stop - address) as usize], + 0, + None, + )?; } Ok(()) } else { - self.scan(data) + self.scan(data, 0, None) } } @@ -320,6 +518,14 @@ impl Reachability { } } +fn with_count(count: usize, one: &str, many: &str) -> String { + if count == 1 { + format!("1 {one}") + } else { + format!("{count} {many}") + } +} + #[cfg(test)] mod tests { use super::*; @@ -430,7 +636,7 @@ mod tests { let allocations = [allocation("target", 0x2000)]; let mut reach = Reachability::new(&allocations, &[], &[], &[]).unwrap(); let bytes = [0x2000u64.to_le_bytes(), 0x2000u64.to_le_bytes()].concat(); - reach.blob(&bytes, &[(0, 8)]).unwrap(); + reach.blob(&bytes, &[(0, 8)], &SITE).unwrap(); assert!(reach.reached.contains("target")); } @@ -482,8 +688,8 @@ mod tests { let bytes = target.address.to_le_bytes(); let mut reach = Reachability::new(&[source.clone(), target.clone()], &[], &[], &[]).unwrap(); - reach.blob(&bytes[..4], &[]).unwrap(); - reach.blob(&bytes[4..], &[]).unwrap(); + reach.blob(&bytes[..4], &[], &SITE).unwrap(); + reach.blob(&bytes[4..], &[], &SITE).unwrap(); reach.contents(&source, 0, &bytes[..4]).unwrap(); reach.contents(&source, 128, &bytes[4..]).unwrap(); assert!(reach.reached.is_empty()); @@ -491,6 +697,7 @@ mod tests { .blob( &[b"abc".as_slice(), bytes.as_slice(), b"xyz".as_slice()].concat(), &[], + &SITE, ) .unwrap(); assert_eq!(reach.reached, HashSet::from([target.name])); @@ -533,6 +740,7 @@ mod tests { let mut reach = Reachability::new(&[scalar.clone(), input.clone()], &[], &[], &[]).unwrap(); reach .graph( + "graph", &[wire::Node { operation: Some(wire::node::Operation::Kernel(node.clone())), }], @@ -543,6 +751,7 @@ mod tests { node.arguments[1].data = node.arguments[0].data.clone(); reach .graph( + "graph", &[wire::Node { operation: Some(wire::node::Operation::Kernel(node)), }], @@ -552,8 +761,481 @@ mod tests { assert_eq!(reach.reached, HashSet::from([input.name, scalar.name])); } + fn kernel_graph(argument_data: &[u8], numeric: Vec<(usize, usize)>) -> (wire::Node, Kernel) { + let kernel = Kernel { + function: 1, + module: "module".into(), + arguments: vec![super::super::Argument { + size: argument_data.len(), + relocations: vec![], + numeric, + }], + }; + let node = wire::Node { + operation: Some(wire::node::Operation::Kernel(wire::Kernel { + function: 0, + arguments: vec![wire::Blob { + data: argument_data.to_vec(), + relocations: vec![], + }], + ..Default::default() + })), + }; + (node, kernel) + } + + const SITE: Site = Site { + graph: "graph", + node: 0, + function: 0, + argument: 0, + }; + + fn first(reach: &Reachability, address: u64) -> &UnresolvedCandidate { + &reach.unresolved[&address].first + } + + #[test] + fn kernel_argument_gap_candidate_is_reported_with_site_context() { + let low = allocation("low", 0x2000); + let high = allocation("high", 0x4000); + let (node, kernel) = kernel_graph(&0x3008u64.to_le_bytes(), vec![]); + let mut reach = Reachability::new(&[low, high], &[], &[], &[]).unwrap(); + reach.graph("prefill-4096", &[node], &[kernel]).unwrap(); + assert_eq!(reach.unresolved_count(), 1); + assert_eq!(reach.unresolved.len(), 1); + let candidate = first(&reach, 0x3008); + assert_eq!(candidate.graph, "prefill-4096"); + assert_eq!(candidate.node, 0); + assert_eq!(candidate.function, 0); + assert_eq!(candidate.argument, 0); + assert_eq!(candidate.offset, 0); + assert_eq!(reach.unresolved_unique_addresses(), 1); + } + + #[test] + fn unresolved_records_every_distinct_address_in_encounter_order() { + let low = allocation("low", 0x2000); + let high = allocation("high", 0x4000); + let data: Vec = (0..12u64) + .flat_map(|index| (0x3000 + 8 * index).to_le_bytes()) + .collect(); + let (node, kernel) = kernel_graph(&data, vec![]); + let mut reach = Reachability::new(&[low, high], &[], &[], &[]).unwrap(); + reach.graph("graph", &[node], &[kernel]).unwrap(); + assert_eq!(reach.unresolved_count(), 12); + assert_eq!(reach.unresolved.len(), 12); + assert_eq!(reach.unresolved_unique_addresses(), 12); + for index in 0..12 { + let address = 0x3000 + 8 * index as u64; + assert_eq!(first(&reach, address).graph, "graph"); + assert_eq!(first(&reach, address).offset, 8 * index); + assert_eq!(reach.unresolved[&address].order, index); + assert_eq!(reach.unresolved[&address].occurrences, 1); + } + } + + #[test] + fn kernel_argument_candidate_offset_counts_from_the_argument_start() { + let low = allocation("low", 0x2000); + let high = allocation("high", 0x4000); + let data = [ + 0x3008u64.to_le_bytes().as_slice(), + &[0u8; 8], + 0x3010u64.to_le_bytes().as_slice(), + ] + .concat(); + let (node, kernel) = kernel_graph(&data, vec![(0, 8)]); + let mut reach = Reachability::new(&[low, high], &[], &[], &[]).unwrap(); + reach.graph("graph", &[node], &[kernel]).unwrap(); + assert_eq!(reach.unresolved_count(), 1); + let candidate = first(&reach, 0x3010); + assert_eq!(candidate.offset, 16); + assert_eq!(candidate.argument, 0); + assert_eq!(candidate.node, 0); + } + #[test] - fn freed_interval_boundaries_exclude_candidates_but_not_explicit_bindings() { + fn shared_argument_bytes_record_one_example_per_address() { + let low = allocation("low", 0x2000); + let high = allocation("high", 0x4000); + let (node, kernel) = kernel_graph(&0x3008u64.to_le_bytes(), vec![]); + let mut reach = Reachability::new(&[low, high], &[], &[], &[]).unwrap(); + reach + .graph("graph-a", &[node.clone()], &[kernel.clone()]) + .unwrap(); + reach.graph("graph-b", &[node], &[kernel]).unwrap(); + assert_eq!(reach.unresolved_count(), 2); + assert_eq!(reach.unresolved.len(), 1); + assert_eq!(first(&reach, 0x3008).graph, "graph-a"); + assert_eq!(reach.unresolved[&0x3008].occurrences, 2); + assert_eq!(reach.unresolved_unique_addresses(), 1); + } + + #[test] + fn unresolved_report_names_the_kernel_and_its_symbol() { + let low = allocation("low", 0x2000); + let high = allocation("high", 0x4000); + let (node, kernel) = kernel_graph(&0x3008u64.to_le_bytes(), vec![]); + let mut reach = Reachability::new(&[low, high], &[], &[], &[]).unwrap(); + reach.graph("prefill-8192", &[node], &[kernel]).unwrap(); + let functions = vec![ + wire::Function { + module: "module".into(), + symbol: "cublasLt::splitKreduce_kernel".into(), + parameter_sizes: vec![8], + attributes: vec![], + }, + wire::Function { + module: "wrong-module".into(), + symbol: "wrong-symbol".into(), + parameter_sizes: vec![8], + attributes: vec![], + }, + ]; + assert_eq!( + reach.unresolved_report(&functions), + vec![ + "kernel argument scan: 1 occurrence and 1 distinct address fall inside the \ + recorded address envelope but resolve to no active recorded allocation (gap or \ + inactive range), so each may be a stale pointer or a numeric constant" + .to_owned(), + " graph \"prefill-8192\" node 0 kernel cublasLt::splitKreduce_kernel (module), \ + argument 0, offset 0: 0x3008 (1 occurrence)" + .to_owned(), + ] + ); + } + + #[test] + fn unresolved_report_bounds_examples_and_counts_hidden_occurrences() { + let low = allocation("low", 0x2000); + let high = allocation("high", 0x4000); + let data: Vec = (0..12u64) + .rev() + .flat_map(|index| (0x3000 + 8 * index).to_le_bytes()) + .collect(); + let (node, kernel) = kernel_graph(&data, vec![]); + let mut reach = Reachability::new(&[low, high], &[], &[], &[]).unwrap(); + reach + .graph("graph-a", &[node.clone()], &[kernel.clone()]) + .unwrap(); + reach.graph("graph-b", &[node], &[kernel]).unwrap(); + let lines = reach.unresolved_report(&[]); + assert_eq!(lines.len(), 12); + assert_eq!( + lines[0], + "kernel argument scan: 24 occurrences and 12 distinct addresses fall inside the \ + recorded address envelope but resolve to no active recorded allocation (gap or \ + inactive range), so each may be a stale pointer or a numeric constant" + ); + assert!(lines[1].contains("graph \"graph-a\" node 0 kernel unknown (unknown)")); + assert!(lines[1].ends_with("0x3058 (2 occurrences)")); + assert!(lines[10].ends_with("0x3010 (2 occurrences)")); + assert_eq!( + lines[11], + " … 2 more distinct addresses (4 occurrences) not shown" + ); + } + + #[test] + fn unresolved_report_omits_hidden_line_when_all_distinct_addresses_are_shown() { + let low = allocation("low", 0x2000); + let high = allocation("high", 0x4000); + + let (single_node, single_kernel) = kernel_graph(&0x3008u64.to_le_bytes(), vec![]); + let mut single = Reachability::new(&[low.clone(), high.clone()], &[], &[], &[]).unwrap(); + for index in 0..5 { + single + .graph( + &format!("graph-{index}"), + &[single_node.clone()], + &[single_kernel.clone()], + ) + .unwrap(); + } + let single_lines = single.unresolved_report(&[]); + assert_eq!(single_lines.len(), 2); + assert!(single_lines[1].ends_with("0x3008 (5 occurrences)")); + assert!(single_lines.iter().all(|line| !line.contains("not shown"))); + + let ten_data: Vec = (0..10u64) + .flat_map(|index| (0x3000 + 8 * index).to_le_bytes()) + .collect(); + let (ten_node, ten_kernel) = kernel_graph(&ten_data, vec![]); + let mut ten = Reachability::new(&[low, high], &[], &[], &[]).unwrap(); + ten.graph("graph-a", &[ten_node.clone()], &[ten_kernel.clone()]) + .unwrap(); + ten.graph("graph-b", &[ten_node], &[ten_kernel]).unwrap(); + let ten_lines = ten.unresolved_report(&[]); + assert_eq!(ten_lines.len(), 11); + for line in &ten_lines[1..11] { + assert!(line.ends_with("(2 occurrences)"), "line was: {line}"); + } + assert!(ten_lines.iter().all(|line| !line.contains("not shown"))); + } + + #[test] + fn unresolved_report_hidden_line_sums_omitted_address_occurrences() { + let low = allocation("low", 0x2000); + let high = allocation("high", 0x4000); + let mut reach = Reachability::new(&[low, high], &[], &[], &[]).unwrap(); + let ten_data: Vec = (0..10u64) + .flat_map(|index| (0x3000 + 8 * index).to_le_bytes()) + .collect(); + let (ten_node, ten_kernel) = kernel_graph(&ten_data, vec![]); + for index in 0..3 { + reach + .graph( + &format!("head-{index}"), + &[ten_node.clone()], + &[ten_kernel.clone()], + ) + .unwrap(); + } + let (eleventh_node, eleventh_kernel) = kernel_graph(&0x3050u64.to_le_bytes(), vec![]); + reach + .graph("tail-one", &[eleventh_node], &[eleventh_kernel]) + .unwrap(); + let (twelfth_node, twelfth_kernel) = kernel_graph(&0x3058u64.to_le_bytes(), vec![]); + for index in 0..4 { + reach + .graph( + &format!("tail-four-{index}"), + &[twelfth_node.clone()], + &[twelfth_kernel.clone()], + ) + .unwrap(); + } + let lines = reach.unresolved_report(&[]); + assert_eq!(lines.len(), 12); + assert!( + lines[0].starts_with("kernel argument scan: 35 occurrences and 12 distinct addresses") + ); + assert!(lines[1].ends_with("(3 occurrences)")); + assert!(lines[10].ends_with("(3 occurrences)")); + assert_eq!( + lines[11], + " … 2 more distinct addresses (5 occurrences) not shown" + ); + } + + #[test] + fn unresolved_report_is_empty_without_candidates() { + let reach = Reachability::new(&[allocation("only", 0x2000)], &[], &[], &[]).unwrap(); + assert!(reach.unresolved_report(&[]).is_empty()); + } + + #[test] + fn unresolved_report_prioritizes_distinct_kernel_symbols_before_backfilling() { + let low = allocation("low", 0x2000); + let high = allocation("high", 0x4000); + let make_fn = |name: &str, module: &str| wire::Function { + module: module.into(), + symbol: name.into(), + parameter_sizes: vec![], + attributes: vec![], + }; + let make_node_kernel = |function: usize, data: Vec| { + let size = data.len(); + ( + wire::Node { + operation: Some(wire::node::Operation::Kernel(wire::Kernel { + function: function as u64, + arguments: vec![wire::Blob { + data, + relocations: vec![], + }], + ..Default::default() + })), + }, + Kernel { + function, + module: format!("mod-{function}"), + arguments: vec![super::super::Argument { + size, + relocations: vec![], + numeric: vec![], + }], + }, + ) + }; + + let a_data: Vec = (0..10u64) + .flat_map(|index| (0x3000 + 8 * index).to_le_bytes()) + .collect(); + let b_data: Vec = (0..2u64) + .flat_map(|index| (0x3100 + 8 * index).to_le_bytes()) + .collect(); + let (node_a, kernel_a) = make_node_kernel(0, a_data); + let (node_b, kernel_b) = make_node_kernel(1, b_data); + let kernels = vec![kernel_a, kernel_b]; + + let mut two_sym = Reachability::new(&[low.clone(), high.clone()], &[], &[], &[]).unwrap(); + two_sym + .graph("g-a-0", std::slice::from_ref(&node_a), &kernels) + .unwrap(); + two_sym.graph("g-a-1", &[node_a], &kernels).unwrap(); + for idx in 0..3 { + two_sym + .graph( + &format!("g-b-{idx}"), + std::slice::from_ref(&node_b), + &kernels, + ) + .unwrap(); + } + let functions = vec![make_fn("kernel_a", "mod_a"), make_fn("kernel_b", "mod_b")]; + let lines = two_sym.unresolved_report(&functions); + assert_eq!(lines.len(), 12); + assert!( + lines[0].starts_with("kernel argument scan: 26 occurrences and 12 distinct addresses") + ); + assert!(lines.iter().any(|line| { + line.contains("kernel kernel_b (mod_b)") && line.contains("0x3100 (3 occurrences)") + })); + assert!( + lines[1..11] + .iter() + .all(|line| !line.contains("0x3048") && !line.contains("0x3108")) + ); + assert_eq!( + lines[11], + " … 2 more distinct addresses (5 occurrences) not shown" + ); + + let mut many_sym = Reachability::new(&[low, high], &[], &[], &[]).unwrap(); + let mut many_nodes = Vec::with_capacity(12); + let mut many_kernels = Vec::with_capacity(12); + let mut many_functions = Vec::with_capacity(12); + for sym_idx in 0..12usize { + let bytes = (0x3000 + 8 * sym_idx as u64).to_le_bytes().to_vec(); + let (node, kernel) = make_node_kernel(sym_idx, bytes); + many_nodes.push(node); + many_kernels.push(kernel); + many_functions.push(make_fn( + &format!("sym_{sym_idx:02}"), + &format!("mod_{sym_idx:02}"), + )); + } + many_sym + .graph("all-unique", &many_nodes, &many_kernels) + .unwrap(); + let many_lines = many_sym.unresolved_report(&many_functions); + assert_eq!(many_lines.len(), 12); + for (idx, line) in many_lines[1..11].iter().enumerate() { + assert!( + line.contains(&format!("kernel sym_{idx:02} (mod_{idx:02})")), + "line {idx}: {line}" + ); + } + assert!( + many_lines[1..11] + .iter() + .all(|line| !line.contains("sym_10") && !line.contains("sym_11")) + ); + assert_eq!( + many_lines[11], + " … 2 more distinct addresses (2 occurrences) not shown" + ); + } + + #[test] + fn kernel_argument_boundaries_and_external_values_follow_the_recorded_contract() { + let low = allocation("low", 0x2000); + let high = allocation("high", 0x4000); + for (value, reported) in [ + (low.address, false), + (low.address + 255, false), + (low.address + 256, true), + (high.address - 1, true), + (high.address, false), + (0x1000, false), + (high.address + 256, false), + ] { + let (node, kernel) = kernel_graph(&value.to_le_bytes(), vec![]); + let mut reach = Reachability::new(&[low.clone(), high.clone()], &[], &[], &[]).unwrap(); + reach.graph("graph", &[node], &[kernel]).unwrap(); + assert_eq!( + reach.unresolved.contains_key(&value), + reported, + "value {value:#x}" + ); + } + } + + #[test] + fn kernel_argument_inactive_ranges_are_reported_but_numeric_ranges_stay_lenient() { + let low = allocation("low", 0x2000); + let high = allocation("high", 0x4000); + let (node, kernel) = kernel_graph(&0x3008u64.to_le_bytes(), vec![]); + let mut reach = + Reachability::new(&[low.clone(), high.clone()], &[], &[(0x3000, 0x3100)], &[]).unwrap(); + reach.graph("graph", &[node], &[kernel]).unwrap(); + assert_eq!(reach.unresolved_count(), 1); + assert!(reach.unresolved.contains_key(&0x3008)); + let (node, kernel) = kernel_graph(&0x3008u64.to_le_bytes(), vec![(0, 8)]); + let mut reach = Reachability::new(&[low, high], &[], &[], &[]).unwrap(); + reach.graph("graph", &[node], &[kernel]).unwrap(); + assert!(reach.unresolved.is_empty()); + } + + #[test] + fn allocation_contents_still_tolerate_gap_candidates() { + let low = allocation("low", 0x2000); + let high = allocation("high", 0x4000); + let mut reach = Reachability::new(&[low.clone(), high], &[], &[], &[]).unwrap(); + reach.contents(&low, 0, &0x3008u64.to_le_bytes()).unwrap(); + assert!(reach.reached.is_empty()); + assert!(reach.unresolved.is_empty()); + } + + #[test] + fn unaligned_straddling_window_is_not_reported_while_aligned_stale_pointer_is() { + let low = allocation("low", 0x0000_0800_0000_0000); + let high = allocation("high", 0x0000_2000_0000_0000); + let small = 0x0000_1000u64; + let stale = 0x0000_1800_0000_0000u64; + let data = [ + low.address.to_le_bytes().as_slice(), + small.to_le_bytes().as_slice(), + stale.to_le_bytes().as_slice(), + ] + .concat(); + let straddling = u64::from_le_bytes(data[4..12].try_into().unwrap()); + assert_eq!(straddling, 0x0000_1000_0000_0800); + assert!(straddling >= low.address + low.nbytes && straddling < high.address); + let (node, kernel) = kernel_graph(&data, vec![]); + let mut reach = Reachability::new(&[low, high], &[], &[], &[]).unwrap(); + reach.graph("prefill4096", &[node], &[kernel]).unwrap(); + assert!(reach.reached.contains("low")); + assert!(!reach.unresolved.contains_key(&straddling)); + assert!(reach.unresolved.contains_key(&stale)); + assert_eq!(first(&reach, stale).offset, 16); + assert_eq!(reach.unresolved_count(), 1); + assert_eq!(reach.unresolved_unique_addresses(), 1); + } + + #[test] + fn aligned_reporting_checks_argument_relative_offset_after_unaligned_numeric_prefix() { + let low = allocation("low", 0x2000); + let high = allocation("high", 0x0001_0000_0000_0000); + let data = [[0u8; 8].as_slice(), 0x3008u64.to_le_bytes().as_slice()].concat(); + let straddling = u64::from_le_bytes(data[4..12].try_into().unwrap()); + assert_eq!(straddling, 0x0000_3008_0000_0000); + assert!(straddling >= low.address + low.nbytes && straddling < high.address); + let (node, kernel) = kernel_graph(&data, vec![(0, 4)]); + let mut reach = Reachability::new(&[low, high], &[], &[], &[]).unwrap(); + reach.graph("prefill4096", &[node], &[kernel]).unwrap(); + assert_eq!(reach.unresolved_count(), 1); + assert_eq!(reach.unresolved_unique_addresses(), 1); + assert!(!reach.unresolved.contains_key(&straddling)); + assert!(reach.unresolved.contains_key(&0x3008)); + assert_eq!(first(&reach, 0x3008).offset, 8); + } + + #[test] + fn freed_interval_boundaries_report_kernel_candidates_without_retaining_storage() { let mut storage = allocation("segment", 0x200000000000); storage.nbytes = 4096; for (offset, retained) in [ @@ -564,14 +1246,14 @@ mod tests { (3071, false), (3072, true), ] { - let mut reach = Reachability::new( + let mut unaligned = Reachability::new( &[storage.clone()], &[], &[(storage.address + 1024, storage.address + 3072)], &[], ) .unwrap(); - reach + unaligned .blob( &[ b"unaligned".as_slice(), @@ -579,11 +1261,40 @@ mod tests { ] .concat(), &[], + &SITE, ) .unwrap(); - assert_eq!(!reach.reached.is_empty(), retained); - reach.reference(&storage.name).unwrap(); - assert!(reach.reached.contains(&storage.name)); + assert_eq!(!unaligned.reached.is_empty(), retained); + assert!(unaligned.unresolved.is_empty()); + + let mut aligned = Reachability::new( + &[storage.clone()], + &[], + &[(storage.address + 1024, storage.address + 3072)], + &[], + ) + .unwrap(); + aligned + .blob( + &[ + [0u8; 8].as_slice(), + (storage.address + offset).to_le_bytes().as_slice(), + ] + .concat(), + &[], + &SITE, + ) + .unwrap(); + assert_eq!(!aligned.reached.is_empty(), retained); + assert_eq!( + aligned.unresolved.contains_key(&(storage.address + offset)), + !retained, + ); + if !retained { + assert_eq!(first(&aligned, storage.address + offset).offset, 8); + } + aligned.reference(&storage.name).unwrap(); + assert!(aligned.reached.contains(&storage.name)); } }