use std::collections::BTreeMap;
use figment::value::{Dict, Value};
pub trait DiscoveryLayer {
fn name(&self) -> &'static str;
fn discover(&self) -> Dict;
}
pub fn deep_merge(base: &mut Dict, overlay: Dict) {
for (key, incoming) in overlay {
match (base.get_mut(&key), incoming) {
(Some(Value::Dict(_, base_inner)), Value::Dict(_, over_inner)) => {
deep_merge(base_inner, over_inner);
}
(_, incoming) => {
base.insert(key, incoming);
}
}
}
}
#[must_use]
pub fn compose(layers: &[&dyn DiscoveryLayer]) -> Dict {
compose_with_provenance(layers).dict
}
#[must_use]
pub fn layer_names(layers: &[&dyn DiscoveryLayer]) -> Vec<&'static str> {
layers.iter().map(|layer| layer.name()).collect()
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct LayerAttribution {
inner: BTreeMap<Vec<String>, &'static str>,
}
impl LayerAttribution {
#[must_use]
pub fn len(&self) -> usize {
self.inner.len()
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.inner.is_empty()
}
#[must_use]
pub fn layer_of(&self, path: &[&str]) -> Option<&'static str> {
self.layer_of_owned(&path.iter().map(|&s| s.to_owned()).collect::<Vec<String>>())
}
#[must_use]
pub fn layer_of_owned(&self, path: &[String]) -> Option<&'static str> {
self.inner.get(path).copied()
}
pub fn iter(&self) -> impl Iterator<Item = (&[String], &'static str)> + '_ {
self.inner.iter().map(|(p, l)| (p.as_slice(), *l))
}
#[must_use]
pub fn writes_by_layer(&self) -> BTreeMap<&'static str, Vec<&[String]>> {
let mut out: BTreeMap<&'static str, Vec<&[String]>> = BTreeMap::new();
for (path, layer) in &self.inner {
out.entry(*layer).or_default().push(path.as_slice());
}
out
}
#[must_use]
pub fn leaf_counts_by_layer(&self) -> BTreeMap<&'static str, usize> {
let mut out: BTreeMap<&'static str, usize> = BTreeMap::new();
for layer in self.inner.values() {
*out.entry(*layer).or_insert(0) += 1;
}
out
}
#[must_use]
pub fn surviving_layer_names(&self) -> Vec<&'static str> {
use std::collections::BTreeSet;
let mut set: BTreeSet<&'static str> = BTreeSet::new();
for &layer in self.inner.values() {
set.insert(layer);
}
set.into_iter().collect()
}
pub fn subtree_iter<'a>(
&'a self,
prefix: &'a [String],
) -> impl Iterator<Item = (&'a [String], &'static str)> + 'a {
use std::ops::Bound;
self.inner
.range::<[String], _>((Bound::Included(prefix), Bound::Unbounded))
.take_while(move |(k, _)| path_has_prefix(k, prefix))
.map(|(k, l)| (k.as_slice(), *l))
}
#[must_use]
pub fn subtree(&self, prefix: &[String]) -> LayerAttribution {
LayerAttribution {
inner: self
.subtree_iter(prefix)
.map(|(p, l)| (p.to_vec(), l))
.collect(),
}
}
#[must_use]
pub fn subtree_surviving_layer_names(&self, prefix: &[String]) -> Vec<&'static str> {
use std::collections::BTreeSet;
let mut set: BTreeSet<&'static str> = BTreeSet::new();
for (_, layer) in self.subtree_iter(prefix) {
set.insert(layer);
}
set.into_iter().collect()
}
#[must_use]
pub fn subtree_leaf_counts_by_layer(&self, prefix: &[String]) -> BTreeMap<&'static str, usize> {
let mut out: BTreeMap<&'static str, usize> = BTreeMap::new();
for (_, layer) in self.subtree_iter(prefix) {
*out.entry(layer).or_insert(0) += 1;
}
out
}
#[must_use]
pub fn subtree_writes_by_layer<'a>(
&'a self,
prefix: &'a [String],
) -> BTreeMap<&'static str, Vec<&'a [String]>> {
let mut out: BTreeMap<&'static str, Vec<&'a [String]>> = BTreeMap::new();
for (path, layer) in self.subtree_iter(prefix) {
out.entry(layer).or_default().push(path);
}
out
}
#[must_use]
pub fn writes_of_layer<'a>(&'a self, layer: &str) -> Vec<&'a [String]> {
self.inner
.iter()
.filter_map(|(p, l)| (*l == layer).then_some(p.as_slice()))
.collect()
}
#[must_use]
pub fn leaf_count_of_layer(&self, layer: &str) -> usize {
self.inner.values().filter(|l| **l == layer).count()
}
#[must_use]
pub fn subtree_writes_of_layer<'a>(
&'a self,
prefix: &'a [String],
layer: &str,
) -> Vec<&'a [String]> {
self.subtree_iter(prefix)
.filter_map(|(p, l)| (l == layer).then_some(p))
.collect()
}
#[must_use]
pub fn subtree_leaf_count_of_layer(&self, prefix: &[String], layer: &str) -> usize {
self.subtree_iter(prefix)
.filter(|(_, l)| *l == layer)
.count()
}
#[must_use]
pub fn dominant_layer(&self) -> Option<&'static str> {
self.leaf_counts_by_layer()
.into_iter()
.max_by(|(a_name, a_count), (b_name, b_count)| {
a_count.cmp(b_count).then_with(|| b_name.cmp(a_name))
})
.map(|(name, _)| name)
}
#[must_use]
pub fn subtree_dominant_layer(&self, prefix: &[String]) -> Option<&'static str> {
self.subtree_leaf_counts_by_layer(prefix)
.into_iter()
.max_by(|(a_name, a_count), (b_name, b_count)| {
a_count.cmp(b_count).then_with(|| b_name.cmp(a_name))
})
.map(|(name, _)| name)
}
#[must_use]
pub fn layer_ranking(&self) -> Vec<(&'static str, usize)> {
let mut ranking: Vec<(&'static str, usize)> =
self.leaf_counts_by_layer().into_iter().collect();
ranking.sort_by(|(a_name, a_count), (b_name, b_count)| {
b_count.cmp(a_count).then_with(|| a_name.cmp(b_name))
});
ranking
}
#[must_use]
pub fn subtree_layer_ranking(&self, prefix: &[String]) -> Vec<(&'static str, usize)> {
let mut ranking: Vec<(&'static str, usize)> = self
.subtree_leaf_counts_by_layer(prefix)
.into_iter()
.collect();
ranking.sort_by(|(a_name, a_count), (b_name, b_count)| {
b_count.cmp(a_count).then_with(|| a_name.cmp(b_name))
});
ranking
}
#[must_use]
pub fn weakest_layer(&self) -> Option<&'static str> {
self.leaf_counts_by_layer()
.into_iter()
.min_by(|(a_name, a_count), (b_name, b_count)| {
a_count.cmp(b_count).then_with(|| b_name.cmp(a_name))
})
.map(|(name, _)| name)
}
#[must_use]
pub fn subtree_weakest_layer(&self, prefix: &[String]) -> Option<&'static str> {
self.subtree_leaf_counts_by_layer(prefix)
.into_iter()
.min_by(|(a_name, a_count), (b_name, b_count)| {
a_count.cmp(b_count).then_with(|| b_name.cmp(a_name))
})
.map(|(name, _)| name)
}
#[must_use]
pub fn dominant_entry(&self) -> Option<(&'static str, usize)> {
self.leaf_counts_by_layer()
.into_iter()
.max_by(|(a_name, a_count), (b_name, b_count)| {
a_count.cmp(b_count).then_with(|| b_name.cmp(a_name))
})
}
#[must_use]
pub fn subtree_dominant_entry(&self, prefix: &[String]) -> Option<(&'static str, usize)> {
self.subtree_leaf_counts_by_layer(prefix)
.into_iter()
.max_by(|(a_name, a_count), (b_name, b_count)| {
a_count.cmp(b_count).then_with(|| b_name.cmp(a_name))
})
}
#[must_use]
pub fn weakest_entry(&self) -> Option<(&'static str, usize)> {
self.leaf_counts_by_layer()
.into_iter()
.min_by(|(a_name, a_count), (b_name, b_count)| {
a_count.cmp(b_count).then_with(|| b_name.cmp(a_name))
})
}
#[must_use]
pub fn subtree_weakest_entry(&self, prefix: &[String]) -> Option<(&'static str, usize)> {
self.subtree_leaf_counts_by_layer(prefix)
.into_iter()
.min_by(|(a_name, a_count), (b_name, b_count)| {
a_count.cmp(b_count).then_with(|| b_name.cmp(a_name))
})
}
}
#[derive(Debug, Clone, Default, PartialEq)]
pub struct DiscoveryComposition {
pub dict: Dict,
pub attribution: LayerAttribution,
}
#[must_use]
pub fn compose_with_provenance(layers: &[&dyn DiscoveryLayer]) -> DiscoveryComposition {
let mut dict = Dict::new();
let mut attribution: BTreeMap<Vec<String>, &'static str> = BTreeMap::new();
for layer in layers {
deep_merge_attributed(
&mut dict,
layer.discover(),
&[],
layer.name(),
&mut attribution,
);
}
DiscoveryComposition {
dict,
attribution: LayerAttribution { inner: attribution },
}
}
fn deep_merge_attributed(
base: &mut Dict,
overlay: Dict,
prefix: &[String],
layer: &'static str,
attribution: &mut BTreeMap<Vec<String>, &'static str>,
) {
for (key, incoming) in overlay {
let mut path = Vec::with_capacity(prefix.len() + 1);
path.extend_from_slice(prefix);
path.push(key.clone());
match (base.get_mut(&key), incoming) {
(Some(Value::Dict(_, base_inner)), Value::Dict(_, over_inner)) => {
deep_merge_attributed(base_inner, over_inner, &path, layer, attribution);
}
(_, incoming) => {
attribution.retain(|p, _| !path_has_prefix(p, &path));
attribute_leaves(&incoming, &path, layer, attribution);
base.insert(key, incoming);
}
}
}
}
fn path_has_prefix(path: &[String], prefix: &[String]) -> bool {
path.len() >= prefix.len() && path[..prefix.len()] == *prefix
}
fn attribute_leaves(
v: &Value,
path: &[String],
layer: &'static str,
attribution: &mut BTreeMap<Vec<String>, &'static str>,
) {
match v {
Value::Dict(_, inner) => {
for (k, sub) in inner {
let mut sub_path = path.to_vec();
sub_path.push(k.clone());
attribute_leaves(sub, &sub_path, layer, attribution);
}
}
_ => {
attribution.insert(path.to_vec(), layer);
}
}
}
#[must_use]
pub fn contributor_names(layers: &[&dyn DiscoveryLayer]) -> Vec<&'static str> {
layers
.iter()
.filter(|layer| !layer.discover().is_empty())
.map(|layer| layer.name())
.collect()
}
#[must_use]
pub fn silent_layer_names(layers: &[&dyn DiscoveryLayer]) -> Vec<&'static str> {
layers
.iter()
.filter(|layer| layer.discover().is_empty())
.map(|layer| layer.name())
.collect()
}
#[must_use]
pub fn nonempty_layer_dicts(layers: &[&dyn DiscoveryLayer]) -> Vec<(&'static str, Dict)> {
layers
.iter()
.filter_map(|layer| {
let dict = layer.discover();
if dict.is_empty() {
None
} else {
Some((layer.name(), dict))
}
})
.collect()
}
fn touches_path(dict: &Dict, path: &[&str]) -> bool {
let Some((head, tail)) = path.split_first() else {
return !dict.is_empty();
};
let Some(value) = dict.get(*head) else {
return false;
};
if tail.is_empty() {
return true;
}
match value {
Value::Dict(_, inner) => touches_path(inner, tail),
_ => true,
}
}
#[must_use]
pub fn contributors_at(layers: &[&dyn DiscoveryLayer], path: &[&str]) -> Vec<&'static str> {
layers
.iter()
.filter(|layer| touches_path(&layer.discover(), path))
.map(|layer| layer.name())
.collect()
}
#[must_use]
pub fn silenced_at(layers: &[&dyn DiscoveryLayer], path: &[&str]) -> Vec<&'static str> {
let mut names: Vec<&'static str> = layers
.iter()
.filter(|layer| touches_path(&layer.discover(), path))
.map(|layer| layer.name())
.collect();
names.pop();
names
}
#[must_use]
pub fn decider_at(layers: &[&dyn DiscoveryLayer], path: &[&str]) -> Option<&'static str> {
layers
.iter()
.rev()
.find(|layer| touches_path(&layer.discover(), path))
.map(|layer| layer.name())
}
#[must_use]
pub fn coarsest_at(layers: &[&dyn DiscoveryLayer], path: &[&str]) -> Option<&'static str> {
layers
.iter()
.find(|layer| touches_path(&layer.discover(), path))
.map(|layer| layer.name())
}
#[must_use]
pub fn is_contested_at(layers: &[&dyn DiscoveryLayer], path: &[&str]) -> bool {
layers
.iter()
.filter(|layer| touches_path(&layer.discover(), path))
.nth(1)
.is_some()
}
#[must_use]
pub fn contributor_count_at(layers: &[&dyn DiscoveryLayer], path: &[&str]) -> usize {
layers
.iter()
.filter(|layer| touches_path(&layer.discover(), path))
.count()
}
#[must_use]
pub fn is_touched_at(layers: &[&dyn DiscoveryLayer], path: &[&str]) -> bool {
layers
.iter()
.any(|layer| touches_path(&layer.discover(), path))
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PathContest {
pub decider: &'static str,
pub overridden: Vec<&'static str>,
}
impl PathContest {
#[must_use]
pub fn is_contested(&self) -> bool {
!self.overridden.is_empty()
}
#[must_use]
pub fn contributor_count(&self) -> usize {
self.overridden.len() + 1
}
#[must_use]
pub fn contributors(&self) -> Vec<&'static str> {
let mut out = Vec::with_capacity(self.overridden.len() + 1);
out.extend_from_slice(&self.overridden);
out.push(self.decider);
out
}
#[must_use]
pub fn coarsest(&self) -> &'static str {
self.overridden.first().copied().unwrap_or(self.decider)
}
}
#[must_use]
pub fn contest_at(layers: &[&dyn DiscoveryLayer], path: &[&str]) -> Option<PathContest> {
let mut names: Vec<&'static str> = layers
.iter()
.filter(|layer| touches_path(&layer.discover(), path))
.map(|layer| layer.name())
.collect();
let decider = names.pop()?;
Some(PathContest {
decider,
overridden: names,
})
}
#[cfg(test)]
mod tests {
use super::*;
use figment::value::Value;
struct Fixed(&'static str, Dict);
impl DiscoveryLayer for Fixed {
fn name(&self) -> &'static str {
self.0
}
fn discover(&self) -> Dict {
self.1.clone()
}
}
fn dict(pairs: &[(&str, Value)]) -> Dict {
let mut d = Dict::new();
for (k, v) in pairs {
d.insert((*k).to_owned(), v.clone());
}
d
}
#[test]
fn deep_merge_overlay_wins_scalars_and_keeps_siblings() {
let mut base = dict(&[("a", Value::from(1i64)), ("b", Value::from(2i64))]);
deep_merge(
&mut base,
dict(&[("b", Value::from(20i64)), ("c", Value::from(3i64))]),
);
assert_eq!(
base.get("a"),
Some(&Value::from(1i64)),
"untouched sibling kept"
);
assert_eq!(base.get("b"), Some(&Value::from(20i64)), "overlay wins");
assert_eq!(base.get("c"), Some(&Value::from(3i64)), "new key added");
}
#[test]
fn deep_merge_recurses_into_nested_dicts() {
let mut base = dict(&[(
"breathe",
Value::from(dict(&[
("setpoint", Value::from(0.80)),
("mode", Value::from("live")),
])),
)]);
deep_merge(
&mut base,
dict(&[(
"breathe",
Value::from(dict(&[("mode", Value::from("shadow"))])),
)]),
);
let Some(Value::Dict(_, inner)) = base.get("breathe") else {
panic!("nested dict preserved");
};
assert_eq!(
inner.get("setpoint"),
Some(&Value::from(0.80)),
"sibling survives"
);
assert_eq!(
inner.get("mode"),
Some(&Value::from("shadow")),
"leaf overridden"
);
}
#[test]
fn deep_merge_dict_replaces_scalar_and_vice_versa() {
let mut base = dict(&[("x", Value::from(1i64))]);
deep_merge(
&mut base,
dict(&[("x", Value::from(dict(&[("y", Value::from(2i64))])))]),
);
assert!(
matches!(base.get("x"), Some(Value::Dict(..))),
"dict replaced scalar"
);
let mut base = dict(&[("x", Value::from(dict(&[("y", Value::from(2i64))])))]);
deep_merge(&mut base, dict(&[("x", Value::from(9i64))]));
assert_eq!(
base.get("x"),
Some(&Value::from(9i64)),
"scalar replaced dict"
);
}
#[test]
fn deep_merge_replaces_arrays_wholesale() {
let mut base = dict(&[(
"xs",
Value::from(vec![Value::from(1i64), Value::from(2i64)]),
)]);
deep_merge(
&mut base,
dict(&[("xs", Value::from(vec![Value::from(9i64)]))]),
);
let Some(Value::Array(_, arr)) = base.get("xs") else {
panic!("array value");
};
assert_eq!(arr.len(), 1, "array replaced wholesale, not concatenated");
assert_eq!(arr[0], Value::from(9i64));
}
#[test]
fn deep_merge_recurses_three_levels_preserving_each_sibling() {
let mut base = dict(&[(
"a",
Value::from(dict(&[(
"b",
Value::from(dict(&[
("keep", Value::from(1i64)),
("change", Value::from(2i64)),
])),
)])),
)]);
deep_merge(
&mut base,
dict(&[(
"a",
Value::from(dict(&[(
"b",
Value::from(dict(&[("change", Value::from(20i64))])),
)])),
)]),
);
let Some(Value::Dict(_, a)) = base.get("a") else {
panic!("a")
};
let Some(Value::Dict(_, b)) = a.get("b") else {
panic!("b")
};
assert_eq!(
b.get("keep"),
Some(&Value::from(1i64)),
"level-3 sibling survives"
);
assert_eq!(
b.get("change"),
Some(&Value::from(20i64)),
"level-3 leaf overridden"
);
}
#[test]
fn compose_specific_layer_overrides_coarse() {
let coarse = Fixed(
"platform",
dict(&[
("setpoint", Value::from(0.80)),
("floor", Value::from("256Mi")),
]),
);
let specific = Fixed("tenancy", dict(&[("setpoint", Value::from(0.70))]));
let out = compose(&[&coarse, &specific]);
assert_eq!(
out.get("setpoint"),
Some(&Value::from(0.70)),
"specific (later) wins"
);
assert_eq!(
out.get("floor"),
Some(&Value::from("256Mi")),
"coarse-only key retained"
);
}
#[test]
fn compose_empty_layer_contributes_nothing() {
let real = Fixed("cloud", dict(&[("k", Value::from(1i64))]));
let empty = Fixed("undetectable", Dict::new());
assert_eq!(
compose(&[&real, &empty]),
compose(&[&real]),
"empty axis invisible"
);
}
#[test]
fn compose_no_layers_is_empty() {
assert!(compose(&[]).is_empty());
}
#[test]
fn layer_names_in_application_order() {
let a = Fixed("platform", Dict::new());
let b = Fixed("tenancy", Dict::new());
assert_eq!(layer_names(&[&a, &b]), vec!["platform", "tenancy"]);
}
#[test]
fn compose_with_provenance_attributes_each_leaf_to_its_writer() {
let a = Fixed(
"platform",
dict(&[("k1", Value::from(1i64)), ("k2", Value::from(2i64))]),
);
let b = Fixed(
"tenancy",
dict(&[("k2", Value::from(20i64)), ("k3", Value::from(3i64))]),
);
let out = compose_with_provenance(&[&a, &b]);
assert_eq!(
out.dict,
compose(&[&a, &b]),
"dict projection agrees with compose"
);
assert_eq!(out.attribution.layer_of(&["k1"]), Some("platform"));
assert_eq!(
out.attribution.layer_of(&["k2"]),
Some("tenancy"),
"later layer wins per leaf"
);
assert_eq!(out.attribution.layer_of(&["k3"]), Some("tenancy"));
assert_eq!(
out.attribution.layer_of(&["never"]),
None,
"unset paths are unattributed"
);
assert_eq!(out.attribution.len(), 3);
assert!(!out.attribution.is_empty());
}
#[test]
fn compose_with_provenance_recurses_into_nested_dicts_per_leaf() {
let a = Fixed(
"platform",
dict(&[(
"breathe",
Value::from(dict(&[
("setpoint", Value::from(0.80)),
("mode", Value::from("live")),
])),
)]),
);
let b = Fixed(
"tenancy",
dict(&[(
"breathe",
Value::from(dict(&[("mode", Value::from("shadow"))])),
)]),
);
let out = compose_with_provenance(&[&a, &b]);
assert_eq!(
out.attribution.layer_of(&["breathe", "setpoint"]),
Some("platform"),
"sibling under nested dict retains coarse writer"
);
assert_eq!(
out.attribution.layer_of(&["breathe", "mode"]),
Some("tenancy"),
"overwritten nested leaf gets the specific writer"
);
assert_eq!(out.attribution.len(), 2);
}
#[test]
fn compose_with_provenance_dict_replaces_scalar_purges_prior_attribution() {
let a = Fixed("first", dict(&[("x", Value::from(1i64))]));
let b = Fixed(
"second",
dict(&[("x", Value::from(dict(&[("y", Value::from(2i64))])))]),
);
let out = compose_with_provenance(&[&a, &b]);
assert_eq!(
out.attribution.layer_of(&["x"]),
None,
"scalar leaf attribution purged when replaced by a dict"
);
assert_eq!(out.attribution.layer_of(&["x", "y"]), Some("second"));
assert_eq!(out.attribution.len(), 1);
}
#[test]
fn compose_with_provenance_scalar_replaces_dict_purges_sub_attributions() {
let a = Fixed(
"first",
dict(&[(
"x",
Value::from(dict(&[("y", Value::from(1i64)), ("z", Value::from(2i64))])),
)]),
);
let b = Fixed("second", dict(&[("x", Value::from(99i64))]));
let out = compose_with_provenance(&[&a, &b]);
assert_eq!(
out.attribution.layer_of(&["x", "y"]),
None,
"sub-leaf attribution purged when parent replaced by scalar"
);
assert_eq!(out.attribution.layer_of(&["x", "z"]), None);
assert_eq!(
out.attribution.layer_of(&["x"]),
Some("second"),
"replacing scalar attributed at the flattened path"
);
assert_eq!(out.attribution.len(), 1);
}
#[test]
fn compose_with_provenance_arrays_replace_wholesale_and_reattribute() {
let a = Fixed(
"first",
dict(&[("xs", Value::from(vec![Value::from(1i64)]))]),
);
let b = Fixed(
"second",
dict(&[(
"xs",
Value::from(vec![Value::from(9i64), Value::from(10i64)]),
)]),
);
let out = compose_with_provenance(&[&a, &b]);
assert_eq!(out.attribution.layer_of(&["xs"]), Some("second"));
assert_eq!(out.attribution.len(), 1);
}
#[test]
fn compose_with_provenance_empty_layer_preserves_prior_attribution() {
let a = Fixed("real", dict(&[("k", Value::from(1i64))]));
let empty = Fixed("undetectable", Dict::new());
let out = compose_with_provenance(&[&a, &empty]);
assert_eq!(out.attribution.layer_of(&["k"]), Some("real"));
assert_eq!(out.attribution.len(), 1);
}
#[test]
fn compose_with_provenance_no_layers_is_empty_and_unattributed() {
let out = compose_with_provenance(&[]);
assert!(out.dict.is_empty());
assert!(out.attribution.is_empty());
assert_eq!(out.attribution.len(), 0);
}
#[test]
fn compose_with_provenance_iter_yields_lexicographic_order() {
let a = Fixed("A", dict(&[("z", Value::from(1i64))]));
let b = Fixed(
"B",
dict(&[("a", Value::from(dict(&[("y", Value::from(2i64))])))]),
);
let c = Fixed("C", dict(&[("m", Value::from(3i64))]));
let out = compose_with_provenance(&[&a, &b, &c]);
let observed: Vec<(Vec<String>, &'static str)> = out
.attribution
.iter()
.map(|(p, l)| (p.to_vec(), l))
.collect();
assert_eq!(
observed,
vec![
(vec!["a".to_owned(), "y".to_owned()], "B"),
(vec!["m".to_owned()], "C"),
(vec!["z".to_owned()], "A"),
]
);
}
#[test]
fn compose_with_provenance_dict_matches_independent_deep_merge_walk() {
let a = Fixed(
"A",
dict(&[
("outer", Value::from(dict(&[("a", Value::from(1i64))]))),
("scalar", Value::from(1i64)),
]),
);
let b = Fixed(
"B",
dict(&[
("outer", Value::from(dict(&[("b", Value::from(2i64))]))),
("scalar", Value::from(dict(&[("inner", Value::from(9i64))]))),
]),
);
let via_prov = compose_with_provenance(&[&a, &b]).dict;
let mut via_plain = Dict::new();
deep_merge(&mut via_plain, a.discover());
deep_merge(&mut via_plain, b.discover());
assert_eq!(
via_prov, via_plain,
"attributed compose dict matches independent deep_merge walk"
);
}
#[test]
fn layer_of_owned_agrees_with_layer_of_pointwise() {
let a = Fixed(
"A",
dict(&[(
"outer",
Value::from(dict(&[("a", Value::from(1i64)), ("b", Value::from(2i64))])),
)]),
);
let b = Fixed("B", dict(&[("scalar", Value::from(3i64))]));
let out = compose_with_provenance(&[&a, &b]);
for (path_slice, layer) in out.attribution.iter() {
let borrowed: Vec<&str> = path_slice.iter().map(String::as_str).collect();
assert_eq!(
out.attribution.layer_of(&borrowed),
Some(layer),
"layer_of at {path_slice:?} must match iter()",
);
assert_eq!(
out.attribution.layer_of_owned(path_slice),
Some(layer),
"layer_of_owned at {path_slice:?} must match iter()",
);
}
let absent: [&str; 2] = ["outer", "never"];
assert_eq!(out.attribution.layer_of(&absent), None);
let absent_owned: Vec<String> = absent.iter().map(|s| (*s).to_owned()).collect();
assert_eq!(out.attribution.layer_of_owned(&absent_owned), None);
}
#[test]
fn layer_of_is_not_a_prefix_match_only_exact_leaves() {
let a = Fixed(
"A",
dict(&[("outer", Value::from(dict(&[("a", Value::from(1i64))])))]),
);
let out = compose_with_provenance(&[&a]);
assert_eq!(out.attribution.layer_of(&["outer", "a"]), Some("A"));
assert_eq!(
out.attribution.layer_of(&["outer"]),
None,
"interior nodes are not leaves and must not resolve",
);
}
#[test]
fn layer_of_owned_skips_allocation_on_owned_paths() {
let a = Fixed(
"A",
dict(&[("k1", Value::from(1i64)), ("k2", Value::from(2i64))]),
);
let b = Fixed("B", dict(&[("k3", Value::from(3i64))]));
let out = compose_with_provenance(&[&a, &b]);
let owned_paths: Vec<Vec<String>> = out
.attribution
.iter()
.map(|(path_slice, _)| path_slice.to_vec())
.collect();
for path in &owned_paths {
assert!(
out.attribution.layer_of_owned(path).is_some(),
"every iter()-sourced path must resolve on layer_of_owned",
);
}
}
#[test]
fn writes_by_layer_groups_leaves_under_their_writer() {
let a = Fixed(
"platform",
dict(&[("k1", Value::from(1i64)), ("k2", Value::from(2i64))]),
);
let b = Fixed(
"tenancy",
dict(&[("k2", Value::from(20i64)), ("k3", Value::from(3i64))]),
);
let out = compose_with_provenance(&[&a, &b]);
let groups = out.attribution.writes_by_layer();
let layers: Vec<&&'static str> = groups.keys().collect();
assert_eq!(
layers,
vec![&"platform", &"tenancy"],
"outer BTreeMap keys sort lex on layer name",
);
let platform = groups.get("platform").expect("platform bucket");
let tenancy = groups.get("tenancy").expect("tenancy bucket");
assert_eq!(
platform,
&vec![["k1".to_owned()].as_slice()],
"platform kept k1 only",
);
assert_eq!(
tenancy,
&vec![["k2".to_owned()].as_slice(), ["k3".to_owned()].as_slice(),],
"tenancy holds k2 (overwritten) and k3, in lex path order",
);
}
#[test]
fn writes_by_layer_partitions_leaves_by_writer() {
let a = Fixed(
"A",
dict(&[(
"outer",
Value::from(dict(&[
("keep", Value::from("k")),
("change", Value::from(1i64)),
])),
)]),
);
let b = Fixed(
"B",
dict(&[
("outer", Value::from(dict(&[("change", Value::from(9i64))]))),
("array", Value::from(vec![Value::from(0i64)])),
]),
);
let out = compose_with_provenance(&[&a, &b]);
let groups = out.attribution.writes_by_layer();
let bucket_sum: usize = groups.values().map(Vec::len).sum();
assert_eq!(bucket_sum, out.attribution.len());
let mut flattened: Vec<&[String]> = groups
.values()
.flat_map(|paths| paths.iter().copied())
.collect();
flattened.sort();
let mut iter_paths: Vec<&[String]> = out.attribution.iter().map(|(p, _)| p).collect();
iter_paths.sort();
assert_eq!(
flattened, iter_paths,
"the flattened bucket union equals iter()'s path set",
);
for (layer, paths) in &groups {
for path in paths {
assert_eq!(
out.attribution.layer_of_owned(path),
Some(*layer),
"layer_of_owned must agree with the bucket layer",
);
}
}
}
#[test]
fn writes_by_layer_empty_when_no_layers() {
let out = compose_with_provenance(&[]);
assert!(
out.attribution.writes_by_layer().is_empty(),
"no layers ⇒ no buckets",
);
}
#[test]
fn writes_by_layer_empty_layer_drops_out_of_buckets() {
let real = Fixed("real", dict(&[("k", Value::from(1i64))]));
let empty = Fixed("undetectable", Dict::new());
let out = compose_with_provenance(&[&real, &empty]);
let groups = out.attribution.writes_by_layer();
assert_eq!(groups.len(), 1);
assert!(
groups.contains_key("real"),
"the real writer keeps its bucket",
);
assert!(
!groups.contains_key("undetectable"),
"an empty-dict layer contributes no leaves, so no bucket",
);
}
#[test]
fn writes_by_layer_yields_deterministic_layer_and_path_order() {
let a = Fixed("Z", dict(&[("z", Value::from(1i64))]));
let b = Fixed(
"A",
dict(&[
("a", Value::from(dict(&[("y", Value::from(2i64))]))),
("m", Value::from(3i64)),
]),
);
let out = compose_with_provenance(&[&a, &b]);
let groups = out.attribution.writes_by_layer();
let layers: Vec<&&'static str> = groups.keys().collect();
assert_eq!(layers, vec![&"A", &"Z"]);
let a_paths = groups.get("A").expect("A bucket");
assert_eq!(
a_paths,
&vec![
["a".to_owned(), "y".to_owned()].as_slice(),
["m".to_owned()].as_slice(),
],
);
let z_paths = groups.get("Z").expect("Z bucket");
assert_eq!(z_paths, &vec![["z".to_owned()].as_slice()]);
}
#[test]
fn leaf_counts_by_layer_counts_writes_per_layer() {
let a = Fixed(
"platform",
dict(&[("k1", Value::from(1i64)), ("k2", Value::from(2i64))]),
);
let b = Fixed(
"tenancy",
dict(&[("k2", Value::from(20i64)), ("k3", Value::from(3i64))]),
);
let out = compose_with_provenance(&[&a, &b]);
let counts = out.attribution.leaf_counts_by_layer();
let layers: Vec<&&'static str> = counts.keys().collect();
assert_eq!(
layers,
vec![&"platform", &"tenancy"],
"outer BTreeMap keys sort lex on layer name",
);
assert_eq!(
counts.get("platform").copied(),
Some(1),
"platform kept k1 only",
);
assert_eq!(
counts.get("tenancy").copied(),
Some(2),
"tenancy holds k2 (overwritten) and k3",
);
}
#[test]
fn leaf_counts_by_layer_partition_count_law() {
let a = Fixed(
"A",
dict(&[(
"outer",
Value::from(dict(&[
("keep", Value::from("k")),
("change", Value::from(1i64)),
])),
)]),
);
let b = Fixed(
"B",
dict(&[
("outer", Value::from(dict(&[("change", Value::from(9i64))]))),
("array", Value::from(vec![Value::from(0i64)])),
]),
);
let out = compose_with_provenance(&[&a, &b]);
let counts = out.attribution.leaf_counts_by_layer();
let sum: usize = counts.values().sum();
assert_eq!(sum, out.attribution.len());
}
#[test]
fn leaf_counts_by_layer_agrees_with_writes_by_layer_sizes() {
let a = Fixed("Z", dict(&[("z", Value::from(1i64))]));
let b = Fixed(
"A",
dict(&[
("a", Value::from(dict(&[("y", Value::from(2i64))]))),
("m", Value::from(3i64)),
]),
);
let c = Fixed("M", dict(&[("q", Value::from(4i64))]));
let out = compose_with_provenance(&[&a, &b, &c]);
let counts = out.attribution.leaf_counts_by_layer();
let groups = out.attribution.writes_by_layer();
let counts_keys: Vec<&&'static str> = counts.keys().collect();
let groups_keys: Vec<&&'static str> = groups.keys().collect();
assert_eq!(
counts_keys, groups_keys,
"compact and wide seams share the outer key set verbatim",
);
for (layer, paths) in &groups {
assert_eq!(
counts.get(layer).copied(),
Some(paths.len()),
"leaf_counts_by_layer[{layer}] == writes_by_layer[{layer}].len()",
);
}
}
#[test]
fn leaf_counts_by_layer_empty_when_no_layers() {
let out = compose_with_provenance(&[]);
assert!(
out.attribution.leaf_counts_by_layer().is_empty(),
"no layers ⇒ no counters",
);
}
#[test]
fn leaf_counts_by_layer_empty_layer_drops_out_of_counters() {
let real = Fixed("real", dict(&[("k", Value::from(1i64))]));
let empty = Fixed("undetectable", Dict::new());
let out = compose_with_provenance(&[&real, &empty]);
let counts = out.attribution.leaf_counts_by_layer();
assert_eq!(counts.len(), 1);
assert_eq!(counts.get("real").copied(), Some(1));
assert!(
!counts.contains_key("undetectable"),
"an empty-dict layer contributes no leaves, so no counter",
);
}
#[test]
fn leaf_counts_by_layer_reflects_dict_over_scalar_reshape() {
let a = Fixed("first", dict(&[("x", Value::from(1i64))]));
let b = Fixed(
"second",
dict(&[("x", Value::from(dict(&[("y", Value::from(2i64))])))]),
);
let out = compose_with_provenance(&[&a, &b]);
let counts = out.attribution.leaf_counts_by_layer();
assert_eq!(counts.get("second").copied(), Some(1));
assert!(
!counts.contains_key("first"),
"purged scalar attribution drops A from the counters",
);
assert_eq!(counts.len(), 1);
}
#[test]
fn compose_with_provenance_dict_matches_compose_projection_across_shape_transitions() {
let a = Fixed(
"A",
dict(&[
("scalar", Value::from(1i64)),
(
"nested",
Value::from(dict(&[
("keep", Value::from("k")),
("change", Value::from("A")),
])),
),
]),
);
let b = Fixed(
"B",
dict(&[
("nested", Value::from(dict(&[("change", Value::from("B"))]))),
("array", Value::from(vec![Value::from(1i64)])),
("scalar", Value::from(dict(&[("inner", Value::from(2i64))]))),
]),
);
let c = Fixed(
"C",
dict(&[
("array", Value::from(vec![Value::from(9i64)])),
("scalar", Value::from(99i64)),
]),
);
let out = compose_with_provenance(&[&a, &b, &c]);
assert_eq!(
out.dict,
compose(&[&a, &b, &c]),
"dict projection equals plain compose across shape transitions"
);
assert_eq!(out.attribution.layer_of(&["nested", "keep"]), Some("A"));
assert_eq!(out.attribution.layer_of(&["nested", "change"]), Some("B"));
assert_eq!(out.attribution.layer_of(&["array"]), Some("C"));
assert_eq!(out.attribution.layer_of(&["scalar"]), Some("C"));
assert_eq!(out.attribution.layer_of(&["scalar", "inner"]), None);
}
fn s(x: &str) -> String {
x.to_owned()
}
fn subtree_fixture() -> DiscoveryComposition {
let coarse = Fixed(
"coarse",
dict(&[
(
"breathe",
Value::from(dict(&[
("mode", Value::from("live")),
("setpoint", Value::from(0.80)),
])),
),
("alpha", Value::from(1i64)),
]),
);
let specific = Fixed(
"specific",
dict(&[
(
"breathe",
Value::from(dict(&[("setpoint", Value::from(0.70))])),
),
("breatheZ", Value::from(9i64)),
]),
);
compose_with_provenance(&[&coarse, &specific])
}
#[test]
fn subtree_iter_at_root_prefix_matches_iter() {
let out = subtree_fixture();
let full: Vec<(Vec<String>, &'static str)> = out
.attribution
.subtree_iter(&[])
.map(|(p, l)| (p.to_vec(), l))
.collect();
let via_iter: Vec<(Vec<String>, &'static str)> = out
.attribution
.iter()
.map(|(p, l)| (p.to_vec(), l))
.collect();
assert_eq!(full, via_iter, "empty prefix ⇒ full iter, same order");
assert_eq!(
out.attribution.subtree(&[]).len(),
out.attribution.len(),
"subtree(&[]) equals self on the len() axis",
);
}
#[test]
fn subtree_iter_at_named_prefix_yields_only_that_subtree_in_lex_order() {
let out = subtree_fixture();
let prefix = vec![s("breathe")];
let observed: Vec<(Vec<String>, &'static str)> = out
.attribution
.subtree_iter(&prefix)
.map(|(p, l)| (p.to_vec(), l))
.collect();
assert_eq!(
observed,
vec![
(vec![s("breathe"), s("mode")], "coarse"),
(vec![s("breathe"), s("setpoint")], "specific"),
],
"subtree yields only breathe.* leaves in lex order",
);
}
#[test]
fn subtree_iter_stops_at_prefix_extending_sibling_key() {
let out = subtree_fixture();
let prefix = vec![s("breathe")];
let observed: Vec<Vec<String>> = out
.attribution
.subtree_iter(&prefix)
.map(|(p, _)| p.to_vec())
.collect();
assert!(
!observed.contains(&vec![s("breatheZ")]),
"prefix-extending sibling `breatheZ` is NOT a descendant of `breathe`",
);
assert_eq!(
observed.len(),
2,
"only the two `breathe.*` leaves are yielded, not `breatheZ`",
);
assert_eq!(
out.attribution.layer_of(&["breatheZ"]),
Some("specific"),
"the excluded sibling is still attributed in the parent",
);
}
#[test]
fn subtree_iter_empty_when_prefix_names_no_subtree() {
let out = subtree_fixture();
assert_eq!(
out.attribution.subtree_iter(&[s("nonexistent")]).count(),
0,
"absent prefix ⇒ empty iterator",
);
assert!(
out.attribution.subtree(&[s("nonexistent")]).is_empty(),
"absent prefix ⇒ empty projection",
);
}
#[test]
fn subtree_iter_at_exact_leaf_yields_that_leaf_only() {
let out = subtree_fixture();
let prefix = vec![s("alpha")];
let observed: Vec<(Vec<String>, &'static str)> = out
.attribution
.subtree_iter(&prefix)
.map(|(p, l)| (p.to_vec(), l))
.collect();
assert_eq!(observed, vec![(vec![s("alpha")], "coarse")]);
}
#[test]
fn subtree_agrees_with_subtree_iter_pointwise() {
let out = subtree_fixture();
let prefix = vec![s("breathe")];
let sub = out.attribution.subtree(&prefix);
let via_projection: Vec<(Vec<String>, &'static str)> =
sub.iter().map(|(p, l)| (p.to_vec(), l)).collect();
let via_iter: Vec<(Vec<String>, &'static str)> = out
.attribution
.subtree_iter(&prefix)
.map(|(p, l)| (p.to_vec(), l))
.collect();
assert_eq!(via_projection, via_iter);
assert_eq!(sub.len(), 2);
for (path, layer) in &via_iter {
assert_eq!(sub.layer_of_owned(path), Some(*layer));
assert_eq!(out.attribution.layer_of_owned(path), Some(*layer));
}
}
#[test]
fn subtree_writes_by_layer_is_subset_of_parent() {
let out = subtree_fixture();
let prefix = vec![s("breathe")];
let sub = out.attribution.subtree(&prefix);
let sub_groups = sub.writes_by_layer();
let parent_groups = out.attribution.writes_by_layer();
for (layer, sub_paths) in &sub_groups {
let parent_paths = parent_groups
.get(layer)
.expect("every subtree layer appears in the parent");
for path in sub_paths {
assert!(
parent_paths.contains(path),
"sub-bucket paths are a subset of parent-bucket paths",
);
}
}
assert!(sub_groups.contains_key("coarse"));
assert!(sub_groups.contains_key("specific"));
}
#[test]
fn subtree_leaf_counts_by_layer_composes_at_sub_altitude() {
let out = subtree_fixture();
let prefix = vec![s("breathe")];
let sub_counts = out.attribution.subtree(&prefix).leaf_counts_by_layer();
assert_eq!(sub_counts.get("coarse").copied(), Some(1));
assert_eq!(sub_counts.get("specific").copied(), Some(1));
assert_eq!(sub_counts.len(), 2);
let parent_counts = out.attribution.leaf_counts_by_layer();
for (layer, sub_count) in &sub_counts {
let parent_count = parent_counts
.get(layer)
.copied()
.expect("every subtree layer appears in the parent");
assert!(
*sub_count <= parent_count,
"sub-count for {layer} ({sub_count}) must not exceed parent count ({parent_count})",
);
}
}
#[test]
fn subtree_iter_reflects_dict_over_scalar_reshape() {
let a = Fixed("first", dict(&[("x", Value::from(1i64))]));
let b = Fixed(
"second",
dict(&[("x", Value::from(dict(&[("y", Value::from(2i64))])))]),
);
let out = compose_with_provenance(&[&a, &b]);
let observed: Vec<(Vec<String>, &'static str)> = out
.attribution
.subtree_iter(&[s("x")])
.map(|(p, l)| (p.to_vec(), l))
.collect();
assert_eq!(observed, vec![(vec![s("x"), s("y")], "second")]);
}
#[test]
fn subtree_surviving_layer_names_empty_prefix_equals_surviving_layer_names() {
let out = subtree_fixture();
assert_eq!(
out.attribution.subtree_surviving_layer_names(&[]),
out.attribution.surviving_layer_names(),
"empty prefix ⇒ same lex name-set as the top-level projection",
);
}
#[test]
fn subtree_surviving_layer_names_at_named_prefix_lists_writers_under_it() {
let out = subtree_fixture();
let prefix = vec![s("breathe")];
assert_eq!(
out.attribution.subtree_surviving_layer_names(&prefix),
vec!["coarse", "specific"],
);
}
#[test]
fn subtree_surviving_layer_names_agrees_with_subtree_surviving_layer_names() {
let out = subtree_fixture();
for prefix in [
vec![],
vec![s("breathe")],
vec![s("alpha")],
vec![s("nonexistent")],
] {
assert_eq!(
out.attribution.subtree_surviving_layer_names(&prefix),
out.attribution.subtree(&prefix).surviving_layer_names(),
"direct seam agrees with the subtree-then-surviving composition at {prefix:?}",
);
}
}
#[test]
fn subtree_surviving_layer_names_absent_prefix_is_empty() {
let out = subtree_fixture();
assert!(
out.attribution
.subtree_surviving_layer_names(&[s("nonexistent")])
.is_empty(),
"absent prefix ⇒ empty name-set",
);
}
#[test]
fn subtree_surviving_layer_names_at_exact_scalar_leaf_lists_only_its_writer() {
let out = subtree_fixture();
let prefix = vec![s("alpha")];
assert_eq!(
out.attribution.subtree_surviving_layer_names(&prefix),
vec!["coarse"],
);
}
#[test]
fn subtree_surviving_layer_names_stops_at_prefix_extending_sibling_key() {
let coarse = Fixed(
"coarse",
dict(&[(
"breathe",
Value::from(dict(&[("mode", Value::from("live"))])),
)]),
);
let specific_only_sibling = Fixed("specific", dict(&[("breatheZ", Value::from(9i64))]));
let out = compose_with_provenance(&[&coarse, &specific_only_sibling]);
let prefix = vec![s("breathe")];
assert_eq!(
out.attribution.subtree_surviving_layer_names(&prefix),
vec!["coarse"],
"the prefix-extending sibling's writer is NOT credited against the subtree",
);
assert_eq!(
out.attribution.surviving_layer_names(),
vec!["coarse", "specific"],
);
}
#[test]
fn subtree_surviving_layer_names_deduplicates_multi_write_writer() {
let only = Fixed(
"only",
dict(&[(
"svc",
Value::from(dict(&[
("a", Value::from(1i64)),
("b", Value::from(2i64)),
("c", Value::from(3i64)),
])),
)]),
);
let out = compose_with_provenance(&[&only]);
let prefix = vec![s("svc")];
assert_eq!(
out.attribution.subtree_surviving_layer_names(&prefix),
vec!["only"],
);
}
#[test]
fn subtree_surviving_layer_names_returns_lex_order_on_layer_name() {
let z_layer = Fixed(
"Z",
dict(&[("svc", Value::from(dict(&[("k1", Value::from(1i64))])))]),
);
let a_layer = Fixed(
"A",
dict(&[("svc", Value::from(dict(&[("k2", Value::from(2i64))])))]),
);
let out = compose_with_provenance(&[&z_layer, &a_layer]);
let prefix = vec![s("svc")];
assert_eq!(
out.attribution.subtree_surviving_layer_names(&prefix),
vec!["A", "Z"],
"lex order, not application order",
);
}
#[test]
fn subtree_surviving_layer_names_subset_of_surviving_layer_names() {
let out = subtree_fixture();
let prefix = vec![s("alpha")];
let sub_set: std::collections::BTreeSet<_> = out
.attribution
.subtree_surviving_layer_names(&prefix)
.into_iter()
.collect();
let top_set: std::collections::BTreeSet<_> = out
.attribution
.surviving_layer_names()
.into_iter()
.collect();
assert!(sub_set.is_subset(&top_set), "sub ⊆ top on every prefix");
assert!(
sub_set.len() < top_set.len(),
"the `alpha`-only subtree drops `specific` — strict subset",
);
assert!(
!sub_set.contains("specific"),
"specific has no leaf under alpha"
);
}
#[test]
fn subtree_surviving_layer_names_empty_when_no_leaves() {
let empty = compose_with_provenance(&[]);
assert!(
empty
.attribution
.subtree_surviving_layer_names(&[])
.is_empty()
);
assert!(
empty
.attribution
.subtree_surviving_layer_names(&[s("any")])
.is_empty(),
);
}
#[test]
fn contributor_names_filters_empty_layers() {
let a = Fixed("platform", dict(&[("k", Value::from(1i64))]));
let b = Fixed("undetectable", Dict::new());
let c = Fixed("tenancy", dict(&[("k", Value::from(2i64))]));
assert_eq!(
contributor_names(&[&a, &b, &c]),
vec!["platform", "tenancy"]
);
}
#[test]
fn contributor_names_preserves_application_order() {
let a = Fixed("tenancy", dict(&[("k", Value::from(1i64))]));
let b = Fixed("platform", dict(&[("k", Value::from(2i64))]));
assert_eq!(contributor_names(&[&a, &b]), vec!["tenancy", "platform"]);
}
#[test]
fn contributor_names_empty_when_all_layers_undetectable() {
let a = Fixed("a", Dict::new());
let b = Fixed("b", Dict::new());
assert!(contributor_names(&[&a, &b]).is_empty());
}
#[test]
fn contributor_names_empty_when_no_layers() {
assert!(contributor_names(&[]).is_empty());
}
#[test]
fn contributor_names_is_subset_of_layer_names() {
let a = Fixed("a", dict(&[("k", Value::from(1i64))]));
let b = Fixed("b", Dict::new());
let c = Fixed("c", dict(&[("k", Value::from(2i64))]));
let all: std::collections::BTreeSet<_> = layer_names(&[&a, &b, &c]).into_iter().collect();
let contributors: std::collections::BTreeSet<_> =
contributor_names(&[&a, &b, &c]).into_iter().collect();
assert!(
contributors.is_subset(&all),
"contributors ⊆ declared names"
);
assert_eq!(
contributors.len(),
2,
"the empty middle layer is filtered out"
);
}
#[test]
fn contributor_names_emptiness_matches_composed_emptiness() {
let a_empty = Fixed("a", Dict::new());
let b_empty = Fixed("b", Dict::new());
let empty_stack: [&dyn DiscoveryLayer; 2] = [&a_empty, &b_empty];
assert!(contributor_names(&empty_stack).is_empty());
assert!(compose(&empty_stack).is_empty());
let a = Fixed("a", dict(&[("x", Value::from(1i64))]));
let b = Fixed("b", Dict::new());
let c = Fixed("c", dict(&[("y", Value::from(2i64))]));
let stack: [&dyn DiscoveryLayer; 3] = [&a, &b, &c];
assert!(!contributor_names(&stack).is_empty());
assert!(!compose(&stack).is_empty());
}
#[test]
fn contributor_names_counts_overridden_writers_too() {
let coarse = Fixed("platform", dict(&[("setpoint", Value::from(0.80))]));
let specific = Fixed("tenancy", dict(&[("setpoint", Value::from(0.70))]));
assert_eq!(
contributor_names(&[&coarse, &specific]),
vec!["platform", "tenancy"],
"both writers show up even when specific wholly overrides coarse",
);
assert_eq!(
compose(&[&coarse, &specific]).get("setpoint"),
Some(&Value::from(0.70)),
);
}
#[test]
fn nonempty_layer_dicts_filters_empty_layers_and_carries_the_dicts() {
let a_dict = dict(&[("k", Value::from(1i64)), ("side", Value::from("A"))]);
let c_dict = dict(&[("k", Value::from(2i64))]);
let a = Fixed("platform", a_dict.clone());
let b = Fixed("undetectable", Dict::new());
let c = Fixed("tenancy", c_dict.clone());
assert_eq!(
nonempty_layer_dicts(&[&a, &b, &c]),
vec![("platform", a_dict), ("tenancy", c_dict)],
);
}
#[test]
fn nonempty_layer_dicts_preserves_application_order() {
let a = Fixed("tenancy", dict(&[("k", Value::from(1i64))]));
let b = Fixed("platform", dict(&[("k", Value::from(2i64))]));
let names: Vec<&'static str> = nonempty_layer_dicts(&[&a, &b])
.iter()
.map(|(n, _)| *n)
.collect();
assert_eq!(names, vec!["tenancy", "platform"]);
}
#[test]
fn nonempty_layer_dicts_empty_when_no_layers() {
assert!(nonempty_layer_dicts(&[]).is_empty());
}
#[test]
fn nonempty_layer_dicts_empty_when_all_layers_undetectable() {
let a = Fixed("a", Dict::new());
let b = Fixed("b", Dict::new());
assert!(nonempty_layer_dicts(&[&a, &b]).is_empty());
}
#[test]
fn nonempty_layer_dicts_projects_to_contributor_names() {
let a = Fixed("platform", dict(&[("k", Value::from(1i64))]));
let b = Fixed("undetectable", Dict::new());
let c = Fixed("tenancy", dict(&[("k", Value::from(2i64))]));
let layers: [&dyn DiscoveryLayer; 3] = [&a, &b, &c];
let derived: Vec<&'static str> = nonempty_layer_dicts(&layers)
.into_iter()
.map(|(n, _)| n)
.collect();
assert_eq!(derived, contributor_names(&layers));
}
#[test]
fn nonempty_layer_dicts_projects_to_compose_via_deep_merge() {
let coarse = Fixed(
"platform",
dict(&[
("setpoint", Value::from(0.80)),
("floor", Value::from("256Mi")),
]),
);
let mid = Fixed("undetectable", Dict::new());
let specific = Fixed("tenancy", dict(&[("setpoint", Value::from(0.70))]));
let layers: [&dyn DiscoveryLayer; 3] = [&coarse, &mid, &specific];
let mut derived = Dict::new();
for (_, d) in nonempty_layer_dicts(&layers) {
deep_merge(&mut derived, d);
}
assert_eq!(derived, compose(&layers), "fold(deep_merge) == compose");
assert_eq!(derived.get("setpoint"), Some(&Value::from(0.70)));
assert_eq!(derived.get("floor"), Some(&Value::from("256Mi")));
}
#[test]
fn nonempty_layer_dicts_length_equals_contributor_names_length() {
let a = Fixed("a", dict(&[("k", Value::from(1i64))]));
let b = Fixed("b", Dict::new());
let c = Fixed("c", dict(&[("k", Value::from(2i64))]));
let layers: [&dyn DiscoveryLayer; 3] = [&a, &b, &c];
assert_eq!(
nonempty_layer_dicts(&layers).len(),
contributor_names(&layers).len()
);
}
#[test]
fn nonempty_layer_dicts_carries_overridden_writers_dicts_unchanged() {
let coarse_dict = dict(&[("setpoint", Value::from(0.80))]);
let specific_dict = dict(&[("setpoint", Value::from(0.70))]);
let coarse = Fixed("platform", coarse_dict.clone());
let specific = Fixed("tenancy", specific_dict.clone());
assert_eq!(
nonempty_layer_dicts(&[&coarse, &specific]),
vec![("platform", coarse_dict), ("tenancy", specific_dict)],
);
}
#[test]
fn surviving_layer_names_lists_layers_with_live_leaves() {
let a = Fixed(
"platform",
dict(&[("k1", Value::from(1i64)), ("k2", Value::from(2i64))]),
);
let b = Fixed(
"tenancy",
dict(&[("k2", Value::from(20i64)), ("k3", Value::from(3i64))]),
);
let out = compose_with_provenance(&[&a, &b]);
assert_eq!(
out.attribution.surviving_layer_names(),
vec!["platform", "tenancy"],
"both writers survive; result sorted lex on layer name",
);
}
#[test]
fn surviving_layer_names_lex_order_regardless_of_application_order() {
let a = Fixed("Z", dict(&[("z", Value::from(1i64))]));
let b = Fixed(
"A",
dict(&[
("a", Value::from(dict(&[("y", Value::from(2i64))]))),
("m", Value::from(3i64)),
]),
);
let out = compose_with_provenance(&[&a, &b]);
assert_eq!(
out.attribution.surviving_layer_names(),
vec!["A", "Z"],
"lex order, not application order",
);
}
#[test]
fn surviving_layer_names_drops_wholly_overridden_writer() {
let coarse = Fixed("coarse", dict(&[("setpoint", Value::from(0.80))]));
let specific = Fixed("specific", dict(&[("setpoint", Value::from(0.70))]));
let out = compose_with_provenance(&[&coarse, &specific]);
assert_eq!(
out.attribution.surviving_layer_names(),
vec!["specific"],
"wholly-overridden writer drops off the surviving axis",
);
assert_eq!(
contributor_names(&[&coarse, &specific]),
vec!["coarse", "specific"],
"pre-merge contributor_names still lists the overridden writer",
);
}
#[test]
fn surviving_layer_names_drops_writer_purged_by_dict_over_scalar() {
let a = Fixed("first", dict(&[("x", Value::from(1i64))]));
let b = Fixed(
"second",
dict(&[("x", Value::from(dict(&[("y", Value::from(2i64))])))]),
);
let out = compose_with_provenance(&[&a, &b]);
assert_eq!(
out.attribution.surviving_layer_names(),
vec!["second"],
"dict-over-scalar reshape purges A's only leaf",
);
}
#[test]
fn surviving_layer_names_empty_when_no_leaves() {
let empty = compose_with_provenance(&[]);
assert!(empty.attribution.surviving_layer_names().is_empty());
let a_empty = Fixed("a", Dict::new());
let b_empty = Fixed("b", Dict::new());
let out = compose_with_provenance(&[&a_empty, &b_empty]);
assert!(
out.attribution.surviving_layer_names().is_empty(),
"empty-only stack ⇒ no surviving writers",
);
}
#[test]
fn surviving_layer_names_agrees_with_writes_by_layer_keys() {
let a = Fixed("Z", dict(&[("z", Value::from(1i64))]));
let b = Fixed(
"A",
dict(&[
("a", Value::from(dict(&[("y", Value::from(2i64))]))),
("m", Value::from(3i64)),
]),
);
let c = Fixed("M", dict(&[("q", Value::from(4i64))]));
let out = compose_with_provenance(&[&a, &b, &c]);
let via_wide: Vec<&'static str> = out.attribution.writes_by_layer().into_keys().collect();
assert_eq!(
out.attribution.surviving_layer_names(),
via_wide,
"compact and wide seams share the outer key set verbatim",
);
assert_eq!(
out.attribution.surviving_layer_names().len(),
out.attribution.writes_by_layer().len(),
);
}
#[test]
fn surviving_layer_names_agrees_with_leaf_counts_by_layer_keys() {
let a = Fixed(
"platform",
dict(&[("k1", Value::from(1i64)), ("k2", Value::from(2i64))]),
);
let b = Fixed(
"tenancy",
dict(&[("k2", Value::from(20i64)), ("k3", Value::from(3i64))]),
);
let out = compose_with_provenance(&[&a, &b]);
let via_counts: Vec<&'static str> =
out.attribution.leaf_counts_by_layer().into_keys().collect();
assert_eq!(
out.attribution.surviving_layer_names(),
via_counts,
"compact and count seams share the outer key set verbatim",
);
assert_eq!(
out.attribution.surviving_layer_names().len(),
out.attribution.leaf_counts_by_layer().len(),
);
}
#[test]
fn surviving_layer_names_subset_of_contributor_names() {
let coarse = Fixed("coarse", dict(&[("setpoint", Value::from(0.80))]));
let specific = Fixed("specific", dict(&[("setpoint", Value::from(0.70))]));
let empty = Fixed("undetectable", Dict::new());
let layers: [&dyn DiscoveryLayer; 3] = [&coarse, &specific, &empty];
let all: std::collections::BTreeSet<_> = layer_names(&layers).into_iter().collect();
let contribs: std::collections::BTreeSet<_> =
contributor_names(&layers).into_iter().collect();
let survivors: std::collections::BTreeSet<_> = compose_with_provenance(&layers)
.attribution
.surviving_layer_names()
.into_iter()
.collect();
assert!(survivors.is_subset(&contribs), "survivors ⊆ contributors");
assert!(contribs.is_subset(&all), "contributors ⊆ declared names");
assert!(
survivors.len() < contribs.len(),
"coarse wholly overridden ⇒ strict subset on this fixture",
);
assert!(
contribs.len() < all.len(),
"the undetectable layer is filtered from contributors but not from declared names",
);
}
#[test]
fn surviving_layer_names_coincides_with_contributor_names_when_no_writer_overridden() {
let a = Fixed("A", dict(&[("k1", Value::from(1i64))]));
let b = Fixed("B", dict(&[("k2", Value::from(2i64))]));
let c = Fixed("C", dict(&[("k3", Value::from(3i64))]));
let layers: [&dyn DiscoveryLayer; 3] = [&a, &b, &c];
let contribs: std::collections::BTreeSet<_> =
contributor_names(&layers).into_iter().collect();
let survivors: std::collections::BTreeSet<_> = compose_with_provenance(&layers)
.attribution
.surviving_layer_names()
.into_iter()
.collect();
assert_eq!(
survivors, contribs,
"no writer overridden ⇒ survivors and contributors agree as sets",
);
}
#[test]
fn silent_layer_names_lists_axes_that_returned_empty_dicts() {
let a = Fixed("platform", dict(&[("k", Value::from(1i64))]));
let b = Fixed("undetectable", Dict::new());
let c = Fixed("also-empty", Dict::new());
assert_eq!(
silent_layer_names(&[&a, &b, &c]),
vec!["undetectable", "also-empty"],
);
}
#[test]
fn silent_layer_names_preserves_application_order() {
let a = Fixed("tenancy", Dict::new());
let b = Fixed("platform", Dict::new());
assert_eq!(silent_layer_names(&[&a, &b]), vec!["tenancy", "platform"]);
}
#[test]
fn silent_layer_names_empty_when_every_layer_contributes() {
let a = Fixed("a", dict(&[("k", Value::from(1i64))]));
let b = Fixed("b", dict(&[("k", Value::from(2i64))]));
assert!(silent_layer_names(&[&a, &b]).is_empty());
}
#[test]
fn silent_layer_names_empty_when_no_layers() {
assert!(silent_layer_names(&[]).is_empty());
}
#[test]
fn silent_layer_names_covers_layer_names_when_all_undetectable() {
let a = Fixed("a", Dict::new());
let b = Fixed("b", Dict::new());
let layers: [&dyn DiscoveryLayer; 2] = [&a, &b];
assert_eq!(silent_layer_names(&layers), layer_names(&layers));
}
#[test]
fn silent_layer_names_is_subset_of_layer_names() {
let a = Fixed("a", dict(&[("k", Value::from(1i64))]));
let b = Fixed("b", Dict::new());
let c = Fixed("c", Dict::new());
let all: std::collections::BTreeSet<_> = layer_names(&[&a, &b, &c]).into_iter().collect();
let silent: std::collections::BTreeSet<_> =
silent_layer_names(&[&a, &b, &c]).into_iter().collect();
assert!(silent.is_subset(&all), "silent ⊆ declared names");
assert_eq!(silent.len(), 2, "two undetectable axes");
}
#[test]
fn silent_layer_names_disjoint_from_contributor_names() {
let a = Fixed("a", dict(&[("k", Value::from(1i64))]));
let b = Fixed("b", Dict::new());
let c = Fixed("c", dict(&[("k", Value::from(2i64))]));
let d = Fixed("d", Dict::new());
let layers: [&dyn DiscoveryLayer; 4] = [&a, &b, &c, &d];
let contribs: std::collections::BTreeSet<_> =
contributor_names(&layers).into_iter().collect();
let silent: std::collections::BTreeSet<_> =
silent_layer_names(&layers).into_iter().collect();
assert!(
contribs.is_disjoint(&silent),
"contributor and silent projections share no elements",
);
}
#[test]
fn silent_layer_names_partitions_layer_names_disjointly() {
let a = Fixed("platform", dict(&[("k", Value::from(1i64))]));
let b = Fixed("undetectable", Dict::new());
let c = Fixed("tenancy", dict(&[("k", Value::from(2i64))]));
let d = Fixed("also-empty", Dict::new());
let layers: [&dyn DiscoveryLayer; 4] = [&a, &b, &c, &d];
let all: std::collections::BTreeSet<_> = layer_names(&layers).into_iter().collect();
let contribs: std::collections::BTreeSet<_> =
contributor_names(&layers).into_iter().collect();
let silent: std::collections::BTreeSet<_> =
silent_layer_names(&layers).into_iter().collect();
let union: std::collections::BTreeSet<_> = contribs.union(&silent).copied().collect();
assert_eq!(union, all, "contributors ∪ silent == declared names");
assert!(contribs.is_disjoint(&silent), "contributors ∩ silent == ∅",);
assert_eq!(
contribs.len() + silent.len(),
layer_names(&layers).len(),
"distinct names ⇒ length sum matches",
);
}
#[test]
fn silent_layer_names_agrees_with_layer_names_minus_contributor_names() {
let a = Fixed("z-first", dict(&[("k", Value::from(1i64))]));
let b = Fixed("m-empty", Dict::new());
let c = Fixed("a-third", dict(&[("k", Value::from(2i64))]));
let d = Fixed("q-empty", Dict::new());
let layers: [&dyn DiscoveryLayer; 4] = [&a, &b, &c, &d];
let all: std::collections::BTreeSet<_> = layer_names(&layers).into_iter().collect();
let contribs: std::collections::BTreeSet<_> =
contributor_names(&layers).into_iter().collect();
let silent: std::collections::BTreeSet<_> =
silent_layer_names(&layers).into_iter().collect();
let derived: std::collections::BTreeSet<_> = all.difference(&contribs).copied().collect();
assert_eq!(silent, derived, "silent == layer_names − contributors");
}
#[test]
fn silent_layer_names_disjoint_from_surviving_layer_names() {
let coarse = Fixed("coarse", dict(&[("setpoint", Value::from(0.80))]));
let specific = Fixed("specific", dict(&[("setpoint", Value::from(0.70))]));
let empty = Fixed("undetectable", Dict::new());
let layers: [&dyn DiscoveryLayer; 3] = [&coarse, &specific, &empty];
let silent: std::collections::BTreeSet<_> =
silent_layer_names(&layers).into_iter().collect();
let survivors: std::collections::BTreeSet<_> = compose_with_provenance(&layers)
.attribution
.surviving_layer_names()
.into_iter()
.collect();
assert!(
silent.is_disjoint(&survivors),
"silent axes cannot survive the merge (they wrote nothing)",
);
assert_eq!(silent, std::collections::BTreeSet::from(["undetectable"]));
assert_eq!(survivors, std::collections::BTreeSet::from(["specific"]));
}
#[test]
fn subtree_leaf_counts_by_layer_empty_prefix_equals_leaf_counts_by_layer() {
let out = subtree_fixture();
assert_eq!(
out.attribution.subtree_leaf_counts_by_layer(&[]),
out.attribution.leaf_counts_by_layer(),
);
}
#[test]
fn subtree_leaf_counts_by_layer_at_named_prefix_counts_only_leaves_under_it() {
let out = subtree_fixture();
let prefix = vec![s("breathe")];
let counts = out.attribution.subtree_leaf_counts_by_layer(&prefix);
assert_eq!(counts.get("coarse").copied(), Some(1));
assert_eq!(counts.get("specific").copied(), Some(1));
assert_eq!(counts.len(), 2);
}
#[test]
fn subtree_leaf_counts_by_layer_agrees_with_subtree_leaf_counts_by_layer() {
let out = subtree_fixture();
for prefix in [
vec![],
vec![s("breathe")],
vec![s("alpha")],
vec![s("nonexistent")],
] {
assert_eq!(
out.attribution.subtree_leaf_counts_by_layer(&prefix),
out.attribution.subtree(&prefix).leaf_counts_by_layer(),
"direct vs composition must agree at prefix {prefix:?}",
);
}
}
#[test]
fn subtree_leaf_counts_by_layer_absent_prefix_is_empty() {
let out = subtree_fixture();
assert!(
out.attribution
.subtree_leaf_counts_by_layer(&[s("nonexistent")])
.is_empty(),
);
}
#[test]
fn subtree_leaf_counts_by_layer_at_exact_scalar_leaf_counts_one() {
let out = subtree_fixture();
let prefix = vec![s("alpha")];
let counts = out.attribution.subtree_leaf_counts_by_layer(&prefix);
assert_eq!(counts.get("coarse").copied(), Some(1));
assert_eq!(counts.len(), 1);
}
#[test]
fn subtree_leaf_counts_by_layer_stops_at_prefix_extending_sibling_key() {
let out = subtree_fixture();
let prefix = vec![s("breathe")];
let sub_counts = out.attribution.subtree_leaf_counts_by_layer(&prefix);
let parent_counts = out.attribution.leaf_counts_by_layer();
assert_eq!(sub_counts.get("specific").copied(), Some(1));
assert_eq!(parent_counts.get("specific").copied(), Some(2));
}
#[test]
fn subtree_leaf_counts_by_layer_partition_count_law() {
let out = subtree_fixture();
for prefix in [
vec![],
vec![s("breathe")],
vec![s("alpha")],
vec![s("nonexistent")],
] {
let counts = out.attribution.subtree_leaf_counts_by_layer(&prefix);
let sum: usize = counts.values().copied().sum();
let subtree_len = out.attribution.subtree(&prefix).len();
assert_eq!(
sum, subtree_len,
"partition-count law failed at prefix {prefix:?}",
);
assert_eq!(
sum,
out.attribution.subtree_iter(&prefix).count(),
"sum must equal subtree_iter count at prefix {prefix:?}",
);
}
}
#[test]
fn subtree_leaf_counts_by_layer_keys_equal_subtree_surviving_layer_names() {
let out = subtree_fixture();
for prefix in [
vec![],
vec![s("breathe")],
vec![s("alpha")],
vec![s("nonexistent")],
] {
let via_counts: Vec<&'static str> = out
.attribution
.subtree_leaf_counts_by_layer(&prefix)
.into_keys()
.collect();
let via_names = out.attribution.subtree_surviving_layer_names(&prefix);
assert_eq!(
via_counts, via_names,
"histogram key set must equal name-set at prefix {prefix:?}",
);
}
}
#[test]
fn subtree_leaf_counts_by_layer_is_leq_leaf_counts_by_layer_pointwise() {
let out = subtree_fixture();
let parent_counts = out.attribution.leaf_counts_by_layer();
for prefix in [
vec![],
vec![s("breathe")],
vec![s("alpha")],
vec![s("nonexistent")],
] {
let sub_counts = out.attribution.subtree_leaf_counts_by_layer(&prefix);
for (layer, sub_count) in &sub_counts {
let parent_count = parent_counts
.get(layer)
.copied()
.expect("every subtree layer appears in the parent");
assert!(
*sub_count <= parent_count,
"sub-count for {layer} at {prefix:?} ({sub_count}) must not exceed parent count ({parent_count})",
);
}
}
}
fn own_writes(
writes: BTreeMap<&'static str, Vec<&[String]>>,
) -> BTreeMap<&'static str, Vec<Vec<String>>> {
writes
.into_iter()
.map(|(layer, paths)| (layer, paths.into_iter().map(<[String]>::to_vec).collect()))
.collect()
}
#[test]
fn subtree_writes_by_layer_empty_prefix_equals_writes_by_layer() {
let out = subtree_fixture();
assert_eq!(
own_writes(out.attribution.subtree_writes_by_layer(&[])),
own_writes(out.attribution.writes_by_layer()),
);
}
#[test]
fn subtree_writes_by_layer_at_named_prefix_lists_paths_under_it() {
let out = subtree_fixture();
let prefix = vec![s("breathe")];
let writes = own_writes(out.attribution.subtree_writes_by_layer(&prefix));
assert_eq!(
writes.get("coarse"),
Some(&vec![vec![s("breathe"), s("mode")]]),
);
assert_eq!(
writes.get("specific"),
Some(&vec![vec![s("breathe"), s("setpoint")]]),
);
assert_eq!(writes.len(), 2);
}
#[test]
fn subtree_writes_by_layer_agrees_with_subtree_writes_by_layer_composition() {
let out = subtree_fixture();
for prefix in [
vec![],
vec![s("breathe")],
vec![s("alpha")],
vec![s("nonexistent")],
] {
let sub = out.attribution.subtree(&prefix);
assert_eq!(
own_writes(out.attribution.subtree_writes_by_layer(&prefix)),
own_writes(sub.writes_by_layer()),
"direct vs composition must agree at prefix {prefix:?}",
);
}
}
#[test]
fn subtree_writes_by_layer_absent_prefix_is_empty() {
let out = subtree_fixture();
assert!(
out.attribution
.subtree_writes_by_layer(&[s("nonexistent")])
.is_empty(),
);
}
#[test]
fn subtree_writes_by_layer_at_exact_scalar_leaf_yields_that_path_only() {
let out = subtree_fixture();
let prefix = vec![s("alpha")];
let writes = own_writes(out.attribution.subtree_writes_by_layer(&prefix));
assert_eq!(writes.get("coarse"), Some(&vec![vec![s("alpha")]]));
assert_eq!(writes.len(), 1);
}
#[test]
fn subtree_writes_by_layer_stops_at_prefix_extending_sibling_key() {
let out = subtree_fixture();
let prefix = vec![s("breathe")];
let sub_writes = own_writes(out.attribution.subtree_writes_by_layer(&prefix));
let parent_writes = own_writes(out.attribution.writes_by_layer());
assert_eq!(
sub_writes.get("specific"),
Some(&vec![vec![s("breathe"), s("setpoint")]]),
);
let parent_specific = parent_writes
.get("specific")
.expect("specific wrote at least one leaf globally");
assert!(
parent_specific.contains(&vec![s("breatheZ")]),
"the excluded sibling IS in the parent's bucket",
);
assert!(
!sub_writes
.get("specific")
.expect("specific wrote a leaf under the subtree")
.contains(&vec![s("breatheZ")]),
"the excluded sibling is NOT in the subtree's bucket",
);
}
#[test]
fn subtree_writes_by_layer_partition_law() {
let out = subtree_fixture();
for prefix in [
vec![],
vec![s("breathe")],
vec![s("alpha")],
vec![s("nonexistent")],
] {
let writes = own_writes(out.attribution.subtree_writes_by_layer(&prefix));
let sum: usize = writes.values().map(Vec::len).sum();
let subtree_len = out.attribution.subtree(&prefix).len();
assert_eq!(
sum, subtree_len,
"partition law failed at prefix {prefix:?}",
);
assert_eq!(
sum,
out.attribution.subtree_iter(&prefix).count(),
"sum must equal subtree_iter count at prefix {prefix:?}",
);
let mut union_paths: Vec<Vec<String>> =
writes.values().flat_map(|v| v.iter().cloned()).collect();
union_paths.sort();
let mut walk_paths: Vec<Vec<String>> = out
.attribution
.subtree_iter(&prefix)
.map(|(p, _)| p.to_vec())
.collect();
walk_paths.sort();
assert_eq!(
union_paths, walk_paths,
"union of inner Vecs must equal subtree_iter's path multiset at {prefix:?}",
);
}
}
#[test]
fn subtree_writes_by_layer_keys_and_bucket_lengths_agree_with_peers() {
let out = subtree_fixture();
for prefix in [
vec![],
vec![s("breathe")],
vec![s("alpha")],
vec![s("nonexistent")],
] {
let writes = own_writes(out.attribution.subtree_writes_by_layer(&prefix));
let via_keys: Vec<&'static str> = writes.keys().copied().collect();
let via_names = out.attribution.subtree_surviving_layer_names(&prefix);
assert_eq!(
via_keys, via_names,
"wide seam key set must equal name-set at prefix {prefix:?}",
);
let counts = out.attribution.subtree_leaf_counts_by_layer(&prefix);
for (layer, paths) in &writes {
assert_eq!(
counts.get(layer).copied(),
Some(paths.len()),
"wide-seam bucket len must equal count-seam counter for {layer} at {prefix:?}",
);
}
}
}
#[test]
fn subtree_writes_by_layer_is_subsequence_of_writes_by_layer_pointwise() {
let out = subtree_fixture();
let parent_writes = own_writes(out.attribution.writes_by_layer());
for prefix in [
vec![],
vec![s("breathe")],
vec![s("alpha")],
vec![s("nonexistent")],
] {
let sub_writes = own_writes(out.attribution.subtree_writes_by_layer(&prefix));
for (layer, sub_paths) in &sub_writes {
let parent_paths = parent_writes
.get(layer)
.expect("every subtree layer appears in the parent");
assert!(
sub_paths.len() <= parent_paths.len(),
"sub-bucket length for {layer} at {prefix:?} exceeds parent",
);
for path in sub_paths {
assert!(
parent_paths.contains(path),
"sub path {path:?} for {layer} at {prefix:?} missing from parent bucket",
);
assert_eq!(
out.attribution.layer_of_owned(path),
Some(*layer),
"sub-bucket path {path:?} must attribute to {layer} on the parent",
);
}
}
}
let specific_sub = own_writes(out.attribution.subtree_writes_by_layer(&[s("breathe")]))
.remove("specific")
.expect("specific wrote under `breathe`");
let specific_parent = own_writes(out.attribution.writes_by_layer())
.remove("specific")
.expect("specific wrote globally");
assert!(
specific_sub.len() < specific_parent.len(),
"strict subsequence pinned on `specific` under `breathe.*` (sub {} < parent {})",
specific_sub.len(),
specific_parent.len(),
);
}
fn layer_axis_fixture() -> DiscoveryComposition {
let a = Fixed(
"platform",
dict(&[("k1", Value::from(1i64)), ("k2", Value::from(2i64))]),
);
let b = Fixed(
"tenancy",
dict(&[("k2", Value::from(20i64)), ("k3", Value::from(3i64))]),
);
compose_with_provenance(&[&a, &b])
}
#[test]
fn writes_of_layer_agrees_with_writes_by_layer_bucket() {
let out = layer_axis_fixture();
let groups = out.attribution.writes_by_layer();
for layer in out.attribution.surviving_layer_names() {
let single: Vec<&[String]> = out.attribution.writes_of_layer(layer);
let bucket: Vec<&[String]> = groups.get(layer).cloned().unwrap_or_default();
assert_eq!(
single, bucket,
"single-layer wide seam equals writes_by_layer[{layer}] verbatim",
);
}
}
#[test]
fn writes_of_layer_preserves_lex_order() {
let a = Fixed(
"A",
dict(&[
("m", Value::from(3i64)),
("a", Value::from(dict(&[("y", Value::from(2i64))]))),
]),
);
let b = Fixed("Z", dict(&[("z", Value::from(1i64))]));
let out = compose_with_provenance(&[&a, &b]);
let a_paths = out.attribution.writes_of_layer("A");
assert_eq!(
a_paths,
vec![
["a".to_owned(), "y".to_owned()].as_slice(),
["m".to_owned()].as_slice(),
],
"single-layer wide seam preserves lex path order",
);
for path in &a_paths {
let owned: Vec<String> = path.iter().map(std::borrow::ToOwned::to_owned).collect();
assert_eq!(
out.attribution.layer_of_owned(&owned),
Some("A"),
"every path in writes_of_layer(A) attributes to A",
);
}
}
#[test]
fn writes_of_layer_missing_writer_is_empty() {
let real = Fixed("real", dict(&[("k", Value::from(1i64))]));
let silent = Fixed("undetectable", Dict::new());
let out = compose_with_provenance(&[&real, &silent]);
assert!(
out.attribution.writes_of_layer("undetectable").is_empty(),
"silent writer yields empty writes",
);
assert!(
out.attribution.writes_of_layer("never-declared").is_empty(),
"never-declared writer yields empty writes",
);
}
#[test]
fn writes_of_layer_empty_attribution_is_empty() {
let out = compose_with_provenance(&[]);
assert!(
out.attribution.writes_of_layer("anything").is_empty(),
"empty attribution yields empty writes for any writer",
);
}
#[test]
fn leaf_count_of_layer_agrees_with_leaf_counts_by_layer_bucket() {
let out = layer_axis_fixture();
let counts = out.attribution.leaf_counts_by_layer();
for layer in out.attribution.surviving_layer_names() {
let single = out.attribution.leaf_count_of_layer(layer);
let bucket = counts.get(layer).copied().unwrap_or(0);
assert_eq!(
single, bucket,
"single-layer count seam equals leaf_counts_by_layer[{layer}] verbatim",
);
}
}
#[test]
fn leaf_count_of_layer_agrees_with_writes_of_layer_len() {
let out = layer_axis_fixture();
for layer in out.attribution.surviving_layer_names() {
assert_eq!(
out.attribution.leaf_count_of_layer(layer),
out.attribution.writes_of_layer(layer).len(),
"leaf_count_of_layer({layer}) == writes_of_layer({layer}).len()",
);
}
}
#[test]
fn leaf_count_of_layer_partition_count_law() {
let out = layer_axis_fixture();
let survivors = out.attribution.surviving_layer_names();
let total: usize = survivors
.iter()
.map(|l| out.attribution.leaf_count_of_layer(l))
.sum();
assert_eq!(
total,
out.attribution.len(),
"sum of per-writer counts equals total leaf count",
);
}
#[test]
fn leaf_count_of_layer_missing_writer_is_zero() {
let real = Fixed("real", dict(&[("k", Value::from(1i64))]));
let silent = Fixed("undetectable", Dict::new());
let out = compose_with_provenance(&[&real, &silent]);
assert_eq!(
out.attribution.leaf_count_of_layer("undetectable"),
0,
"silent writer yields count zero",
);
assert_eq!(
out.attribution.leaf_count_of_layer("never-declared"),
0,
"never-declared writer yields count zero",
);
let empty = compose_with_provenance(&[]);
assert_eq!(
empty.attribution.leaf_count_of_layer("anything"),
0,
"empty attribution yields count zero for any writer",
);
}
#[test]
fn subtree_writes_of_layer_empty_prefix_equals_writes_of_layer() {
let out = layer_axis_fixture();
for layer in out.attribution.surviving_layer_names() {
assert_eq!(
out.attribution.subtree_writes_of_layer(&[], layer),
out.attribution.writes_of_layer(layer),
"empty prefix ⇒ subtree_writes_of_layer({layer}) equals writes_of_layer({layer})",
);
}
assert!(
out.attribution
.subtree_writes_of_layer(&[], "never-declared")
.is_empty(),
"empty prefix + never-declared writer ⇒ empty",
);
}
#[test]
fn subtree_writes_of_layer_agrees_with_subtree_writes_by_layer_bucket() {
let out = subtree_fixture();
for prefix in [
vec![],
vec![s("breathe")],
vec![s("alpha")],
vec![s("nonexistent")],
] {
let groups = out.attribution.subtree_writes_by_layer(&prefix);
for layer in out.attribution.subtree_surviving_layer_names(&prefix) {
let single: Vec<&[String]> =
out.attribution.subtree_writes_of_layer(&prefix, layer);
let bucket: Vec<&[String]> = groups.get(layer).cloned().unwrap_or_default();
assert_eq!(
single, bucket,
"single-writer seam at prefix {prefix:?} equals subtree_writes_by_layer[{layer}]",
);
}
}
}
#[test]
fn subtree_writes_of_layer_at_named_prefix_lists_only_this_writer_under_it() {
let out = subtree_fixture();
let prefix = vec![s("breathe")];
let coarse: Vec<Vec<String>> = out
.attribution
.subtree_writes_of_layer(&prefix, "coarse")
.into_iter()
.map(<[String]>::to_vec)
.collect();
assert_eq!(coarse, vec![vec![s("breathe"), s("mode")]]);
let specific: Vec<Vec<String>> = out
.attribution
.subtree_writes_of_layer(&prefix, "specific")
.into_iter()
.map(<[String]>::to_vec)
.collect();
assert_eq!(specific, vec![vec![s("breathe"), s("setpoint")]]);
}
#[test]
fn subtree_writes_of_layer_stops_at_prefix_extending_sibling_key() {
let out = subtree_fixture();
let prefix = vec![s("breathe")];
let sub: Vec<Vec<String>> = out
.attribution
.subtree_writes_of_layer(&prefix, "specific")
.into_iter()
.map(<[String]>::to_vec)
.collect();
assert!(
!sub.contains(&vec![s("breatheZ")]),
"prefix-extending sibling is excluded from the 2D-restricted seam",
);
let parent: Vec<Vec<String>> = out
.attribution
.writes_of_layer("specific")
.into_iter()
.map(<[String]>::to_vec)
.collect();
assert!(
parent.contains(&vec![s("breatheZ")]),
"the excluded sibling IS in the top-level layer-axis seam",
);
}
#[test]
fn subtree_writes_of_layer_preserves_lex_order() {
let a = Fixed(
"A",
dict(&[
(
"s",
Value::from(dict(&[
("m", Value::from(3i64)),
("a", Value::from(dict(&[("y", Value::from(2i64))]))),
])),
),
("t", Value::from(4i64)),
]),
);
let b = Fixed(
"B",
dict(&[("s", Value::from(dict(&[("p", Value::from(9i64))])))]),
);
let out = compose_with_provenance(&[&a, &b]);
let prefix = vec![s("s")];
let a_paths: Vec<Vec<String>> = out
.attribution
.subtree_writes_of_layer(&prefix, "A")
.into_iter()
.map(<[String]>::to_vec)
.collect();
assert_eq!(
a_paths,
vec![vec![s("s"), s("a"), s("y")], vec![s("s"), s("m")],],
"2D-restricted seam preserves lex path order under the subtree",
);
for path in &a_paths {
assert_eq!(
out.attribution.layer_of_owned(path),
Some("A"),
"every path attributes to A on the parent",
);
}
}
#[test]
fn subtree_writes_of_layer_absent_prefix_is_empty() {
let out = subtree_fixture();
for layer in ["coarse", "specific", "never-declared"] {
assert!(
out.attribution
.subtree_writes_of_layer(&[s("nonexistent")], layer)
.is_empty(),
"absent prefix ⇒ subtree_writes_of_layer({layer}) is empty",
);
}
}
#[test]
fn subtree_writes_of_layer_missing_writer_is_empty() {
let out = subtree_fixture();
let prefix = vec![s("breathe")];
assert!(
out.attribution
.subtree_writes_of_layer(&prefix, "never-declared")
.is_empty(),
);
let elsewhere = Fixed("elsewhere", dict(&[("outside", Value::from(1i64))]));
let under = Fixed(
"under",
dict(&[("root", Value::from(dict(&[("leaf", Value::from(2i64))])))]),
);
let out2 = compose_with_provenance(&[&elsewhere, &under]);
assert!(
out2.attribution
.subtree_writes_of_layer(&[s("root")], "elsewhere")
.is_empty(),
"writer active elsewhere but silent under the subtree ⇒ empty",
);
}
#[test]
fn subtree_leaf_count_of_layer_empty_prefix_equals_leaf_count_of_layer() {
let out = layer_axis_fixture();
for layer in out.attribution.surviving_layer_names() {
assert_eq!(
out.attribution.subtree_leaf_count_of_layer(&[], layer),
out.attribution.leaf_count_of_layer(layer),
"empty prefix ⇒ subtree_leaf_count_of_layer({layer}) equals leaf_count_of_layer({layer})",
);
}
assert_eq!(
out.attribution
.subtree_leaf_count_of_layer(&[], "never-declared"),
0,
"empty prefix + never-declared writer ⇒ zero",
);
}
#[test]
fn subtree_leaf_count_of_layer_agrees_with_subtree_writes_of_layer_len() {
let out = subtree_fixture();
for prefix in [
vec![],
vec![s("breathe")],
vec![s("alpha")],
vec![s("nonexistent")],
] {
for layer in ["coarse", "specific", "never-declared"] {
assert_eq!(
out.attribution.subtree_leaf_count_of_layer(&prefix, layer),
out.attribution
.subtree_writes_of_layer(&prefix, layer)
.len(),
"count seam == wide seam length at prefix {prefix:?} × layer {layer}",
);
}
}
}
#[test]
fn subtree_leaf_count_of_layer_agrees_with_subtree_leaf_counts_by_layer_bucket() {
let out = subtree_fixture();
for prefix in [
vec![],
vec![s("breathe")],
vec![s("alpha")],
vec![s("nonexistent")],
] {
let counts = out.attribution.subtree_leaf_counts_by_layer(&prefix);
for layer in out.attribution.subtree_surviving_layer_names(&prefix) {
let single = out.attribution.subtree_leaf_count_of_layer(&prefix, layer);
let bucket = counts.get(layer).copied().unwrap_or(0);
assert_eq!(
single, bucket,
"single-writer count at prefix {prefix:?} equals subtree_leaf_counts_by_layer[{layer}]",
);
}
}
}
#[test]
fn subtree_leaf_count_of_layer_partition_count_law() {
let out = subtree_fixture();
for prefix in [vec![], vec![s("breathe")], vec![s("alpha")]] {
let survivors = out.attribution.subtree_surviving_layer_names(&prefix);
let total: usize = survivors
.iter()
.map(|l| out.attribution.subtree_leaf_count_of_layer(&prefix, l))
.sum();
let expected = out.attribution.subtree_iter(&prefix).count();
assert_eq!(
total, expected,
"sum of per-writer counts at prefix {prefix:?} equals subtree leaf count",
);
}
}
#[test]
fn subtree_leaf_count_of_layer_absent_prefix_is_zero() {
let out = subtree_fixture();
for layer in ["coarse", "specific", "never-declared"] {
assert_eq!(
out.attribution
.subtree_leaf_count_of_layer(&[s("nonexistent")], layer),
0,
"absent prefix ⇒ zero for every writer ({layer})",
);
}
}
#[test]
fn subtree_leaf_count_of_layer_missing_writer_is_zero() {
let out = subtree_fixture();
let prefix = vec![s("breathe")];
assert_eq!(
out.attribution
.subtree_leaf_count_of_layer(&prefix, "never-declared"),
0,
"never-declared writer under a real subtree ⇒ zero",
);
let empty = compose_with_provenance(&[]);
assert_eq!(
empty
.attribution
.subtree_leaf_count_of_layer(&[s("anything")], "anyone"),
0,
"empty attribution ⇒ zero for every (prefix, writer)",
);
}
#[test]
fn subtree_leaf_count_of_layer_is_leq_leaf_count_of_layer_pointwise() {
let out = subtree_fixture();
for prefix in [vec![], vec![s("breathe")], vec![s("alpha")]] {
for layer in ["coarse", "specific"] {
let sub = out.attribution.subtree_leaf_count_of_layer(&prefix, layer);
let parent = out.attribution.leaf_count_of_layer(layer);
assert!(
sub <= parent,
"sub count for {layer} at prefix {prefix:?} ({sub}) must not exceed parent count ({parent})",
);
}
}
let strict_prefix = vec![s("breathe")];
assert!(
out.attribution
.subtree_leaf_count_of_layer(&strict_prefix, "coarse")
< out.attribution.leaf_count_of_layer("coarse"),
"strict inequality when coarse wrote leaves outside `breathe.*`",
);
}
#[test]
fn subtree_writes_of_layer_at_exact_scalar_leaf_yields_that_leaf_only() {
let out = subtree_fixture();
let prefix = vec![s("alpha")];
let coarse: Vec<Vec<String>> = out
.attribution
.subtree_writes_of_layer(&prefix, "coarse")
.into_iter()
.map(<[String]>::to_vec)
.collect();
assert_eq!(coarse, vec![vec![s("alpha")]]);
assert!(
out.attribution
.subtree_writes_of_layer(&prefix, "specific")
.is_empty(),
"the leaf's non-writer gets no bucket at the exact-leaf prefix",
);
assert_eq!(
out.attribution
.subtree_leaf_count_of_layer(&prefix, "coarse"),
1,
"the leaf's writer gets count 1 at the exact-leaf prefix",
);
assert_eq!(
out.attribution
.subtree_leaf_count_of_layer(&prefix, "specific"),
0,
"non-writer's count at the exact-leaf prefix is zero",
);
}
fn three_way_tie_fixture() -> DiscoveryComposition {
let a = Fixed("aaa", dict(&[("ka", Value::from(1i64))]));
let b = Fixed("bbb", dict(&[("kb", Value::from(2i64))]));
let c = Fixed("ccc", dict(&[("kc", Value::from(3i64))]));
compose_with_provenance(&[&a, &b, &c])
}
fn inversion_fixture() -> DiscoveryComposition {
let coarse = Fixed(
"coarse",
dict(&[
(
"big",
Value::from(dict(&[
("a", Value::from(1i64)),
("b", Value::from(2i64)),
("c", Value::from(3i64)),
])),
),
("small", Value::from(dict(&[("x", Value::from(4i64))]))),
]),
);
let specific = Fixed(
"specific",
dict(&[(
"small",
Value::from(dict(&[("y", Value::from(5i64)), ("z", Value::from(6i64))])),
)]),
);
compose_with_provenance(&[&coarse, &specific])
}
#[test]
fn dominant_layer_agrees_with_leaf_counts_argmax() {
let out = layer_axis_fixture();
let dominant = out.attribution.dominant_layer().expect("non-empty");
assert_eq!(dominant, "tenancy", "tenancy owns 2 leaves > platform's 1");
let counts = out.attribution.leaf_counts_by_layer();
let max_count = counts.values().copied().max().expect("non-empty");
assert_eq!(
counts.get(dominant).copied().unwrap_or(0),
max_count,
"dominant writer's count equals the max of leaf_counts_by_layer",
);
assert_eq!(
out.attribution.leaf_count_of_layer(dominant),
max_count,
"leaf_count_of_layer(dominant) also equals the max",
);
}
#[test]
fn dominant_layer_ties_broken_by_lex_name_ascending() {
let out = three_way_tie_fixture();
assert_eq!(
out.attribution.dominant_layer(),
Some("aaa"),
"on a three-way tie, the smallest lex name wins",
);
}
#[test]
fn dominant_layer_empty_attribution_is_none() {
let empty = compose_with_provenance(&[]);
assert_eq!(
empty.attribution.dominant_layer(),
None,
"empty attribution ⇒ no dominant layer",
);
let silent = Fixed("silent-a", Dict::new());
let more_silent = Fixed("silent-b", Dict::new());
let silent_out = compose_with_provenance(&[&silent, &more_silent]);
assert_eq!(
silent_out.attribution.dominant_layer(),
None,
"silent-only stack ⇒ no dominant layer",
);
}
#[test]
fn dominant_layer_single_writer_is_that_writer() {
let solo = Fixed(
"solo",
dict(&[("k1", Value::from(1i64)), ("k2", Value::from(2i64))]),
);
let silent = Fixed("silent", Dict::new());
let out = compose_with_provenance(&[&solo, &silent]);
assert_eq!(
out.attribution.dominant_layer(),
Some("solo"),
"the only surviving writer is the dominant one",
);
}
#[test]
fn dominant_layer_is_member_of_surviving_layer_names() {
for out in [
layer_axis_fixture(),
subtree_fixture(),
three_way_tie_fixture(),
inversion_fixture(),
] {
if let Some(dominant) = out.attribution.dominant_layer() {
assert!(
out.attribution.surviving_layer_names().contains(&dominant),
"dominant_layer must be a member of surviving_layer_names",
);
}
}
}
#[test]
fn subtree_dominant_layer_empty_prefix_equals_dominant_layer() {
for out in [
layer_axis_fixture(),
subtree_fixture(),
three_way_tie_fixture(),
inversion_fixture(),
compose_with_provenance(&[]),
] {
assert_eq!(
out.attribution.subtree_dominant_layer(&[]),
out.attribution.dominant_layer(),
"empty prefix ⇒ subtree_dominant_layer equals dominant_layer",
);
}
}
#[test]
fn subtree_dominant_layer_at_named_prefix_narrows_the_argmax() {
let out = subtree_fixture();
assert_eq!(
out.attribution.subtree_dominant_layer(&[s("breathe")]),
Some("coarse"),
"under breathe.*, coarse and specific tie at 1 leaf each — coarse wins by lex",
);
assert_eq!(
out.attribution.subtree_dominant_layer(&[s("alpha")]),
Some("coarse"),
"under alpha (a leaf), coarse alone is dominant",
);
}
#[test]
fn subtree_dominant_layer_absent_prefix_is_none() {
let out = subtree_fixture();
assert_eq!(
out.attribution.subtree_dominant_layer(&[s("nonexistent")]),
None,
"absent prefix ⇒ empty subtree ⇒ None",
);
}
#[test]
fn subtree_dominant_layer_agrees_with_argmax_of_subtree_counts() {
let prefixes: Vec<Vec<String>> = vec![
vec![],
vec![s("breathe")],
vec![s("alpha")],
vec![s("small")],
vec![s("big")],
vec![s("nonexistent")],
];
for out in [subtree_fixture(), inversion_fixture(), layer_axis_fixture()] {
for prefix in &prefixes {
let counts = out.attribution.subtree_leaf_counts_by_layer(prefix);
let dominant = out.attribution.subtree_dominant_layer(prefix);
if let Some(name) = dominant {
let max_count = counts.values().copied().max().unwrap_or(0);
assert_eq!(
counts.get(name).copied().unwrap_or(0),
max_count,
"at prefix {prefix:?}, dominant {name}'s subtree count equals the max",
);
assert_eq!(
out.attribution.subtree_leaf_count_of_layer(prefix, name),
max_count,
"at prefix {prefix:?}, subtree_leaf_count_of_layer({name}) also equals the max",
);
let tied_at_max: Vec<&'static str> = counts
.iter()
.filter_map(|(k, v)| (*v == max_count).then_some(*k))
.collect();
assert_eq!(
tied_at_max.first().copied(),
Some(name),
"the winner is the smallest lex name among tied maxima",
);
} else {
assert!(
counts.is_empty(),
"None ⇒ empty subtree_leaf_counts_by_layer at prefix {prefix:?}",
);
assert_eq!(
out.attribution.subtree_iter(prefix).count(),
0,
"None ⇒ empty subtree_iter at prefix {prefix:?}",
);
}
}
}
}
#[test]
fn subtree_dominant_layer_is_member_of_subtree_surviving_layer_names_when_some() {
let prefixes: Vec<Vec<String>> = vec![
vec![],
vec![s("breathe")],
vec![s("alpha")],
vec![s("small")],
vec![s("big")],
vec![s("nonexistent")],
];
for out in [subtree_fixture(), inversion_fixture(), layer_axis_fixture()] {
for prefix in &prefixes {
if let Some(dominant) = out.attribution.subtree_dominant_layer(prefix) {
assert!(
out.attribution
.subtree_surviving_layer_names(prefix)
.contains(&dominant),
"at prefix {prefix:?}, dominant {dominant} must be in subtree_surviving_layer_names",
);
assert!(
out.attribution.surviving_layer_names().contains(&dominant),
"at prefix {prefix:?}, dominant {dominant} must be in surviving_layer_names",
);
}
}
}
}
#[test]
fn subtree_dominant_layer_can_differ_from_dominant_layer() {
let out = inversion_fixture();
assert_eq!(
out.attribution.dominant_layer(),
Some("coarse"),
"coarse owns the top-level argmax (4 leaves)",
);
assert_eq!(
out.attribution.subtree_dominant_layer(&[s("small")]),
Some("specific"),
"specific owns the ['small'] subtree (2 leaves vs coarse's 1)",
);
assert_eq!(
out.attribution.subtree_dominant_layer(&[s("big")]),
Some("coarse"),
"coarse still owns the ['big'] subtree (3 leaves vs specific's 0)",
);
}
#[test]
fn layer_ranking_agrees_with_leaf_counts_by_layer() {
for out in [
layer_axis_fixture(),
subtree_fixture(),
three_way_tie_fixture(),
inversion_fixture(),
] {
let ranking = out.attribution.layer_ranking();
let counts = out.attribution.leaf_counts_by_layer();
for (name, count) in &ranking {
assert_eq!(
counts.get(name).copied(),
Some(*count),
"ranking entry ({name}, {count}) must match leaf_counts_by_layer",
);
assert_eq!(
out.attribution.leaf_count_of_layer(name),
*count,
"ranking entry ({name}, {count}) must match leaf_count_of_layer",
);
}
let ranking_names: std::collections::BTreeSet<&'static str> =
ranking.iter().map(|(n, _)| *n).collect();
let counts_names: std::collections::BTreeSet<&'static str> =
counts.into_keys().collect();
assert_eq!(
ranking_names, counts_names,
"ranking names ≡ leaf_counts_by_layer keys (as a set)",
);
}
}
#[test]
fn layer_ranking_len_equals_surviving_layer_names_len() {
for out in [
layer_axis_fixture(),
subtree_fixture(),
three_way_tie_fixture(),
inversion_fixture(),
compose_with_provenance(&[]),
] {
assert_eq!(
out.attribution.layer_ranking().len(),
out.attribution.surviving_layer_names().len(),
"|layer_ranking| = |surviving_layer_names|",
);
assert_eq!(
out.attribution.layer_ranking().len(),
out.attribution.leaf_counts_by_layer().len(),
"|layer_ranking| = |leaf_counts_by_layer|",
);
}
}
#[test]
fn layer_ranking_counts_sum_to_len() {
for out in [
layer_axis_fixture(),
subtree_fixture(),
three_way_tie_fixture(),
inversion_fixture(),
compose_with_provenance(&[]),
] {
let sum: usize = out.attribution.layer_ranking().iter().map(|(_, c)| c).sum();
assert_eq!(sum, out.attribution.len(), "Σ counts = attribution.len()");
}
}
#[test]
fn layer_ranking_empty_iff_attribution_is_empty() {
assert!(
compose_with_provenance(&[])
.attribution
.layer_ranking()
.is_empty(),
"empty attribution ⇒ empty ranking",
);
for out in [
layer_axis_fixture(),
subtree_fixture(),
three_way_tie_fixture(),
inversion_fixture(),
] {
assert!(
!out.attribution.layer_ranking().is_empty(),
"non-empty attribution ⇒ non-empty ranking",
);
}
}
#[test]
fn layer_ranking_first_equals_dominant_layer() {
for out in [
layer_axis_fixture(),
subtree_fixture(),
three_way_tie_fixture(),
inversion_fixture(),
compose_with_provenance(&[]),
] {
let ranking_first: Option<&'static str> =
out.attribution.layer_ranking().first().map(|(n, _)| *n);
assert_eq!(
ranking_first,
out.attribution.dominant_layer(),
"ranking.first().name ≡ dominant_layer()",
);
}
}
#[test]
fn layer_ranking_counts_are_non_increasing() {
for out in [
layer_axis_fixture(),
subtree_fixture(),
three_way_tie_fixture(),
inversion_fixture(),
] {
let ranking = out.attribution.layer_ranking();
for window in ranking.windows(2) {
assert!(
window[0].1 >= window[1].1,
"counts must be non-increasing: {} !>= {}",
window[0].1,
window[1].1,
);
}
}
}
#[test]
fn layer_ranking_ties_are_lex_ascending() {
let out = three_way_tie_fixture();
assert_eq!(
out.attribution.layer_ranking(),
vec![("aaa", 1), ("bbb", 1), ("ccc", 1)],
"three-way tie orders by lex ascending",
);
for out in [
layer_axis_fixture(),
subtree_fixture(),
three_way_tie_fixture(),
inversion_fixture(),
] {
let ranking = out.attribution.layer_ranking();
for window in ranking.windows(2) {
if window[0].1 == window[1].1 {
assert!(
window[0].0 < window[1].0,
"tied names must be lex-ascending: {} !< {}",
window[0].0,
window[1].0,
);
}
}
}
}
#[test]
fn subtree_layer_ranking_empty_prefix_equals_layer_ranking() {
for out in [
layer_axis_fixture(),
subtree_fixture(),
three_way_tie_fixture(),
inversion_fixture(),
compose_with_provenance(&[]),
] {
assert_eq!(
out.attribution.subtree_layer_ranking(&[]),
out.attribution.layer_ranking(),
"empty prefix ⇒ subtree_layer_ranking equals layer_ranking",
);
}
}
#[test]
fn subtree_layer_ranking_absent_prefix_is_empty() {
let out = subtree_fixture();
assert!(
out.attribution
.subtree_layer_ranking(&[s("nonexistent")])
.is_empty(),
"absent prefix ⇒ empty subtree ⇒ empty ranking",
);
}
#[test]
fn subtree_layer_ranking_first_equals_subtree_dominant_layer() {
let prefixes: Vec<Vec<String>> = vec![
vec![],
vec![s("breathe")],
vec![s("alpha")],
vec![s("small")],
vec![s("big")],
vec![s("nonexistent")],
];
for out in [
subtree_fixture(),
inversion_fixture(),
layer_axis_fixture(),
three_way_tie_fixture(),
] {
for prefix in &prefixes {
let ranking_first: Option<&'static str> = out
.attribution
.subtree_layer_ranking(prefix)
.first()
.map(|(n, _)| *n);
assert_eq!(
ranking_first,
out.attribution.subtree_dominant_layer(prefix),
"at prefix {prefix:?}, subtree ranking.first().name ≡ subtree_dominant_layer",
);
}
}
}
#[test]
fn subtree_layer_ranking_agrees_with_subtree_leaf_counts() {
let prefixes: Vec<Vec<String>> = vec![
vec![],
vec![s("breathe")],
vec![s("alpha")],
vec![s("small")],
vec![s("big")],
vec![s("nonexistent")],
];
for out in [subtree_fixture(), inversion_fixture(), layer_axis_fixture()] {
for prefix in &prefixes {
let ranking = out.attribution.subtree_layer_ranking(prefix);
let counts = out.attribution.subtree_leaf_counts_by_layer(prefix);
let sum: usize = ranking.iter().map(|(_, c)| c).sum();
assert_eq!(
sum,
out.attribution.subtree_iter(prefix).count(),
"at prefix {prefix:?}, Σ counts = subtree_iter count",
);
for (name, count) in &ranking {
assert_eq!(
counts.get(name).copied(),
Some(*count),
"at prefix {prefix:?}, ranking entry ({name}, {count}) matches subtree_leaf_counts_by_layer",
);
assert_eq!(
out.attribution.subtree_leaf_count_of_layer(prefix, name),
*count,
"at prefix {prefix:?}, ranking entry ({name}, {count}) matches subtree_leaf_count_of_layer",
);
}
let ranking_names: std::collections::BTreeSet<&'static str> =
ranking.iter().map(|(n, _)| *n).collect();
let survivor_names: std::collections::BTreeSet<&'static str> = out
.attribution
.subtree_surviving_layer_names(prefix)
.into_iter()
.collect();
assert_eq!(
ranking_names, survivor_names,
"at prefix {prefix:?}, ranking names ≡ subtree_surviving_layer_names (as a set)",
);
}
}
}
#[test]
fn subtree_layer_ranking_counts_are_non_increasing_and_ties_lex_ascending() {
let prefixes: Vec<Vec<String>> = vec![
vec![],
vec![s("breathe")],
vec![s("alpha")],
vec![s("small")],
vec![s("big")],
];
for out in [
subtree_fixture(),
inversion_fixture(),
layer_axis_fixture(),
three_way_tie_fixture(),
] {
for prefix in &prefixes {
let ranking = out.attribution.subtree_layer_ranking(prefix);
for window in ranking.windows(2) {
assert!(
window[0].1 >= window[1].1,
"at prefix {prefix:?}, counts non-increasing: {} !>= {}",
window[0].1,
window[1].1,
);
if window[0].1 == window[1].1 {
assert!(
window[0].0 < window[1].0,
"at prefix {prefix:?}, tied names lex-ascending: {} !< {}",
window[0].0,
window[1].0,
);
}
}
}
}
}
#[test]
fn subtree_layer_ranking_narrows_at_named_prefix() {
let out = inversion_fixture();
assert_eq!(
out.attribution.subtree_layer_ranking(&[s("small")]),
vec![("specific", 2), ("coarse", 1)],
"under small.*, specific tops the ranking (2 vs 1)",
);
assert_eq!(
out.attribution.subtree_layer_ranking(&[s("big")]),
vec![("coarse", 3)],
"under big.*, only coarse contributes (3 leaves)",
);
}
#[test]
fn subtree_layer_ranking_name_set_subset_of_surviving_layer_names() {
let prefixes: Vec<Vec<String>> = vec![
vec![],
vec![s("breathe")],
vec![s("alpha")],
vec![s("small")],
vec![s("big")],
vec![s("nonexistent")],
];
for out in [subtree_fixture(), inversion_fixture(), layer_axis_fixture()] {
let global: std::collections::BTreeSet<&'static str> = out
.attribution
.surviving_layer_names()
.into_iter()
.collect();
for prefix in &prefixes {
let ranking = out.attribution.subtree_layer_ranking(prefix);
for (name, count) in &ranking {
assert!(
global.contains(name),
"at prefix {prefix:?}, subtree ranking name {name} must survive globally",
);
assert!(
*count <= out.attribution.leaf_count_of_layer(name),
"at prefix {prefix:?}, subtree count {count} ≤ global {} for {name}",
out.attribution.leaf_count_of_layer(name),
);
}
}
}
}
#[test]
fn weakest_layer_agrees_with_leaf_counts_argmin() {
let out = layer_axis_fixture();
let weakest = out.attribution.weakest_layer().expect("non-empty");
assert_eq!(weakest, "platform", "platform owns 1 leaf < tenancy's 2");
let counts = out.attribution.leaf_counts_by_layer();
let min_count = counts.values().copied().min().expect("non-empty");
assert_eq!(
counts.get(weakest).copied().unwrap_or(0),
min_count,
"weakest writer's count equals the min of leaf_counts_by_layer",
);
assert_eq!(
out.attribution.leaf_count_of_layer(weakest),
min_count,
"leaf_count_of_layer(weakest) also equals the min",
);
}
#[test]
fn weakest_layer_ties_broken_by_lex_name_descending() {
let out = three_way_tie_fixture();
assert_eq!(
out.attribution.weakest_layer(),
Some("ccc"),
"on a three-way tie, the largest lex name wins the argmin",
);
}
#[test]
fn weakest_layer_empty_attribution_is_none() {
let empty = compose_with_provenance(&[]);
assert_eq!(empty.attribution.weakest_layer(), None);
let silent = Fixed("silent-a", Dict::new());
let more_silent = Fixed("silent-b", Dict::new());
let silent_out = compose_with_provenance(&[&silent, &more_silent]);
assert_eq!(silent_out.attribution.weakest_layer(), None);
}
#[test]
fn weakest_layer_single_writer_is_that_writer() {
let solo = Fixed(
"solo",
dict(&[("k1", Value::from(1i64)), ("k2", Value::from(2i64))]),
);
let silent = Fixed("silent", Dict::new());
let out = compose_with_provenance(&[&solo, &silent]);
assert_eq!(out.attribution.weakest_layer(), Some("solo"));
assert_eq!(
out.attribution.weakest_layer(),
out.attribution.dominant_layer(),
"single-writer bookend collapse",
);
}
#[test]
fn weakest_layer_is_member_of_surviving_layer_names() {
for out in [
layer_axis_fixture(),
subtree_fixture(),
three_way_tie_fixture(),
inversion_fixture(),
] {
if let Some(weakest) = out.attribution.weakest_layer() {
assert!(
out.attribution.surviving_layer_names().contains(&weakest),
"weakest_layer must be a member of surviving_layer_names",
);
}
}
}
#[test]
fn weakest_layer_equals_layer_ranking_last() {
for out in [
layer_axis_fixture(),
subtree_fixture(),
three_way_tie_fixture(),
inversion_fixture(),
compose_with_provenance(&[]),
] {
let ranking_last: Option<&'static str> =
out.attribution.layer_ranking().last().map(|(n, _)| *n);
assert_eq!(
ranking_last,
out.attribution.weakest_layer(),
"ranking.last().name ≡ weakest_layer()",
);
}
}
#[test]
fn weakest_layer_equals_dominant_layer_on_single_writer_or_flat() {
let solo = Fixed("solo", dict(&[("k", Value::from(1i64))]));
let out = compose_with_provenance(&[&solo]);
assert_eq!(
out.attribution.weakest_layer(),
out.attribution.dominant_layer(),
"single-writer ⇒ bookends coincide",
);
let tied = three_way_tie_fixture();
assert_ne!(
tied.attribution.weakest_layer(),
tied.attribution.dominant_layer(),
"flat but multi-writer ⇒ bookends disagree by tie-break rule",
);
assert_eq!(tied.attribution.dominant_layer(), Some("aaa"));
assert_eq!(tied.attribution.weakest_layer(), Some("ccc"));
let axis = layer_axis_fixture();
assert_ne!(
axis.attribution.weakest_layer(),
axis.attribution.dominant_layer(),
"distinct counts ⇒ bookends differ",
);
}
#[test]
fn subtree_weakest_layer_empty_prefix_equals_weakest_layer() {
for out in [
layer_axis_fixture(),
subtree_fixture(),
three_way_tie_fixture(),
inversion_fixture(),
compose_with_provenance(&[]),
] {
assert_eq!(
out.attribution.subtree_weakest_layer(&[]),
out.attribution.weakest_layer(),
"empty prefix ⇒ subtree_weakest_layer equals weakest_layer",
);
}
}
#[test]
fn subtree_weakest_layer_at_named_prefix_narrows_the_argmin() {
let out = subtree_fixture();
assert_eq!(
out.attribution.subtree_weakest_layer(&[s("breathe")]),
Some("specific"),
"under breathe.*, tied at 1 leaf each — specific wins by largest lex",
);
assert_eq!(
out.attribution.subtree_weakest_layer(&[s("alpha")]),
Some("coarse"),
"under alpha (a leaf), coarse alone is trivially weakest",
);
let inv = inversion_fixture();
assert_eq!(
inv.attribution.subtree_weakest_layer(&[s("small")]),
Some("coarse"),
"under small.*, coarse (1 leaf) is weaker than specific (2)",
);
assert_eq!(
inv.attribution.subtree_weakest_layer(&[s("big")]),
Some("coarse"),
"under big.*, coarse alone is trivially weakest",
);
}
#[test]
fn subtree_weakest_layer_absent_prefix_is_none() {
let out = subtree_fixture();
assert_eq!(
out.attribution.subtree_weakest_layer(&[s("nonexistent")]),
None,
"absent prefix ⇒ empty subtree ⇒ None",
);
}
#[test]
fn subtree_weakest_layer_agrees_with_argmin_of_subtree_counts() {
let prefixes: Vec<Vec<String>> = vec![
vec![],
vec![s("breathe")],
vec![s("alpha")],
vec![s("small")],
vec![s("big")],
vec![s("nonexistent")],
];
for out in [
subtree_fixture(),
inversion_fixture(),
layer_axis_fixture(),
three_way_tie_fixture(),
] {
for prefix in &prefixes {
let weakest = out.attribution.subtree_weakest_layer(prefix);
let counts = out.attribution.subtree_leaf_counts_by_layer(prefix);
if let Some(name) = weakest {
let min_count = counts
.values()
.copied()
.min()
.expect("non-empty subtree ⇒ non-empty counter map");
assert_eq!(
counts.get(name).copied(),
Some(min_count),
"at prefix {prefix:?}, weakest {name} owns the min count",
);
assert_eq!(
out.attribution.subtree_leaf_count_of_layer(prefix, name),
min_count,
"at prefix {prefix:?}, subtree_leaf_count_of_layer({name}) equals the min",
);
let tied_at_min: Vec<&'static str> = counts
.iter()
.filter_map(|(n, c)| (*c == min_count).then_some(*n))
.collect();
assert_eq!(
tied_at_min.last().copied(),
Some(name),
"at prefix {prefix:?}, weakest picks the largest lex name among tied minima",
);
} else {
assert!(
counts.is_empty(),
"at prefix {prefix:?}, None ⇒ counter map is empty",
);
assert_eq!(
out.attribution.subtree_iter(prefix).count(),
0,
"at prefix {prefix:?}, None ⇒ subtree_iter is empty",
);
}
}
}
}
#[test]
fn subtree_weakest_layer_is_member_of_subtree_surviving_layer_names_when_some() {
let prefixes: Vec<Vec<String>> = vec![
vec![],
vec![s("breathe")],
vec![s("alpha")],
vec![s("small")],
vec![s("big")],
vec![s("nonexistent")],
];
for out in [
subtree_fixture(),
inversion_fixture(),
layer_axis_fixture(),
three_way_tie_fixture(),
] {
let global: std::collections::BTreeSet<&'static str> = out
.attribution
.surviving_layer_names()
.into_iter()
.collect();
for prefix in &prefixes {
if let Some(weakest) = out.attribution.subtree_weakest_layer(prefix) {
let subtree_set: std::collections::BTreeSet<&'static str> = out
.attribution
.subtree_surviving_layer_names(prefix)
.into_iter()
.collect();
assert!(
subtree_set.contains(weakest),
"at prefix {prefix:?}, weakest {weakest} lives in subtree_surviving_layer_names",
);
assert!(
global.contains(weakest),
"at prefix {prefix:?}, weakest {weakest} lives in the global surviving set",
);
}
}
}
}
#[test]
fn subtree_weakest_layer_equals_subtree_layer_ranking_last() {
let prefixes: Vec<Vec<String>> = vec![
vec![],
vec![s("breathe")],
vec![s("alpha")],
vec![s("small")],
vec![s("big")],
vec![s("nonexistent")],
];
for out in [
subtree_fixture(),
inversion_fixture(),
layer_axis_fixture(),
three_way_tie_fixture(),
] {
for prefix in &prefixes {
let ranking_last: Option<&'static str> = out
.attribution
.subtree_layer_ranking(prefix)
.last()
.map(|(n, _)| *n);
assert_eq!(
ranking_last,
out.attribution.subtree_weakest_layer(prefix),
"at prefix {prefix:?}, subtree ranking.last().name ≡ subtree_weakest_layer",
);
}
}
}
#[test]
fn subtree_weakest_layer_can_differ_from_weakest_layer() {
let out = inversion_fixture();
assert_eq!(out.attribution.weakest_layer(), Some("specific"));
assert_eq!(
out.attribution.subtree_weakest_layer(&[s("big")]),
Some("coarse"),
"under big.*, specific is absent — coarse is the only (and weakest) writer",
);
assert_eq!(
out.attribution.subtree_weakest_layer(&[s("small")]),
Some("coarse"),
"under small.*, coarse (1 leaf) is weaker than specific (2)",
);
}
#[test]
fn dominant_entry_agrees_with_leaf_counts_argmax() {
let out = layer_axis_fixture();
let entry = out.attribution.dominant_entry().expect("non-empty");
assert_eq!(entry, ("tenancy", 2));
let counts = out.attribution.leaf_counts_by_layer();
let max_count = counts.values().copied().max().expect("non-empty");
assert_eq!(entry.1, max_count);
assert_eq!(counts.get(entry.0).copied(), Some(entry.1));
}
#[test]
fn dominant_entry_ties_broken_by_lex_name_ascending() {
let out = three_way_tie_fixture();
assert_eq!(
out.attribution.dominant_entry(),
Some(("aaa", 1)),
"on a three-way tie, smallest lex name wins with its count",
);
}
#[test]
fn dominant_entry_empty_attribution_is_none() {
let empty = compose_with_provenance(&[]);
assert_eq!(empty.attribution.dominant_entry(), None);
let silent = Fixed("silent-a", Dict::new());
let more_silent = Fixed("silent-b", Dict::new());
let silent_out = compose_with_provenance(&[&silent, &more_silent]);
assert_eq!(silent_out.attribution.dominant_entry(), None);
}
#[test]
fn dominant_entry_single_writer_pairs_writer_with_its_leaf_count() {
let solo = Fixed(
"solo",
dict(&[("k1", Value::from(1i64)), ("k2", Value::from(2i64))]),
);
let silent = Fixed("silent", Dict::new());
let out = compose_with_provenance(&[&solo, &silent]);
assert_eq!(out.attribution.dominant_entry(), Some(("solo", 2)));
}
#[test]
fn dominant_entry_equals_layer_ranking_first() {
for out in [
layer_axis_fixture(),
subtree_fixture(),
three_way_tie_fixture(),
inversion_fixture(),
compose_with_provenance(&[]),
] {
let via_ranking: Option<(&'static str, usize)> =
out.attribution.layer_ranking().first().copied();
assert_eq!(
out.attribution.dominant_entry(),
via_ranking,
"dominant_entry() ≡ layer_ranking().first().copied()",
);
}
}
#[test]
fn dominant_entry_name_projection_equals_dominant_layer() {
for out in [
layer_axis_fixture(),
subtree_fixture(),
three_way_tie_fixture(),
inversion_fixture(),
compose_with_provenance(&[]),
] {
let entry_name: Option<&'static str> = out.attribution.dominant_entry().map(|(n, _)| n);
assert_eq!(
entry_name,
out.attribution.dominant_layer(),
"dominant_entry().map(|(n, _)| n) ≡ dominant_layer()",
);
}
}
#[test]
fn dominant_entry_count_projection_equals_leaf_counts_max() {
for out in [
layer_axis_fixture(),
subtree_fixture(),
three_way_tie_fixture(),
inversion_fixture(),
compose_with_provenance(&[]),
] {
let entry_count: Option<usize> = out.attribution.dominant_entry().map(|(_, c)| c);
let max_count: Option<usize> = out
.attribution
.leaf_counts_by_layer()
.values()
.copied()
.max();
assert_eq!(
entry_count, max_count,
"dominant_entry().map(|(_, c)| c) ≡ leaf_counts_by_layer().values().max()",
);
}
}
#[test]
fn dominant_entry_count_agrees_with_leaf_count_of_layer() {
for out in [
layer_axis_fixture(),
subtree_fixture(),
three_way_tie_fixture(),
inversion_fixture(),
] {
let (name, count) = out.attribution.dominant_entry().expect("non-empty fixture");
assert_eq!(
count,
out.attribution.leaf_count_of_layer(name),
"dominant_entry count ≡ leaf_count_of_layer(name)",
);
}
}
#[test]
fn subtree_dominant_entry_empty_prefix_equals_dominant_entry() {
for out in [
layer_axis_fixture(),
subtree_fixture(),
three_way_tie_fixture(),
inversion_fixture(),
compose_with_provenance(&[]),
] {
assert_eq!(
out.attribution.subtree_dominant_entry(&[]),
out.attribution.dominant_entry(),
"empty prefix ⇒ subtree_dominant_entry ≡ dominant_entry",
);
}
}
#[test]
fn subtree_dominant_entry_at_named_prefix_narrows_the_argmax() {
let out = subtree_fixture();
assert_eq!(
out.attribution.subtree_dominant_entry(&[s("breathe")]),
Some(("coarse", 1)),
"under breathe.*, tied at 1 leaf each — coarse wins by smallest lex",
);
assert_eq!(
out.attribution.subtree_dominant_entry(&[s("alpha")]),
Some(("coarse", 1)),
"under alpha (a leaf), coarse alone owns the row",
);
let inv = inversion_fixture();
assert_eq!(
inv.attribution.subtree_dominant_entry(&[s("small")]),
Some(("specific", 2)),
"under small.*, specific (2 leaves) beats coarse (1)",
);
assert_eq!(
inv.attribution.subtree_dominant_entry(&[s("big")]),
Some(("coarse", 3)),
"under big.*, coarse alone owns the row with 3 leaves",
);
}
#[test]
fn subtree_dominant_entry_absent_prefix_is_none() {
let out = subtree_fixture();
assert_eq!(
out.attribution.subtree_dominant_entry(&[s("nonexistent")]),
None,
"absent prefix ⇒ empty subtree ⇒ None",
);
}
#[test]
fn subtree_dominant_entry_agrees_with_argmax_of_subtree_counts() {
let prefixes: Vec<Vec<String>> = vec![
vec![],
vec![s("breathe")],
vec![s("alpha")],
vec![s("small")],
vec![s("big")],
vec![s("nonexistent")],
];
for out in [
subtree_fixture(),
inversion_fixture(),
layer_axis_fixture(),
three_way_tie_fixture(),
] {
for prefix in &prefixes {
let entry = out.attribution.subtree_dominant_entry(prefix);
let counts = out.attribution.subtree_leaf_counts_by_layer(prefix);
if let Some((name, count)) = entry {
let max_count = counts
.values()
.copied()
.max()
.expect("non-empty subtree ⇒ non-empty counter map");
assert_eq!(
count, max_count,
"at prefix {prefix:?}, entry count equals subtree argmax",
);
assert_eq!(
counts.get(name).copied(),
Some(count),
"at prefix {prefix:?}, entry count equals the histogram bucket",
);
assert_eq!(
out.attribution.subtree_leaf_count_of_layer(prefix, name),
count,
"at prefix {prefix:?}, entry count ≡ subtree_leaf_count_of_layer",
);
let tied_at_max: Vec<&'static str> = counts
.iter()
.filter_map(|(n, c)| (*c == max_count).then_some(*n))
.collect();
assert_eq!(
tied_at_max.first().copied(),
Some(name),
"at prefix {prefix:?}, entry picks smallest lex name among tied maxima",
);
} else {
assert!(
counts.is_empty(),
"at prefix {prefix:?}, None ⇒ counter map is empty",
);
assert_eq!(
out.attribution.subtree_iter(prefix).count(),
0,
"at prefix {prefix:?}, None ⇒ subtree_iter is empty",
);
}
}
}
}
#[test]
fn subtree_dominant_entry_equals_subtree_layer_ranking_first() {
let prefixes: Vec<Vec<String>> = vec![
vec![],
vec![s("breathe")],
vec![s("alpha")],
vec![s("small")],
vec![s("big")],
vec![s("nonexistent")],
];
for out in [
subtree_fixture(),
inversion_fixture(),
layer_axis_fixture(),
three_way_tie_fixture(),
] {
for prefix in &prefixes {
let via_ranking: Option<(&'static str, usize)> = out
.attribution
.subtree_layer_ranking(prefix)
.first()
.copied();
assert_eq!(
out.attribution.subtree_dominant_entry(prefix),
via_ranking,
"at prefix {prefix:?}, subtree_dominant_entry ≡ subtree_layer_ranking.first().copied()",
);
}
}
}
#[test]
fn subtree_dominant_entry_projections_equal_scalars() {
let prefixes: Vec<Vec<String>> = vec![
vec![],
vec![s("breathe")],
vec![s("alpha")],
vec![s("small")],
vec![s("big")],
vec![s("nonexistent")],
];
for out in [
subtree_fixture(),
inversion_fixture(),
layer_axis_fixture(),
three_way_tie_fixture(),
compose_with_provenance(&[]),
] {
for prefix in &prefixes {
let entry = out.attribution.subtree_dominant_entry(prefix);
assert_eq!(
entry.map(|(n, _)| n),
out.attribution.subtree_dominant_layer(prefix),
"at prefix {prefix:?}, name projection ≡ subtree_dominant_layer",
);
let counts_max: Option<usize> = out
.attribution
.subtree_leaf_counts_by_layer(prefix)
.values()
.copied()
.max();
assert_eq!(
entry.map(|(_, c)| c),
counts_max,
"at prefix {prefix:?}, count projection ≡ subtree histogram max",
);
}
}
}
#[test]
fn subtree_dominant_entry_name_in_surviving_and_count_le_global() {
let prefixes: Vec<Vec<String>> = vec![
vec![],
vec![s("breathe")],
vec![s("alpha")],
vec![s("small")],
vec![s("big")],
vec![s("nonexistent")],
];
for out in [
subtree_fixture(),
inversion_fixture(),
layer_axis_fixture(),
three_way_tie_fixture(),
] {
let global: std::collections::BTreeSet<&'static str> = out
.attribution
.surviving_layer_names()
.into_iter()
.collect();
for prefix in &prefixes {
if let Some((name, count)) = out.attribution.subtree_dominant_entry(prefix) {
assert!(
global.contains(name),
"at prefix {prefix:?}, entry name {name} lives in the global surviving set",
);
assert!(
count <= out.attribution.leaf_count_of_layer(name),
"at prefix {prefix:?}, subtree count {count} ≤ global {} for {name}",
out.attribution.leaf_count_of_layer(name),
);
}
}
}
}
#[test]
fn subtree_dominant_entry_can_differ_from_dominant_entry() {
let out = inversion_fixture();
assert_eq!(out.attribution.dominant_entry(), Some(("coarse", 4)));
assert_eq!(
out.attribution.subtree_dominant_entry(&[s("small")]),
Some(("specific", 2)),
"under small.*, specific owns the top row locally",
);
assert_eq!(
out.attribution.subtree_dominant_entry(&[s("big")]),
Some(("coarse", 3)),
"under big.*, coarse alone with 3 leaves — count narrows",
);
}
#[test]
fn weakest_entry_agrees_with_leaf_counts_argmin() {
let out = layer_axis_fixture();
let entry = out.attribution.weakest_entry().expect("non-empty");
assert_eq!(entry, ("platform", 1));
let counts = out.attribution.leaf_counts_by_layer();
let min_count = counts.values().copied().min().expect("non-empty");
assert_eq!(entry.1, min_count);
assert_eq!(counts.get(entry.0).copied(), Some(entry.1));
}
#[test]
fn weakest_entry_ties_broken_by_lex_name_descending() {
let out = three_way_tie_fixture();
assert_eq!(
out.attribution.weakest_entry(),
Some(("ccc", 1)),
"on a three-way tie, the largest lex name wins with its count",
);
}
#[test]
fn weakest_entry_empty_attribution_is_none() {
let empty = compose_with_provenance(&[]);
assert_eq!(empty.attribution.weakest_entry(), None);
let silent = Fixed("silent-a", Dict::new());
let more_silent = Fixed("silent-b", Dict::new());
let silent_out = compose_with_provenance(&[&silent, &more_silent]);
assert_eq!(silent_out.attribution.weakest_entry(), None);
}
#[test]
fn weakest_entry_single_writer_pairs_writer_with_its_leaf_count() {
let solo = Fixed(
"solo",
dict(&[("k1", Value::from(1i64)), ("k2", Value::from(2i64))]),
);
let silent = Fixed("silent", Dict::new());
let out = compose_with_provenance(&[&solo, &silent]);
assert_eq!(out.attribution.weakest_entry(), Some(("solo", 2)));
assert_eq!(
out.attribution.weakest_entry(),
out.attribution.dominant_entry(),
"single-writer ⇒ bookend entries coincide",
);
}
#[test]
fn weakest_entry_equals_layer_ranking_last() {
for out in [
layer_axis_fixture(),
subtree_fixture(),
three_way_tie_fixture(),
inversion_fixture(),
compose_with_provenance(&[]),
] {
let via_ranking: Option<(&'static str, usize)> =
out.attribution.layer_ranking().last().copied();
assert_eq!(
out.attribution.weakest_entry(),
via_ranking,
"weakest_entry() ≡ layer_ranking().last().copied()",
);
}
}
#[test]
fn weakest_entry_name_projection_equals_weakest_layer() {
for out in [
layer_axis_fixture(),
subtree_fixture(),
three_way_tie_fixture(),
inversion_fixture(),
compose_with_provenance(&[]),
] {
let entry_name: Option<&'static str> = out.attribution.weakest_entry().map(|(n, _)| n);
assert_eq!(
entry_name,
out.attribution.weakest_layer(),
"weakest_entry().map(|(n, _)| n) ≡ weakest_layer()",
);
}
}
#[test]
fn weakest_entry_count_projection_equals_leaf_counts_min() {
for out in [
layer_axis_fixture(),
subtree_fixture(),
three_way_tie_fixture(),
inversion_fixture(),
compose_with_provenance(&[]),
] {
let entry_count: Option<usize> = out.attribution.weakest_entry().map(|(_, c)| c);
let min_count: Option<usize> = out
.attribution
.leaf_counts_by_layer()
.values()
.copied()
.min();
assert_eq!(
entry_count, min_count,
"weakest_entry().map(|(_, c)| c) ≡ leaf_counts_by_layer().values().min()",
);
}
}
#[test]
fn weakest_entry_count_agrees_with_leaf_count_of_layer() {
for out in [
layer_axis_fixture(),
subtree_fixture(),
three_way_tie_fixture(),
inversion_fixture(),
] {
let (name, count) = out.attribution.weakest_entry().expect("non-empty fixture");
assert_eq!(
count,
out.attribution.leaf_count_of_layer(name),
"weakest_entry count ≡ leaf_count_of_layer(name)",
);
}
}
#[test]
fn weakest_entry_bookend_law_vs_dominant_entry() {
let solo = Fixed("solo", dict(&[("k", Value::from(1i64))]));
let solo_out = compose_with_provenance(&[&solo]);
assert_eq!(
solo_out.attribution.weakest_entry(),
solo_out.attribution.dominant_entry(),
"single-writer ⇒ bookend entries coincide",
);
let tied = three_way_tie_fixture();
let dom = tied.attribution.dominant_entry().expect("non-empty");
let weak = tied.attribution.weakest_entry().expect("non-empty");
assert_ne!(dom.0, weak.0, "flat but multi-writer ⇒ names disagree");
assert_eq!(dom.1, weak.1, "flat ⇒ counts agree");
assert_eq!(dom, ("aaa", 1));
assert_eq!(weak, ("ccc", 1));
let axis = layer_axis_fixture();
assert_ne!(
axis.attribution.weakest_entry(),
axis.attribution.dominant_entry(),
"distinct counts ⇒ bookend entries disagree",
);
}
#[test]
fn subtree_weakest_entry_empty_prefix_equals_weakest_entry() {
for out in [
layer_axis_fixture(),
subtree_fixture(),
three_way_tie_fixture(),
inversion_fixture(),
compose_with_provenance(&[]),
] {
assert_eq!(
out.attribution.subtree_weakest_entry(&[]),
out.attribution.weakest_entry(),
"empty prefix ⇒ subtree_weakest_entry ≡ weakest_entry",
);
}
}
#[test]
fn subtree_weakest_entry_at_named_prefix_narrows_the_argmin() {
let out = subtree_fixture();
assert_eq!(
out.attribution.subtree_weakest_entry(&[s("breathe")]),
Some(("specific", 1)),
"under breathe.*, tied at 1 leaf each — specific wins by largest lex",
);
assert_eq!(
out.attribution.subtree_weakest_entry(&[s("alpha")]),
Some(("coarse", 1)),
"under alpha (a leaf), coarse alone owns the row",
);
let inv = inversion_fixture();
assert_eq!(
inv.attribution.subtree_weakest_entry(&[s("small")]),
Some(("coarse", 1)),
"under small.*, coarse (1 leaf) is the weakest row",
);
assert_eq!(
inv.attribution.subtree_weakest_entry(&[s("big")]),
Some(("coarse", 3)),
"under big.*, coarse alone owns the row with 3 leaves",
);
}
#[test]
fn subtree_weakest_entry_absent_prefix_is_none() {
let out = subtree_fixture();
assert_eq!(
out.attribution.subtree_weakest_entry(&[s("nonexistent")]),
None,
"absent prefix ⇒ empty subtree ⇒ None",
);
}
#[test]
fn subtree_weakest_entry_agrees_with_argmin_of_subtree_counts() {
let prefixes: Vec<Vec<String>> = vec![
vec![],
vec![s("breathe")],
vec![s("alpha")],
vec![s("small")],
vec![s("big")],
vec![s("nonexistent")],
];
for out in [
subtree_fixture(),
inversion_fixture(),
layer_axis_fixture(),
three_way_tie_fixture(),
] {
for prefix in &prefixes {
let entry = out.attribution.subtree_weakest_entry(prefix);
let counts = out.attribution.subtree_leaf_counts_by_layer(prefix);
if let Some((name, count)) = entry {
let min_count = counts
.values()
.copied()
.min()
.expect("non-empty subtree ⇒ non-empty counter map");
assert_eq!(
count, min_count,
"at prefix {prefix:?}, entry count equals subtree argmin",
);
assert_eq!(
counts.get(name).copied(),
Some(count),
"at prefix {prefix:?}, entry count equals the histogram bucket",
);
assert_eq!(
out.attribution.subtree_leaf_count_of_layer(prefix, name),
count,
"at prefix {prefix:?}, entry count ≡ subtree_leaf_count_of_layer",
);
let tied_at_min: Vec<&'static str> = counts
.iter()
.filter_map(|(n, c)| (*c == min_count).then_some(*n))
.collect();
assert_eq!(
tied_at_min.last().copied(),
Some(name),
"at prefix {prefix:?}, entry picks largest lex name among tied minima",
);
} else {
assert!(
counts.is_empty(),
"at prefix {prefix:?}, None ⇒ counter map is empty",
);
assert_eq!(
out.attribution.subtree_iter(prefix).count(),
0,
"at prefix {prefix:?}, None ⇒ subtree_iter is empty",
);
}
}
}
}
#[test]
fn subtree_weakest_entry_equals_subtree_layer_ranking_last() {
let prefixes: Vec<Vec<String>> = vec![
vec![],
vec![s("breathe")],
vec![s("alpha")],
vec![s("small")],
vec![s("big")],
vec![s("nonexistent")],
];
for out in [
subtree_fixture(),
inversion_fixture(),
layer_axis_fixture(),
three_way_tie_fixture(),
] {
for prefix in &prefixes {
let via_ranking: Option<(&'static str, usize)> = out
.attribution
.subtree_layer_ranking(prefix)
.last()
.copied();
assert_eq!(
out.attribution.subtree_weakest_entry(prefix),
via_ranking,
"at prefix {prefix:?}, subtree_weakest_entry ≡ subtree_layer_ranking.last().copied()",
);
}
}
}
#[test]
fn subtree_weakest_entry_projections_equal_scalars() {
let prefixes: Vec<Vec<String>> = vec![
vec![],
vec![s("breathe")],
vec![s("alpha")],
vec![s("small")],
vec![s("big")],
vec![s("nonexistent")],
];
for out in [
subtree_fixture(),
inversion_fixture(),
layer_axis_fixture(),
three_way_tie_fixture(),
compose_with_provenance(&[]),
] {
for prefix in &prefixes {
let entry = out.attribution.subtree_weakest_entry(prefix);
assert_eq!(
entry.map(|(n, _)| n),
out.attribution.subtree_weakest_layer(prefix),
"at prefix {prefix:?}, name projection ≡ subtree_weakest_layer",
);
let counts_min: Option<usize> = out
.attribution
.subtree_leaf_counts_by_layer(prefix)
.values()
.copied()
.min();
assert_eq!(
entry.map(|(_, c)| c),
counts_min,
"at prefix {prefix:?}, count projection ≡ subtree histogram min",
);
}
}
}
#[test]
fn subtree_weakest_entry_name_in_surviving_and_count_le_global() {
let prefixes: Vec<Vec<String>> = vec![
vec![],
vec![s("breathe")],
vec![s("alpha")],
vec![s("small")],
vec![s("big")],
vec![s("nonexistent")],
];
for out in [
subtree_fixture(),
inversion_fixture(),
layer_axis_fixture(),
three_way_tie_fixture(),
] {
let global: std::collections::BTreeSet<&'static str> = out
.attribution
.surviving_layer_names()
.into_iter()
.collect();
for prefix in &prefixes {
if let Some((name, count)) = out.attribution.subtree_weakest_entry(prefix) {
assert!(
global.contains(name),
"at prefix {prefix:?}, entry name {name} lives in the global surviving set",
);
assert!(
count <= out.attribution.leaf_count_of_layer(name),
"at prefix {prefix:?}, subtree count {count} ≤ global {} for {name}",
out.attribution.leaf_count_of_layer(name),
);
}
}
}
}
#[test]
fn subtree_weakest_entry_can_differ_from_weakest_entry() {
let out = inversion_fixture();
assert_eq!(out.attribution.weakest_entry(), Some(("specific", 2)));
assert_eq!(
out.attribution.subtree_weakest_entry(&[s("big")]),
Some(("coarse", 3)),
"under big.*, specific is absent — coarse alone owns the row",
);
assert_eq!(
out.attribution.subtree_weakest_entry(&[s("small")]),
Some(("coarse", 1)),
"under small.*, coarse (1 leaf) is weakest locally",
);
}
#[test]
fn contributors_at_lists_layers_that_touched_leaf_in_application_order() {
let a = Fixed("a", dict(&[("k", Value::from(1i64))]));
let b = Fixed("b", dict(&[("k", Value::from(2i64))]));
let c = Fixed("c", dict(&[("other", Value::from(3i64))]));
let silent = Fixed("silent", Dict::new());
assert_eq!(
contributors_at(&[&a, &b, &c, &silent], &["k"]),
vec!["a", "b"],
);
assert_eq!(
contributors_at(&[&a, &b, &c, &silent], &["other"]),
vec!["c"]
);
assert_eq!(
contributors_at(&[&a, &b, &c, &silent], &["nope"]),
Vec::<&'static str>::new(),
);
}
#[test]
fn contributors_at_includes_prefix_scalar_and_dict_container_touchers() {
let a = Fixed(
"a",
dict(&[("x", Value::from(dict(&[("a", Value::from(1i64))])))]),
);
let b = Fixed("b", dict(&[("x", Value::from(9i64))]));
assert_eq!(contributors_at(&[&a, &b], &["x", "a"]), vec!["a", "b"]);
let out = compose_with_provenance(&[&a, &b]);
assert_eq!(out.attribution.layer_of(&["x", "a"]), None);
}
#[test]
fn contributors_at_last_element_equals_layer_of_when_leaf_survives() {
let coarse = Fixed(
"platform",
dict(&[(
"breathe",
Value::from(dict(&[
("setpoint", Value::from(0.80)),
("mode", Value::from("live")),
])),
)]),
);
let specific = Fixed(
"tenancy",
dict(&[(
"breathe",
Value::from(dict(&[("mode", Value::from("shadow"))])),
)]),
);
let layers: [&dyn DiscoveryLayer; 2] = [&coarse, &specific];
let out = compose_with_provenance(&layers);
let contested = contributors_at(&layers, &["breathe", "mode"]);
assert_eq!(contested, vec!["platform", "tenancy"]);
assert_eq!(
contested.last().copied(),
out.attribution.layer_of(&["breathe", "mode"])
);
let uncontested = contributors_at(&layers, &["breathe", "setpoint"]);
assert_eq!(uncontested, vec!["platform"]);
assert_eq!(
uncontested.last().copied(),
out.attribution.layer_of(&["breathe", "setpoint"]),
);
}
#[test]
fn contributors_at_root_equals_contributor_names() {
let coarse = Fixed("platform", dict(&[("a", Value::from(1i64))]));
let silent = Fixed("undetectable", Dict::new());
let specific = Fixed("tenancy", dict(&[("b", Value::from(2i64))]));
let layers: [&dyn DiscoveryLayer; 3] = [&coarse, &silent, &specific];
assert_eq!(contributors_at(&layers, &[]), contributor_names(&layers));
assert_eq!(contributors_at(&layers, &[]), vec!["platform", "tenancy"]);
}
#[test]
fn contributors_at_is_subset_of_contributor_names() {
let a = Fixed("a", dict(&[("k", Value::from(1i64))]));
let b = Fixed("b", dict(&[("k", Value::from(2i64))]));
let c = Fixed("c", dict(&[("other", Value::from(3i64))]));
let silent = Fixed("silent", Dict::new());
let layers: [&dyn DiscoveryLayer; 4] = [&a, &b, &c, &silent];
let all: std::collections::BTreeSet<_> = contributor_names(&layers).into_iter().collect();
for path in [&["k"][..], &["other"][..], &["nope"][..], &[][..]] {
let restricted: std::collections::BTreeSet<_> =
contributors_at(&layers, path).into_iter().collect();
assert!(
restricted.is_subset(&all),
"contributors_at({path:?}) = {restricted:?} not ⊆ contributor_names = {all:?}",
);
}
}
#[test]
fn contributors_at_empty_layers_is_empty() {
assert_eq!(contributors_at(&[], &["k"]), Vec::<&'static str>::new());
assert_eq!(contributors_at(&[], &[]), Vec::<&'static str>::new());
}
#[test]
fn contributors_at_ignores_layers_with_disjoint_content() {
let match_layer = Fixed(
"match",
dict(&[("a", Value::from(dict(&[("b", Value::from(1i64))])))]),
);
let disjoint = Fixed("disjoint", dict(&[("z", Value::from(9i64))]));
assert_eq!(
contributors_at(&[&match_layer, &disjoint], &["a", "b"]),
vec!["match"],
);
}
#[test]
fn silenced_at_lists_overridden_touchers_in_application_order() {
let a = Fixed("a", dict(&[("k", Value::from(1i64))]));
let b = Fixed("b", dict(&[("k", Value::from(2i64))]));
let c = Fixed("c", dict(&[("k", Value::from(3i64))]));
let disjoint = Fixed("disjoint", dict(&[("other", Value::from(9i64))]));
assert_eq!(
silenced_at(&[&a, &b, &c, &disjoint], &["k"]),
vec!["a", "b"],
);
}
#[test]
fn silenced_at_empty_when_single_toucher_or_no_toucher() {
let a = Fixed("a", dict(&[("k", Value::from(1i64))]));
let disjoint = Fixed("z", dict(&[("other", Value::from(9i64))]));
assert_eq!(
silenced_at(&[&a, &disjoint], &["k"]),
Vec::<&'static str>::new(),
);
assert_eq!(
silenced_at(&[&a, &disjoint], &["nope"]),
Vec::<&'static str>::new(),
);
assert_eq!(silenced_at(&[], &["k"]), Vec::<&'static str>::new());
assert_eq!(silenced_at(&[], &[]), Vec::<&'static str>::new());
}
#[test]
fn silenced_at_partitions_contributors_at_disjointly() {
let coarse = Fixed(
"platform",
dict(&[(
"breathe",
Value::from(dict(&[
("setpoint", Value::from(0.80)),
("mode", Value::from("live")),
])),
)]),
);
let specific = Fixed(
"tenancy",
dict(&[(
"breathe",
Value::from(dict(&[("mode", Value::from("shadow"))])),
)]),
);
let layers: [&dyn DiscoveryLayer; 2] = [&coarse, &specific];
for path in [
&["breathe", "mode"][..],
&["breathe", "setpoint"][..],
&["breathe"][..],
&["absent"][..],
&[][..],
] {
let contributors = contributors_at(&layers, path);
let mut recomposed = silenced_at(&layers, path);
if let Some(&decider) = contributors.last() {
recomposed.push(decider);
}
assert_eq!(
recomposed, contributors,
"silenced_at ⊎ decider != contributors_at at {path:?}",
);
assert_eq!(
silenced_at(&layers, path).len(),
contributors.len().saturating_sub(1),
"silenced_at.len() != contributors_at.len() - 1 at {path:?}",
);
}
}
#[test]
fn silenced_at_excludes_layer_of_winner_when_leaf_survives() {
let coarse = Fixed(
"platform",
dict(&[(
"breathe",
Value::from(dict(&[
("setpoint", Value::from(0.80)),
("mode", Value::from("live")),
])),
)]),
);
let specific = Fixed(
"tenancy",
dict(&[(
"breathe",
Value::from(dict(&[("mode", Value::from("shadow"))])),
)]),
);
let layers: [&dyn DiscoveryLayer; 2] = [&coarse, &specific];
let out = compose_with_provenance(&layers);
let winner = out.attribution.layer_of(&["breathe", "mode"]);
assert_eq!(winner, Some("tenancy"));
let silenced = silenced_at(&layers, &["breathe", "mode"]);
assert_eq!(silenced, vec!["platform"]);
assert!(
!silenced.contains(&"tenancy"),
"winner never appears silenced"
);
let winner = out.attribution.layer_of(&["breathe", "setpoint"]);
assert_eq!(winner, Some("platform"));
assert_eq!(
silenced_at(&layers, &["breathe", "setpoint"]),
Vec::<&'static str>::new(),
);
}
#[test]
fn silenced_at_credits_earlier_writer_when_prefix_scalar_erases_subtree() {
let a = Fixed(
"a",
dict(&[("x", Value::from(dict(&[("a", Value::from(1i64))])))]),
);
let b = Fixed("b", dict(&[("x", Value::from(9i64))]));
assert_eq!(silenced_at(&[&a, &b], &["x", "a"]), vec!["a"]);
let out = compose_with_provenance(&[&a, &b]);
assert_eq!(out.attribution.layer_of(&["x", "a"]), None);
assert_eq!(
contributors_at(&[&a, &b], &["x", "a"]),
vec!["a", "b"],
"contributors_at includes both toucher and erasure decider",
);
}
#[test]
fn silenced_at_at_root_equals_contributor_names_minus_last() {
let coarse = Fixed("platform", dict(&[("a", Value::from(1i64))]));
let silent = Fixed("undetectable", Dict::new());
let middle = Fixed("cloud", dict(&[("c", Value::from(3i64))]));
let specific = Fixed("tenancy", dict(&[("b", Value::from(2i64))]));
let layers: [&dyn DiscoveryLayer; 4] = [&coarse, &silent, &middle, &specific];
let mut expected = contributor_names(&layers);
expected.pop();
assert_eq!(silenced_at(&layers, &[]), expected);
assert_eq!(silenced_at(&layers, &[]), vec!["platform", "cloud"]);
}
#[test]
fn silenced_at_is_subset_of_contributors_at() {
let a = Fixed("a", dict(&[("k", Value::from(1i64))]));
let b = Fixed("b", dict(&[("k", Value::from(2i64))]));
let c = Fixed("c", dict(&[("other", Value::from(3i64))]));
let silent = Fixed("silent", Dict::new());
let layers: [&dyn DiscoveryLayer; 4] = [&a, &b, &c, &silent];
for path in [&["k"][..], &["other"][..], &["nope"][..], &[][..]] {
let contributors: std::collections::BTreeSet<_> =
contributors_at(&layers, path).into_iter().collect();
let silenced: std::collections::BTreeSet<_> =
silenced_at(&layers, path).into_iter().collect();
assert!(
silenced.is_subset(&contributors),
"silenced_at({path:?}) = {silenced:?} not ⊆ contributors_at = {contributors:?}",
);
}
}
#[test]
fn decider_at_names_most_specific_toucher() {
let a = Fixed("a", dict(&[("k", Value::from(1i64))]));
let b = Fixed("b", dict(&[("k", Value::from(2i64))]));
let c = Fixed("c", dict(&[("k", Value::from(3i64))]));
let disjoint = Fixed("disjoint", dict(&[("other", Value::from(9i64))]));
assert_eq!(decider_at(&[&a, &b, &c, &disjoint], &["k"]), Some("c"));
}
#[test]
fn decider_at_none_on_no_toucher_and_empty_stack() {
let a = Fixed("a", dict(&[("k", Value::from(1i64))]));
let disjoint = Fixed("z", dict(&[("other", Value::from(9i64))]));
assert_eq!(decider_at(&[&a, &disjoint], &["nope"]), None);
assert_eq!(decider_at(&[], &["k"]), None);
assert_eq!(decider_at(&[], &[]), None);
}
#[test]
fn decider_at_single_toucher_is_that_toucher() {
let a = Fixed("a", dict(&[("k", Value::from(1i64))]));
let disjoint = Fixed("z", dict(&[("other", Value::from(9i64))]));
assert_eq!(decider_at(&[&a, &disjoint], &["k"]), Some("a"));
}
#[test]
fn decider_at_order_sensitivity() {
let a = Fixed("a", dict(&[("k", Value::from(1i64))]));
let b = Fixed("b", dict(&[("k", Value::from(2i64))]));
assert_eq!(decider_at(&[&a, &b], &["k"]), Some("b"));
assert_eq!(decider_at(&[&b, &a], &["k"]), Some("a"));
}
#[test]
fn decider_at_partitions_contributors_at_disjointly_with_silenced_at() {
let coarse = Fixed(
"platform",
dict(&[(
"breathe",
Value::from(dict(&[
("setpoint", Value::from(0.80)),
("mode", Value::from("live")),
])),
)]),
);
let specific = Fixed(
"tenancy",
dict(&[(
"breathe",
Value::from(dict(&[("mode", Value::from("shadow"))])),
)]),
);
let layers: [&dyn DiscoveryLayer; 2] = [&coarse, &specific];
for path in [
&["breathe", "mode"][..],
&["breathe", "setpoint"][..],
&["breathe"][..],
&["absent"][..],
&[][..],
] {
let contributors = contributors_at(&layers, path);
let mut recomposed = silenced_at(&layers, path);
recomposed.extend(decider_at(&layers, path));
assert_eq!(
recomposed, contributors,
"silenced_at ⊎ decider_at != contributors_at at {path:?}",
);
assert_eq!(
decider_at(&layers, path),
contributors.last().copied(),
"decider_at != contributors_at.last() at {path:?}",
);
}
}
#[test]
fn decider_at_agrees_with_layer_of_on_surviving_leaves() {
let coarse = Fixed(
"platform",
dict(&[(
"breathe",
Value::from(dict(&[
("setpoint", Value::from(0.80)),
("mode", Value::from("live")),
])),
)]),
);
let specific = Fixed(
"tenancy",
dict(&[(
"breathe",
Value::from(dict(&[("mode", Value::from("shadow"))])),
)]),
);
let layers: [&dyn DiscoveryLayer; 2] = [&coarse, &specific];
let out = compose_with_provenance(&layers);
for path in [&["breathe", "mode"][..], &["breathe", "setpoint"][..]] {
assert_eq!(
decider_at(&layers, path),
out.attribution.layer_of(path),
"decider_at != layer_of on surviving leaf {path:?}",
);
}
}
#[test]
fn decider_at_names_erasure_agent_when_prefix_scalar_wipes_subtree() {
let a = Fixed(
"a",
dict(&[("x", Value::from(dict(&[("a", Value::from(1i64))])))]),
);
let b = Fixed("b", dict(&[("x", Value::from(9i64))]));
assert_eq!(decider_at(&[&a, &b], &["x", "a"]), Some("b"));
assert_eq!(decider_at(&[&a, &b], &["x"]), Some("b"));
let out = compose_with_provenance(&[&a, &b]);
assert_eq!(out.attribution.layer_of(&["x", "a"]), None);
}
#[test]
fn decider_at_at_root_equals_last_contributor_name() {
let coarse = Fixed("platform", dict(&[("a", Value::from(1i64))]));
let silent = Fixed("undetectable", Dict::new());
let middle = Fixed("cloud", dict(&[("c", Value::from(3i64))]));
let specific = Fixed("tenancy", dict(&[("b", Value::from(2i64))]));
let layers: [&dyn DiscoveryLayer; 4] = [&coarse, &silent, &middle, &specific];
assert_eq!(
decider_at(&layers, &[]),
contributor_names(&layers).last().copied(),
);
assert_eq!(decider_at(&layers, &[]), Some("tenancy"));
}
#[test]
fn decider_at_matches_contributors_at_last_across_all_path_shapes() {
let a = Fixed(
"a",
dict(&[("x", Value::from(dict(&[("a", Value::from(1i64))])))]),
);
let b = Fixed("b", dict(&[("x", Value::from(9i64))]));
let c = Fixed("c", dict(&[("k", Value::from(3i64))]));
let d = Fixed("d", dict(&[("k", Value::from(4i64))]));
let layers: [&dyn DiscoveryLayer; 4] = [&a, &b, &c, &d];
for path in [
&["k"][..],
&["x"][..],
&["x", "a"][..],
&["nope"][..],
&[][..],
] {
assert_eq!(
decider_at(&layers, path),
contributors_at(&layers, path).last().copied(),
"decider_at != contributors_at.last() at {path:?}",
);
}
}
#[test]
fn contest_at_none_on_no_toucher_and_empty_stack() {
let a = Fixed("a", dict(&[("k", Value::from(1i64))]));
let disjoint = Fixed("z", dict(&[("other", Value::from(9i64))]));
assert_eq!(contest_at(&[&a, &disjoint], &["nope"]), None);
assert_eq!(contest_at(&[], &["k"]), None);
assert_eq!(contest_at(&[], &[]), None);
}
#[test]
fn contest_at_single_toucher_is_uncontested_with_that_decider() {
let a = Fixed("a", dict(&[("k", Value::from(1i64))]));
let disjoint = Fixed("z", dict(&[("other", Value::from(9i64))]));
let contest = contest_at(&[&a, &disjoint], &["k"]).expect("some toucher");
assert_eq!(contest.decider, "a");
assert!(contest.overridden.is_empty(), "no override contest");
assert!(!contest.is_contested(), "single toucher is not contested");
assert_eq!(contest.contributor_count(), 1);
}
#[test]
fn contest_at_lists_overridden_in_application_order() {
let a = Fixed("a", dict(&[("k", Value::from(1i64))]));
let b = Fixed("b", dict(&[("k", Value::from(2i64))]));
let c = Fixed("c", dict(&[("k", Value::from(3i64))]));
let disjoint = Fixed("disjoint", dict(&[("other", Value::from(9i64))]));
let contest = contest_at(&[&a, &b, &c, &disjoint], &["k"]).expect("some toucher");
assert_eq!(contest.decider, "c");
assert_eq!(contest.overridden, vec!["a", "b"]);
assert!(contest.is_contested());
assert_eq!(contest.contributor_count(), 3);
}
#[test]
fn contest_at_covers_erasure_case() {
let a = Fixed(
"a",
dict(&[("x", Value::from(dict(&[("a", Value::from(1i64))])))]),
);
let b = Fixed("b", dict(&[("x", Value::from(9i64))]));
let contest = contest_at(&[&a, &b], &["x", "a"]).expect("erasure decider is a toucher");
assert_eq!(
contest.decider, "b",
"erasure agent decides the erased path"
);
assert_eq!(contest.overridden, vec!["a"]);
let out = compose_with_provenance(&[&a, &b]);
assert_eq!(out.attribution.layer_of(&["x", "a"]), None);
}
#[test]
fn contest_at_projections_match_decider_and_silenced_axes() {
let coarse = Fixed(
"platform",
dict(&[(
"breathe",
Value::from(dict(&[
("setpoint", Value::from(0.80)),
("mode", Value::from("live")),
])),
)]),
);
let specific = Fixed(
"tenancy",
dict(&[(
"breathe",
Value::from(dict(&[("mode", Value::from("shadow"))])),
)]),
);
let layers: [&dyn DiscoveryLayer; 2] = [&coarse, &specific];
for path in [
&["breathe", "mode"][..],
&["breathe", "setpoint"][..],
&["breathe"][..],
&["absent"][..],
&[][..],
] {
let contest = contest_at(&layers, path);
assert_eq!(
contest.as_ref().map(|c| c.decider),
decider_at(&layers, path),
"contest.decider != decider_at at {path:?}",
);
match &contest {
Some(c) => assert_eq!(
c.overridden,
silenced_at(&layers, path),
"contest.overridden != silenced_at at {path:?}",
),
None => assert!(
silenced_at(&layers, path).is_empty()
&& contributors_at(&layers, path).is_empty(),
"contest_at is None but touchers exist at {path:?}",
),
}
}
}
#[test]
fn contest_at_reconstructs_contributors_at() {
let coarse = Fixed(
"platform",
dict(&[(
"breathe",
Value::from(dict(&[
("setpoint", Value::from(0.80)),
("mode", Value::from("live")),
])),
)]),
);
let middle = Fixed(
"cloud",
dict(&[(
"breathe",
Value::from(dict(&[("mode", Value::from("staging"))])),
)]),
);
let specific = Fixed(
"tenancy",
dict(&[(
"breathe",
Value::from(dict(&[("mode", Value::from("shadow"))])),
)]),
);
let layers: [&dyn DiscoveryLayer; 3] = [&coarse, &middle, &specific];
for path in [
&["breathe", "mode"][..],
&["breathe", "setpoint"][..],
&["breathe"][..],
&["absent"][..],
&[][..],
] {
let contributors = contributors_at(&layers, path);
let recomposed = contest_at(&layers, path).map_or_else(Vec::new, |c| {
let mut v = c.overridden.clone();
v.push(c.decider);
v
});
assert_eq!(
recomposed, contributors,
"reconstructed != contributors_at at {path:?}",
);
}
}
#[test]
fn contest_at_contributor_count_matches_contributors_at_len() {
let a = Fixed("a", dict(&[("k", Value::from(1i64))]));
let b = Fixed("b", dict(&[("k", Value::from(2i64))]));
let c = Fixed("c", dict(&[("other", Value::from(3i64))]));
let silent = Fixed("silent", Dict::new());
let layers: [&dyn DiscoveryLayer; 4] = [&a, &b, &c, &silent];
for path in [&["k"][..], &["other"][..], &["nope"][..], &[][..]] {
assert_eq!(
contest_at(&layers, path).map_or(0, |c| c.contributor_count()),
contributors_at(&layers, path).len(),
"contributor_count != contributors_at.len() at {path:?}",
);
}
}
#[test]
fn contest_at_is_contested_iff_silenced_non_empty() {
let a = Fixed("a", dict(&[("k", Value::from(1i64))]));
let b = Fixed("b", dict(&[("k", Value::from(2i64))]));
let c = Fixed("c", dict(&[("other", Value::from(3i64))]));
let layers: [&dyn DiscoveryLayer; 3] = [&a, &b, &c];
for path in [&["k"][..], &["other"][..], &["nope"][..], &[][..]] {
let contested_via_fused = contest_at(&layers, path).is_some_and(|c| c.is_contested());
let contested_via_loose = !silenced_at(&layers, path).is_empty();
assert_eq!(
contested_via_fused, contested_via_loose,
"is_contested() != !silenced_at.is_empty() at {path:?}",
);
}
}
#[test]
fn contest_at_root_boundary() {
let coarse = Fixed("platform", dict(&[("a", Value::from(1i64))]));
let silent = Fixed("undetectable", Dict::new());
let middle = Fixed("cloud", dict(&[("c", Value::from(3i64))]));
let specific = Fixed("tenancy", dict(&[("b", Value::from(2i64))]));
let layers: [&dyn DiscoveryLayer; 4] = [&coarse, &silent, &middle, &specific];
let contest = contest_at(&layers, &[]).expect("some non-empty layer at root");
assert_eq!(contest.decider, "tenancy");
assert_eq!(contest.overridden, vec!["platform", "cloud"]);
let mut expected_overridden = contributor_names(&layers);
expected_overridden.pop();
assert_eq!(contest.overridden, expected_overridden);
}
#[test]
fn contest_at_agrees_with_layer_of_on_surviving_leaves() {
let coarse = Fixed(
"platform",
dict(&[(
"breathe",
Value::from(dict(&[
("setpoint", Value::from(0.80)),
("mode", Value::from("live")),
])),
)]),
);
let specific = Fixed(
"tenancy",
dict(&[(
"breathe",
Value::from(dict(&[("mode", Value::from("shadow"))])),
)]),
);
let layers: [&dyn DiscoveryLayer; 2] = [&coarse, &specific];
let out = compose_with_provenance(&layers);
for path in [&["breathe", "mode"][..], &["breathe", "setpoint"][..]] {
let contest = contest_at(&layers, path).expect("surviving leaf has toucher");
assert_eq!(
Some(contest.decider),
out.attribution.layer_of(path),
"contest.decider != layer_of on surviving leaf {path:?}",
);
}
}
#[test]
fn path_contest_contributors_uncontested_returns_singleton_decider() {
let contest = PathContest {
decider: "solo",
overridden: vec![],
};
assert_eq!(contest.contributors(), vec!["solo"]);
assert!(!contest.is_contested());
assert_eq!(contest.contributors().len(), 1);
assert_eq!(contest.contributors().len(), contest.contributor_count());
}
#[test]
fn path_contest_contributors_three_writers_ordered_coarse_to_specific() {
let platform = Fixed(
"platform",
dict(&[(
"breathe",
Value::from(dict(&[("mode", Value::from("live"))])),
)]),
);
let cloud = Fixed(
"cloud",
dict(&[(
"breathe",
Value::from(dict(&[("mode", Value::from("aws"))])),
)]),
);
let tenancy = Fixed(
"tenancy",
dict(&[(
"breathe",
Value::from(dict(&[("mode", Value::from("prod"))])),
)]),
);
let disjoint = Fixed("logger", dict(&[("logger", Value::from("info"))]));
let layers: [&dyn DiscoveryLayer; 4] = [&platform, &cloud, &tenancy, &disjoint];
let contest = contest_at(&layers, &["breathe", "mode"]).expect("three touchers");
assert_eq!(
contest.contributors(),
vec!["platform", "cloud", "tenancy"],
"contributors() enumerates touchers coarse→specific",
);
}
#[test]
fn path_contest_contributors_matches_contributors_at() {
let a = Fixed(
"a",
dict(&[(
"breathe",
Value::from(dict(&[
("mode", Value::from("live")),
("setpoint", Value::from(0.80)),
])),
)]),
);
let b = Fixed(
"b",
dict(&[(
"breathe",
Value::from(dict(&[("mode", Value::from("shadow"))])),
)]),
);
let c = Fixed("c", dict(&[("logger", Value::from("info"))]));
let layers: [&dyn DiscoveryLayer; 3] = [&a, &b, &c];
for path in [
&[][..],
&["breathe"][..],
&["breathe", "mode"][..],
&["breathe", "setpoint"][..],
&["logger"][..],
&["absent"][..],
] {
let expected = contributors_at(&layers, path);
let via_fused = contest_at(&layers, path).map_or_else(Vec::new, |c| c.contributors());
assert_eq!(
via_fused, expected,
"contest.contributors() != contributors_at at {path:?}",
);
}
}
#[test]
fn path_contest_contributors_len_matches_contributor_count() {
let a = Fixed(
"a",
dict(&[("k", Value::from(dict(&[("leaf", Value::from(1i64))])))]),
);
let b = Fixed("b", dict(&[("k", Value::from("erased"))]));
let c = Fixed(
"c",
dict(&[("k", Value::from(dict(&[("leaf", Value::from(3i64))])))]),
);
let layers: [&dyn DiscoveryLayer; 3] = [&a, &b, &c];
for path in [&[][..], &["k"][..], &["k", "leaf"][..], &["absent"][..]] {
let expected = contributors_at(&layers, path).len();
let via_contributors = contest_at(&layers, path).map_or(0, |c| c.contributors().len());
let via_count = contest_at(&layers, path).map_or(0, |c| c.contributor_count());
assert_eq!(via_contributors, expected, "len mismatch at {path:?}");
assert_eq!(via_count, expected, "count mismatch at {path:?}");
}
}
#[test]
fn path_contest_contributors_trailing_element_is_decider() {
let a = Fixed(
"a",
dict(&[(
"breathe",
Value::from(dict(&[("mode", Value::from("live"))])),
)]),
);
let b = Fixed(
"b",
dict(&[(
"breathe",
Value::from(dict(&[("mode", Value::from("shadow"))])),
)]),
);
let c = Fixed(
"c",
dict(&[(
"breathe",
Value::from(dict(&[("mode", Value::from("prod"))])),
)]),
);
let layers: [&dyn DiscoveryLayer; 3] = [&a, &b, &c];
for path in [&["breathe"][..], &["breathe", "mode"][..], &[][..]] {
let contest = contest_at(&layers, path).expect("some toucher");
let contributors = contest.contributors();
assert_eq!(
contributors.last().copied(),
Some(contest.decider),
"trailing element != decider at {path:?}",
);
}
}
#[test]
fn path_contest_contributors_leading_prefix_is_overridden() {
let a = Fixed(
"a",
dict(&[(
"breathe",
Value::from(dict(&[("mode", Value::from("live"))])),
)]),
);
let b = Fixed(
"b",
dict(&[(
"breathe",
Value::from(dict(&[("mode", Value::from("shadow"))])),
)]),
);
let c = Fixed(
"c",
dict(&[(
"breathe",
Value::from(dict(&[("mode", Value::from("prod"))])),
)]),
);
let layers: [&dyn DiscoveryLayer; 3] = [&a, &b, &c];
for path in [&["breathe"][..], &["breathe", "mode"][..], &[][..]] {
let contest = contest_at(&layers, path).expect("some toucher");
let contributors = contest.contributors();
let leading = &contributors[..contest.overridden.len()];
assert_eq!(
leading,
contest.overridden.as_slice(),
"leading prefix != overridden at {path:?}",
);
}
}
#[test]
fn path_contest_contributors_covers_erasure_case() {
let a = Fixed(
"a",
dict(&[("k", Value::from(dict(&[("leaf", Value::from(1i64))])))]),
);
let b = Fixed("b", dict(&[("k", Value::from("erased"))]));
let layers: [&dyn DiscoveryLayer; 2] = [&a, &b];
let contest = contest_at(&layers, &["k", "leaf"]).expect("erasure decider is a toucher");
assert_eq!(contest.contributors(), vec!["a", "b"]);
assert_eq!(contest.decider, "b");
assert_eq!(contest.overridden, vec!["a"]);
}
#[test]
fn path_contest_coarsest_uncontested_singleton_equals_decider() {
let contest = PathContest {
decider: "solo",
overridden: vec![],
};
assert_eq!(contest.coarsest(), "solo");
assert_eq!(contest.coarsest(), contest.decider);
assert!(!contest.is_contested());
}
#[test]
fn path_contest_coarsest_three_writers_returns_leading_overridden() {
let platform = Fixed(
"platform",
dict(&[(
"breathe",
Value::from(dict(&[("mode", Value::from("live"))])),
)]),
);
let cloud = Fixed(
"cloud",
dict(&[(
"breathe",
Value::from(dict(&[("mode", Value::from("aws"))])),
)]),
);
let tenancy = Fixed(
"tenancy",
dict(&[(
"breathe",
Value::from(dict(&[("mode", Value::from("prod"))])),
)]),
);
let disjoint = Fixed("logger", dict(&[("logger", Value::from("info"))]));
let layers: [&dyn DiscoveryLayer; 4] = [&platform, &cloud, &tenancy, &disjoint];
let contest = contest_at(&layers, &["breathe", "mode"]).expect("three touchers");
assert_eq!(contest.coarsest(), "platform");
assert_eq!(contest.decider, "tenancy");
assert_ne!(contest.coarsest(), contest.decider);
assert_eq!(
contest.coarsest(),
contest.overridden[0],
"coarsest is the leading overridden entry when contested",
);
}
#[test]
fn path_contest_coarsest_matches_contributors_first() {
let a = Fixed(
"a",
dict(&[(
"breathe",
Value::from(dict(&[
("mode", Value::from("live")),
("setpoint", Value::from(0.80)),
])),
)]),
);
let b = Fixed(
"b",
dict(&[(
"breathe",
Value::from(dict(&[("mode", Value::from("shadow"))])),
)]),
);
let c = Fixed("c", dict(&[("logger", Value::from("info"))]));
let layers: [&dyn DiscoveryLayer; 3] = [&a, &b, &c];
for path in [
&[][..],
&["breathe"][..],
&["breathe", "mode"][..],
&["breathe", "setpoint"][..],
&["logger"][..],
] {
let contest = contest_at(&layers, path).expect("some toucher");
let leading = contest
.contributors()
.first()
.copied()
.expect("contest is non-empty");
assert_eq!(
contest.coarsest(),
leading,
"coarsest() != contributors().first() at {path:?}",
);
}
}
#[test]
fn path_contest_coarsest_matches_contributors_at_first() {
let coarse = Fixed(
"platform",
dict(&[(
"breathe",
Value::from(dict(&[
("setpoint", Value::from(0.80)),
("mode", Value::from("live")),
])),
)]),
);
let middle = Fixed(
"cloud",
dict(&[(
"breathe",
Value::from(dict(&[("mode", Value::from("staging"))])),
)]),
);
let specific = Fixed(
"tenancy",
dict(&[(
"breathe",
Value::from(dict(&[("mode", Value::from("shadow"))])),
)]),
);
let layers: [&dyn DiscoveryLayer; 3] = [&coarse, &middle, &specific];
for path in [
&["breathe", "mode"][..],
&["breathe", "setpoint"][..],
&["breathe"][..],
&["absent"][..],
&[][..],
] {
let via_fused = contest_at(&layers, path).map(|c| c.coarsest());
let via_loose = contributors_at(&layers, path).first().copied();
assert_eq!(
via_fused, via_loose,
"coarsest() != contributors_at.first() at {path:?}",
);
}
}
#[test]
fn path_contest_coarsest_equals_decider_iff_uncontested() {
let a = Fixed(
"a",
dict(&[
("solo", Value::from(1i64)),
(
"breathe",
Value::from(dict(&[("mode", Value::from("live"))])),
),
]),
);
let b = Fixed(
"b",
dict(&[(
"breathe",
Value::from(dict(&[("mode", Value::from("shadow"))])),
)]),
);
let layers: [&dyn DiscoveryLayer; 2] = [&a, &b];
for path in [
&["solo"][..], &["breathe"][..], &["breathe", "mode"][..], ] {
let contest = contest_at(&layers, path).expect("some toucher");
let uncontested = !contest.is_contested();
let coarsest_is_decider = contest.coarsest() == contest.decider;
assert_eq!(
uncontested, coarsest_is_decider,
"!is_contested() != (coarsest == decider) at {path:?}",
);
}
}
#[test]
fn path_contest_coarsest_covers_erasure_case() {
let a = Fixed(
"a",
dict(&[("k", Value::from(dict(&[("leaf", Value::from(1i64))])))]),
);
let b = Fixed("b", dict(&[("k", Value::from("erased"))]));
let layers: [&dyn DiscoveryLayer; 2] = [&a, &b];
let contest = contest_at(&layers, &["k", "leaf"]).expect("erasure decider is a toucher");
assert_eq!(contest.coarsest(), "a");
assert_eq!(contest.decider, "b");
assert_ne!(contest.coarsest(), contest.decider);
}
#[test]
fn path_contest_coarsest_root_boundary() {
let coarse = Fixed("platform", dict(&[("a", Value::from(1i64))]));
let silent = Fixed("undetectable", Dict::new());
let middle = Fixed("cloud", dict(&[("c", Value::from(3i64))]));
let specific = Fixed("tenancy", dict(&[("b", Value::from(2i64))]));
let layers: [&dyn DiscoveryLayer; 4] = [&coarse, &silent, &middle, &specific];
let contest = contest_at(&layers, &[]).expect("some non-empty layer at root");
let names = contributor_names(&layers);
assert_eq!(
contest.coarsest(),
*names.first().expect("some contributor"),
"root coarsest is first contributor_name",
);
assert_eq!(
contest.decider,
*names.last().expect("some contributor"),
"root decider is last contributor_name",
);
assert_eq!(contest.coarsest(), "platform");
assert_eq!(contest.decider, "tenancy");
}
#[test]
fn coarsest_at_none_boundary_matches_decider_at_and_contributors_at() {
let a = Fixed("a", dict(&[("k", Value::from(1i64))]));
let b = Fixed("b", dict(&[("k", Value::from(2i64))]));
let layers: [&dyn DiscoveryLayer; 2] = [&a, &b];
assert_eq!(coarsest_at(&layers, &["absent"]), None);
assert_eq!(decider_at(&layers, &["absent"]), None);
assert!(contributors_at(&layers, &["absent"]).is_empty());
assert!(contest_at(&layers, &["absent"]).is_none());
let empty: [&dyn DiscoveryLayer; 0] = [];
assert_eq!(coarsest_at(&empty, &[]), None);
assert_eq!(decider_at(&empty, &[]), None);
}
#[test]
fn coarsest_at_matches_contributors_at_first_across_paths() {
let a = Fixed(
"a",
dict(&[(
"breathe",
Value::from(dict(&[
("mode", Value::from("live")),
("setpoint", Value::from(0.80)),
])),
)]),
);
let b = Fixed(
"b",
dict(&[(
"breathe",
Value::from(dict(&[("mode", Value::from("shadow"))])),
)]),
);
let c = Fixed("c", dict(&[("logger", Value::from("info"))]));
let layers: [&dyn DiscoveryLayer; 3] = [&a, &b, &c];
for path in [
&[][..],
&["breathe"][..],
&["breathe", "mode"][..],
&["breathe", "setpoint"][..],
&["logger"][..],
&["absent"][..],
] {
let via_primitive = coarsest_at(&layers, path);
let via_loose = contributors_at(&layers, path).first().copied();
assert_eq!(
via_primitive, via_loose,
"coarsest_at != contributors_at.first() at {path:?}",
);
}
}
#[test]
fn coarsest_at_matches_contest_at_coarsest_across_paths() {
let coarse = Fixed(
"platform",
dict(&[(
"breathe",
Value::from(dict(&[
("setpoint", Value::from(0.80)),
("mode", Value::from("live")),
])),
)]),
);
let middle = Fixed(
"cloud",
dict(&[(
"breathe",
Value::from(dict(&[("mode", Value::from("staging"))])),
)]),
);
let specific = Fixed(
"tenancy",
dict(&[(
"breathe",
Value::from(dict(&[("mode", Value::from("shadow"))])),
)]),
);
let layers: [&dyn DiscoveryLayer; 3] = [&coarse, &middle, &specific];
for path in [
&["breathe", "mode"][..],
&["breathe", "setpoint"][..],
&["breathe"][..],
&["absent"][..],
&[][..],
] {
let via_primitive = coarsest_at(&layers, path);
let via_fused = contest_at(&layers, path).map(|c| c.coarsest());
assert_eq!(
via_primitive, via_fused,
"coarsest_at != contest_at.map(|c| c.coarsest()) at {path:?}",
);
}
}
#[test]
fn coarsest_at_three_writers_returns_leading_toucher() {
let platform = Fixed(
"platform",
dict(&[(
"breathe",
Value::from(dict(&[("mode", Value::from("live"))])),
)]),
);
let cloud = Fixed(
"cloud",
dict(&[(
"breathe",
Value::from(dict(&[("mode", Value::from("aws"))])),
)]),
);
let tenancy = Fixed(
"tenancy",
dict(&[(
"breathe",
Value::from(dict(&[("mode", Value::from("prod"))])),
)]),
);
let disjoint = Fixed("logger", dict(&[("logger", Value::from("info"))]));
let layers: [&dyn DiscoveryLayer; 4] = [&platform, &cloud, &tenancy, &disjoint];
assert_eq!(coarsest_at(&layers, &["breathe", "mode"]), Some("platform"));
assert_eq!(decider_at(&layers, &["breathe", "mode"]), Some("tenancy"));
assert_ne!(
coarsest_at(&layers, &["breathe", "mode"]),
decider_at(&layers, &["breathe", "mode"]),
);
}
#[test]
fn coarsest_at_equals_decider_at_iff_at_most_one_toucher() {
let a = Fixed(
"a",
dict(&[
("solo", Value::from(1i64)),
(
"breathe",
Value::from(dict(&[("mode", Value::from("live"))])),
),
]),
);
let b = Fixed(
"b",
dict(&[(
"breathe",
Value::from(dict(&[("mode", Value::from("shadow"))])),
)]),
);
let layers: [&dyn DiscoveryLayer; 2] = [&a, &b];
for path in [
&["solo"][..], &["absent"][..], &["breathe"][..], &["breathe", "mode"][..], ] {
let coarsest = coarsest_at(&layers, path);
let decider = decider_at(&layers, path);
let at_most_one = contributors_at(&layers, path).len() <= 1;
assert_eq!(
coarsest == decider,
at_most_one,
"coarsest_at == decider_at != (contributors_at.len() <= 1) at {path:?}",
);
}
}
#[test]
fn coarsest_at_covers_prefix_scalar_erasure() {
let a = Fixed(
"a",
dict(&[("k", Value::from(dict(&[("leaf", Value::from(1i64))])))]),
);
let b = Fixed("b", dict(&[("k", Value::from("erased"))]));
let layers: [&dyn DiscoveryLayer; 2] = [&a, &b];
assert_eq!(coarsest_at(&layers, &["k", "leaf"]), Some("a"));
assert_eq!(decider_at(&layers, &["k", "leaf"]), Some("b"));
assert_ne!(
coarsest_at(&layers, &["k", "leaf"]),
decider_at(&layers, &["k", "leaf"]),
);
}
#[test]
fn coarsest_at_root_boundary_equals_first_contributor_name() {
let coarse = Fixed("platform", dict(&[("a", Value::from(1i64))]));
let silent = Fixed("undetectable", Dict::new());
let middle = Fixed("cloud", dict(&[("c", Value::from(3i64))]));
let specific = Fixed("tenancy", dict(&[("b", Value::from(2i64))]));
let layers: [&dyn DiscoveryLayer; 4] = [&coarse, &silent, &middle, &specific];
let names = contributor_names(&layers);
assert_eq!(coarsest_at(&layers, &[]), names.first().copied());
assert_eq!(decider_at(&layers, &[]), names.last().copied());
assert_eq!(coarsest_at(&layers, &[]), Some("platform"));
assert_eq!(decider_at(&layers, &[]), Some("tenancy"));
}
#[test]
fn is_contested_at_false_boundary_on_zero_or_one_toucher() {
let a = Fixed(
"a",
dict(&[
("solo", Value::from(1i64)),
(
"breathe",
Value::from(dict(&[("mode", Value::from("live"))])),
),
]),
);
let b = Fixed("b", dict(&[("logger", Value::from("info"))]));
let layers: [&dyn DiscoveryLayer; 2] = [&a, &b];
assert!(!is_contested_at(&layers, &["absent"]));
assert!(!is_contested_at(&layers, &["solo"]));
assert!(!is_contested_at(&layers, &["breathe"]));
assert!(!is_contested_at(&layers, &["breathe", "mode"]));
assert!(!is_contested_at(&layers, &["logger"]));
let empty: [&dyn DiscoveryLayer; 0] = [];
assert!(!is_contested_at(&empty, &[]));
assert!(!is_contested_at(&empty, &["absent"]));
}
#[test]
fn is_contested_at_matches_silenced_non_empty_across_paths() {
let a = Fixed(
"a",
dict(&[(
"breathe",
Value::from(dict(&[
("mode", Value::from("live")),
("setpoint", Value::from(0.80)),
])),
)]),
);
let b = Fixed(
"b",
dict(&[(
"breathe",
Value::from(dict(&[("mode", Value::from("shadow"))])),
)]),
);
let c = Fixed("c", dict(&[("logger", Value::from("info"))]));
let layers: [&dyn DiscoveryLayer; 3] = [&a, &b, &c];
for path in [
&[][..],
&["breathe"][..],
&["breathe", "mode"][..],
&["breathe", "setpoint"][..],
&["logger"][..],
&["absent"][..],
] {
let via_primitive = is_contested_at(&layers, path);
let via_loose = !silenced_at(&layers, path).is_empty();
assert_eq!(
via_primitive, via_loose,
"is_contested_at != !silenced_at.is_empty() at {path:?}",
);
}
}
#[test]
fn is_contested_at_matches_contest_at_is_contested_across_paths() {
let coarse = Fixed(
"platform",
dict(&[(
"breathe",
Value::from(dict(&[
("setpoint", Value::from(0.80)),
("mode", Value::from("live")),
])),
)]),
);
let middle = Fixed(
"cloud",
dict(&[(
"breathe",
Value::from(dict(&[("mode", Value::from("staging"))])),
)]),
);
let specific = Fixed(
"tenancy",
dict(&[(
"breathe",
Value::from(dict(&[("mode", Value::from("shadow"))])),
)]),
);
let layers: [&dyn DiscoveryLayer; 3] = [&coarse, &middle, &specific];
for path in [
&["breathe", "mode"][..],
&["breathe", "setpoint"][..],
&["breathe"][..],
&["absent"][..],
&[][..],
] {
let via_primitive = is_contested_at(&layers, path);
let via_fused = contest_at(&layers, path).is_some_and(|c| c.is_contested());
assert_eq!(
via_primitive, via_fused,
"is_contested_at != contest_at.is_some_and(is_contested) at {path:?}",
);
}
}
#[test]
fn is_contested_at_matches_contributors_len_ge_two_across_paths() {
let a = Fixed(
"a",
dict(&[(
"breathe",
Value::from(dict(&[
("mode", Value::from("live")),
("setpoint", Value::from(0.80)),
])),
)]),
);
let b = Fixed(
"b",
dict(&[(
"breathe",
Value::from(dict(&[("mode", Value::from("shadow"))])),
)]),
);
let c = Fixed("c", dict(&[("logger", Value::from("info"))]));
let layers: [&dyn DiscoveryLayer; 3] = [&a, &b, &c];
for path in [
&[][..],
&["breathe"][..],
&["breathe", "mode"][..],
&["breathe", "setpoint"][..],
&["logger"][..],
&["absent"][..],
] {
let via_primitive = is_contested_at(&layers, path);
let via_len = contributors_at(&layers, path).len() >= 2;
assert_eq!(
via_primitive, via_len,
"is_contested_at != contributors_at.len() >= 2 at {path:?}",
);
}
}
#[test]
fn is_contested_at_matches_endpoint_inequality_across_paths() {
let a = Fixed(
"a",
dict(&[
("solo", Value::from(1i64)),
(
"breathe",
Value::from(dict(&[("mode", Value::from("live"))])),
),
]),
);
let b = Fixed(
"b",
dict(&[(
"breathe",
Value::from(dict(&[("mode", Value::from("shadow"))])),
)]),
);
let layers: [&dyn DiscoveryLayer; 2] = [&a, &b];
for path in [
&["solo"][..], &["absent"][..], &["breathe"][..], &["breathe", "mode"][..], ] {
let via_primitive = is_contested_at(&layers, path);
let via_endpoints = coarsest_at(&layers, path) != decider_at(&layers, path);
assert_eq!(
via_primitive, via_endpoints,
"is_contested_at != (coarsest_at != decider_at) at {path:?}",
);
}
}
#[test]
fn is_contested_at_covers_prefix_scalar_erasure() {
let a = Fixed(
"a",
dict(&[("k", Value::from(dict(&[("leaf", Value::from(1i64))])))]),
);
let b = Fixed("b", dict(&[("k", Value::from("erased"))]));
let layers: [&dyn DiscoveryLayer; 2] = [&a, &b];
assert!(is_contested_at(&layers, &["k", "leaf"]));
assert_eq!(coarsest_at(&layers, &["k", "leaf"]), Some("a"));
assert_eq!(decider_at(&layers, &["k", "leaf"]), Some("b"));
}
#[test]
fn is_contested_at_root_boundary_filters_silent_layers() {
let coarse = Fixed("platform", dict(&[("a", Value::from(1i64))]));
let silent = Fixed("undetectable", Dict::new());
let middle = Fixed("cloud", dict(&[("c", Value::from(3i64))]));
let specific = Fixed("tenancy", dict(&[("b", Value::from(2i64))]));
let layers_four: [&dyn DiscoveryLayer; 4] = [&coarse, &silent, &middle, &specific];
assert!(is_contested_at(&layers_four, &[]));
let layers_one: [&dyn DiscoveryLayer; 2] = [&coarse, &silent];
assert!(!is_contested_at(&layers_one, &[]));
let layers_zero: [&dyn DiscoveryLayer; 2] = [&silent, &silent];
assert!(!is_contested_at(&layers_zero, &[]));
}
#[test]
fn contributor_count_at_matches_contributors_len_across_paths() {
let a = Fixed(
"a",
dict(&[(
"breathe",
Value::from(dict(&[
("mode", Value::from("live")),
("setpoint", Value::from(0.80)),
])),
)]),
);
let b = Fixed(
"b",
dict(&[(
"breathe",
Value::from(dict(&[("mode", Value::from("shadow"))])),
)]),
);
let c = Fixed("c", dict(&[("logger", Value::from("info"))]));
let layers: [&dyn DiscoveryLayer; 3] = [&a, &b, &c];
for path in [
&[][..],
&["breathe"][..],
&["breathe", "mode"][..],
&["breathe", "setpoint"][..],
&["logger"][..],
&["absent"][..],
] {
let via_primitive = contributor_count_at(&layers, path);
let via_len = contributors_at(&layers, path).len();
assert_eq!(
via_primitive, via_len,
"contributor_count_at != contributors_at.len() at {path:?}",
);
}
}
#[test]
fn contributor_count_at_matches_contest_at_contributor_count_across_paths() {
let coarse = Fixed(
"platform",
dict(&[(
"breathe",
Value::from(dict(&[
("setpoint", Value::from(0.80)),
("mode", Value::from("live")),
])),
)]),
);
let middle = Fixed(
"cloud",
dict(&[(
"breathe",
Value::from(dict(&[("mode", Value::from("staging"))])),
)]),
);
let specific = Fixed(
"tenancy",
dict(&[(
"breathe",
Value::from(dict(&[("mode", Value::from("shadow"))])),
)]),
);
let layers: [&dyn DiscoveryLayer; 3] = [&coarse, &middle, &specific];
for path in [
&["breathe", "mode"][..],
&["breathe", "setpoint"][..],
&["breathe"][..],
&["absent"][..],
&[][..],
] {
let via_primitive = contributor_count_at(&layers, path);
let via_fused = contest_at(&layers, path).map_or(0, |c| c.contributor_count());
assert_eq!(
via_primitive, via_fused,
"contributor_count_at != contest_at.map_or(0, contributor_count) at {path:?}",
);
}
}
#[test]
fn contributor_count_at_matches_partition_across_paths() {
let a = Fixed(
"a",
dict(&[
("solo", Value::from(1i64)),
(
"breathe",
Value::from(dict(&[("mode", Value::from("live"))])),
),
]),
);
let b = Fixed(
"b",
dict(&[(
"breathe",
Value::from(dict(&[("mode", Value::from("shadow"))])),
)]),
);
let c = Fixed("c", dict(&[("logger", Value::from("info"))]));
let layers: [&dyn DiscoveryLayer; 3] = [&a, &b, &c];
for path in [
&[][..],
&["solo"][..],
&["breathe"][..],
&["breathe", "mode"][..],
&["logger"][..],
&["absent"][..],
] {
let via_primitive = contributor_count_at(&layers, path);
let via_partition =
silenced_at(&layers, path).len() + usize::from(decider_at(&layers, path).is_some());
assert_eq!(
via_primitive, via_partition,
"contributor_count_at != silenced_at.len() + decider_at.is_some() at {path:?}",
);
}
}
#[test]
fn contributor_count_at_matches_is_contested_threshold_across_paths() {
let a = Fixed(
"a",
dict(&[
("solo", Value::from(1i64)),
(
"breathe",
Value::from(dict(&[("mode", Value::from("live"))])),
),
]),
);
let b = Fixed(
"b",
dict(&[(
"breathe",
Value::from(dict(&[("mode", Value::from("shadow"))])),
)]),
);
let layers: [&dyn DiscoveryLayer; 2] = [&a, &b];
for path in [
&["solo"][..],
&["absent"][..],
&["breathe"][..],
&["breathe", "mode"][..],
] {
let via_scalar = contributor_count_at(&layers, path) >= 2;
let via_bool = is_contested_at(&layers, path);
assert_eq!(
via_scalar, via_bool,
"(contributor_count_at >= 2) != is_contested_at at {path:?}",
);
}
}
#[test]
fn contributor_count_at_zero_pins_every_none_endpoint() {
let a = Fixed(
"a",
dict(&[
("solo", Value::from(1i64)),
(
"breathe",
Value::from(dict(&[("mode", Value::from("live"))])),
),
]),
);
let b = Fixed(
"b",
dict(&[(
"breathe",
Value::from(dict(&[("mode", Value::from("shadow"))])),
)]),
);
let layers: [&dyn DiscoveryLayer; 2] = [&a, &b];
for path in [
&["solo"][..],
&["absent"][..],
&["breathe"][..],
&["breathe", "mode"][..],
&[][..],
] {
let zero = contributor_count_at(&layers, path) == 0;
assert_eq!(
zero,
contest_at(&layers, path).is_none(),
"zero != contest_at.is_none() at {path:?}",
);
assert_eq!(
zero,
decider_at(&layers, path).is_none(),
"zero != decider_at.is_none() at {path:?}",
);
assert_eq!(
zero,
coarsest_at(&layers, path).is_none(),
"zero != coarsest_at.is_none() at {path:?}",
);
assert_eq!(
zero,
contributors_at(&layers, path).is_empty(),
"zero != contributors_at.is_empty() at {path:?}",
);
}
let empty: [&dyn DiscoveryLayer; 0] = [];
assert_eq!(contributor_count_at(&empty, &[]), 0);
assert_eq!(contributor_count_at(&empty, &["absent"]), 0);
}
#[test]
fn contributor_count_at_credits_prefix_scalar_erasure_toucher() {
let a = Fixed(
"a",
dict(&[("k", Value::from(dict(&[("leaf", Value::from(1i64))])))]),
);
let b = Fixed("b", dict(&[("k", Value::from("erased"))]));
let layers: [&dyn DiscoveryLayer; 2] = [&a, &b];
assert_eq!(contributor_count_at(&layers, &["k", "leaf"]), 2);
assert_eq!(contributor_count_at(&layers, &["k"]), 2);
}
#[test]
fn contributor_count_at_root_boundary_filters_silent_layers() {
let coarse = Fixed("platform", dict(&[("a", Value::from(1i64))]));
let silent = Fixed("undetectable", Dict::new());
let middle = Fixed("cloud", dict(&[("c", Value::from(3i64))]));
let specific = Fixed("tenancy", dict(&[("b", Value::from(2i64))]));
let layers_four: [&dyn DiscoveryLayer; 4] = [&coarse, &silent, &middle, &specific];
assert_eq!(contributor_count_at(&layers_four, &[]), 3);
let layers_one: [&dyn DiscoveryLayer; 2] = [&coarse, &silent];
assert_eq!(contributor_count_at(&layers_one, &[]), 1);
let layers_zero: [&dyn DiscoveryLayer; 2] = [&silent, &silent];
assert_eq!(contributor_count_at(&layers_zero, &[]), 0);
}
#[test]
fn is_touched_at_matches_contributor_count_ge_one_across_paths() {
let a = Fixed(
"a",
dict(&[
("solo", Value::from(1i64)),
(
"breathe",
Value::from(dict(&[("mode", Value::from("live"))])),
),
]),
);
let b = Fixed(
"b",
dict(&[(
"breathe",
Value::from(dict(&[("mode", Value::from("shadow"))])),
)]),
);
let layers: [&dyn DiscoveryLayer; 2] = [&a, &b];
for path in [
&[][..],
&["solo"][..],
&["absent"][..],
&["breathe"][..],
&["breathe", "mode"][..],
] {
let via_bool = is_touched_at(&layers, path);
let via_scalar = contributor_count_at(&layers, path) >= 1;
assert_eq!(
via_bool, via_scalar,
"is_touched_at != (contributor_count_at >= 1) at {path:?}",
);
}
}
#[test]
fn is_touched_at_pins_every_none_endpoint_across_paths() {
let coarse = Fixed(
"platform",
dict(&[(
"breathe",
Value::from(dict(&[
("setpoint", Value::from(0.80)),
("mode", Value::from("live")),
])),
)]),
);
let specific = Fixed(
"tenancy",
dict(&[(
"breathe",
Value::from(dict(&[("mode", Value::from("shadow"))])),
)]),
);
let layers: [&dyn DiscoveryLayer; 2] = [&coarse, &specific];
for path in [
&[][..],
&["breathe"][..],
&["breathe", "mode"][..],
&["breathe", "setpoint"][..],
&["absent"][..],
&["breathe", "absent"][..],
] {
let touched = is_touched_at(&layers, path);
assert_eq!(
touched,
contest_at(&layers, path).is_some(),
"is_touched_at != contest_at.is_some() at {path:?}",
);
assert_eq!(
touched,
decider_at(&layers, path).is_some(),
"is_touched_at != decider_at.is_some() at {path:?}",
);
assert_eq!(
touched,
coarsest_at(&layers, path).is_some(),
"is_touched_at != coarsest_at.is_some() at {path:?}",
);
assert_eq!(
touched,
!contributors_at(&layers, path).is_empty(),
"is_touched_at != !contributors_at.is_empty() at {path:?}",
);
}
let empty: [&dyn DiscoveryLayer; 0] = [];
assert!(!is_touched_at(&empty, &[]));
assert!(!is_touched_at(&empty, &["absent"]));
}
#[test]
fn is_touched_at_matches_monotonic_chain_against_is_contested_at() {
let a = Fixed(
"a",
dict(&[
("solo", Value::from(1i64)),
(
"breathe",
Value::from(dict(&[("mode", Value::from("live"))])),
),
]),
);
let b = Fixed(
"b",
dict(&[(
"breathe",
Value::from(dict(&[("mode", Value::from("shadow"))])),
)]),
);
let layers: [&dyn DiscoveryLayer; 2] = [&a, &b];
for path in [
&[][..],
&["solo"][..],
&["absent"][..],
&["breathe"][..],
&["breathe", "mode"][..],
] {
let touched = is_touched_at(&layers, path);
let contested = is_contested_at(&layers, path);
assert!(
!contested || touched,
"is_contested_at ⇒ is_touched_at broken at {path:?}",
);
assert!(
touched || !contested,
"!is_touched_at ⇒ !is_contested_at broken at {path:?}",
);
}
}
#[test]
fn is_touched_at_singleton_characterization_across_paths() {
let a = Fixed(
"a",
dict(&[
("solo", Value::from(1i64)),
(
"breathe",
Value::from(dict(&[("mode", Value::from("live"))])),
),
]),
);
let b = Fixed(
"b",
dict(&[(
"breathe",
Value::from(dict(&[("mode", Value::from("shadow"))])),
)]),
);
let c = Fixed("c", dict(&[("logger", Value::from("info"))]));
let layers: [&dyn DiscoveryLayer; 3] = [&a, &b, &c];
for path in [
&[][..],
&["solo"][..],
&["logger"][..],
&["breathe"][..],
&["breathe", "mode"][..],
&["absent"][..],
] {
let singleton_via_bools =
is_touched_at(&layers, path) && !is_contested_at(&layers, path);
let singleton_via_scalar = contributor_count_at(&layers, path) == 1;
assert_eq!(
singleton_via_bools, singleton_via_scalar,
"singleton characterization broken at {path:?}",
);
}
}
#[test]
fn is_touched_at_credits_prefix_scalar_erasure_toucher() {
let a = Fixed(
"a",
dict(&[("k", Value::from(dict(&[("leaf", Value::from(1i64))])))]),
);
let b = Fixed("b", dict(&[("k", Value::from("erased"))]));
let layers: [&dyn DiscoveryLayer; 2] = [&a, &b];
assert!(is_touched_at(&layers, &["k", "leaf"]));
assert!(is_touched_at(&layers, &["k"]));
assert!(!is_touched_at(&layers, &["unrelated"]));
assert!(!is_touched_at(&layers, &["unrelated", "deep"]));
}
#[test]
fn is_touched_at_root_boundary_filters_silent_layers() {
let coarse = Fixed("platform", dict(&[("a", Value::from(1i64))]));
let silent = Fixed("undetectable", Dict::new());
let specific = Fixed("tenancy", dict(&[("b", Value::from(2i64))]));
let layers_two_non_empty: [&dyn DiscoveryLayer; 3] = [&coarse, &silent, &specific];
assert!(is_touched_at(&layers_two_non_empty, &[]));
let layers_one: [&dyn DiscoveryLayer; 2] = [&coarse, &silent];
assert!(is_touched_at(&layers_one, &[]));
let layers_only_silent: [&dyn DiscoveryLayer; 2] = [&silent, &silent];
assert!(!is_touched_at(&layers_only_silent, &[]));
}
}