use std::collections::btree_map::Entry;
use std::collections::BTreeMap;
use crate::error::{PackageError, Result};
use crate::slot::types::ConfigSlot;
pub fn aggregate<'a>(slots: impl IntoIterator<Item = &'a ConfigSlot>) -> Result<Vec<ConfigSlot>> {
let mut map: BTreeMap<(&'static str, &'a str), ConfigSlot> = BTreeMap::new();
for slot in slots {
let key = slot.slot.key();
match map.entry(key) {
Entry::Vacant(e) => {
e.insert(slot.clone());
},
Entry::Occupied(e) => reconcile_collision(key.1, e.get(), slot)?,
}
}
Ok(map.into_values().collect())
}
fn reconcile_collision(name: &str, existing: &ConfigSlot, incoming: &ConfigSlot) -> Result<()> {
if existing.supplied_by != incoming.supplied_by {
return Err(PackageError::ConfigSlotViolation {
key: name.to_string(),
reason: "declared with two different `supplied_by` values by different components; \
since `required_slots` enumerates only environment-supplied slots, \
resolving this by input order would either ask an operator for a value the \
host injects or fail to ask for one nobody supplies — both silent"
.to_string(),
});
}
if existing.config_key != incoming.config_key {
return Err(PackageError::ConfigSlotViolation {
key: name.to_string(),
reason: "declared with two different `config_key` values by different components; \
one slot fills one config path, so this must be reconciled rather than \
silently resolved by input order"
.to_string(),
});
}
if existing.slot == incoming.slot {
return Ok(());
}
if let (Some(tested), Some(proposed)) =
(existing.slot.tested_value(), incoming.slot.tested_value())
{
if tested != proposed {
return Err(PackageError::SlotConflict {
slot: name.to_string(),
tested: tested.to_string(),
proposed: proposed.to_string(),
});
}
}
Err(PackageError::ConfigSlotViolation {
key: name.to_string(),
reason: "declared twice with different declaration fields by different components; one \
slot is one declaration, so this must be reconciled rather than silently \
resolved by input order"
.to_string(),
})
}
#[cfg(test)]
mod tests {
use super::*;
use crate::slot::types::SlotType;
use proptest::prelude::*;
#[test]
fn dedup_two_identical_secrets_into_one_entry() {
let a = ConfigSlot::new(SlotType::Secret {
name: "LICHESS_API_KEY".to_string(),
});
let b = a.clone();
let result = aggregate([&a, &b]).unwrap();
assert_eq!(result, vec![a]);
}
#[test]
fn conflicting_tested_values_return_slot_conflict_error() {
let a = ConfigSlot::new(SlotType::LlmProvider {
name: "primary-llm".to_string(),
tested_value: "anthropic".to_string(),
});
let b = ConfigSlot::new(SlotType::LlmProvider {
name: "primary-llm".to_string(),
tested_value: "openai".to_string(),
});
let err = aggregate([&a, &b]).unwrap_err();
assert!(matches!(
err,
PackageError::SlotConflict {
tested,
proposed,
..
} if tested == "anthropic" && proposed == "openai"
));
}
#[test]
fn same_slot_with_two_different_config_keys_errors_in_either_order() {
let keyed = ConfigSlot::new(SlotType::Secret {
name: "TFL_APP_KEY".to_string(),
})
.with_config_key("backend.auth.query_params.app_key");
let rekeyed = ConfigSlot::new(SlotType::Secret {
name: "TFL_APP_KEY".to_string(),
})
.with_config_key("backend.auth.headers.x-api-key");
for pair in [[&keyed, &rekeyed], [&rekeyed, &keyed]] {
let err = aggregate(pair).unwrap_err();
assert!(
matches!(
&err,
PackageError::ConfigSlotViolation { key, .. } if key == "TFL_APP_KEY"
),
"differing config_keys must be a ConfigSlotViolation naming the slot, got: {err:?}"
);
}
}
#[test]
fn same_slot_keyed_and_unkeyed_errors_rather_than_first_wins() {
let keyed = ConfigSlot::new(SlotType::Secret {
name: "TFL_APP_KEY".to_string(),
})
.with_config_key("backend.auth.query_params.app_key");
let unkeyed = ConfigSlot::new(SlotType::Secret {
name: "TFL_APP_KEY".to_string(),
});
assert!(aggregate([&keyed, &unkeyed]).is_err());
assert!(aggregate([&unkeyed, &keyed]).is_err());
}
#[test]
fn identity_bearing_slots_differing_in_non_value_fields_error_in_either_order() {
let approver = |description: &str| {
ConfigSlot::new(SlotType::HumanRole {
role: "approver".to_string(),
description: description.to_string(),
responsibilities: vec!["review".to_string()],
channel_hints: vec!["slack".to_string()],
})
};
let a = approver("Approves budget overrides");
let b = approver("Signs off on spend");
for pair in [[&a, &b], [&b, &a]] {
let err = aggregate(pair).unwrap_err();
assert!(
matches!(
&err,
PackageError::ConfigSlotViolation { key, .. } if key == "approver"
),
"differing identity-bearing declarations must be a ConfigSlotViolation naming \
the slot, got: {err:?}"
);
}
assert_eq!(aggregate([&a, &a.clone()]).unwrap(), vec![a]);
}
#[test]
fn identical_slots_with_the_same_config_key_still_dedup() {
let a = ConfigSlot::new(SlotType::Secret {
name: "TFL_APP_KEY".to_string(),
})
.with_config_key("backend.auth.query_params.app_key");
let b = a.clone();
let result = aggregate([&a, &b]).unwrap();
assert_eq!(result, vec![a]);
}
#[test]
fn preserves_all_distinct_conflict_free_slots() {
let a = ConfigSlot::new(SlotType::Secret {
name: "A".to_string(),
});
let b = ConfigSlot::new(SlotType::OauthClient {
name: "B".to_string(),
});
let result = aggregate([&a, &b]).unwrap();
assert_eq!(result.len(), 2);
}
fn one_slot_per_variant() -> Vec<ConfigSlot> {
vec![
ConfigSlot::new(SlotType::LlmProvider {
name: "primary-llm".to_string(),
tested_value: "anthropic".to_string(),
}),
ConfigSlot::new(SlotType::Secret {
name: "TFL_API_KEY".to_string(),
}),
ConfigSlot::new(SlotType::AuthMode {
name: "backend.auth.type".to_string(),
tested_value: "api_key".to_string(),
}),
ConfigSlot::new(SlotType::HumanRole {
role: "approver".to_string(),
description: "Approves budget overrides".to_string(),
responsibilities: vec!["review".to_string()],
channel_hints: vec!["slack".to_string()],
}),
ConfigSlot::new(SlotType::Endpoint {
name: "backend.base_url".to_string(),
tested_value: "https://api.tfl.gov.uk".to_string(),
}),
ConfigSlot::new(SlotType::OauthClient {
name: "primary-oauth".to_string(),
}),
ConfigSlot::new(SlotType::BudgetOverride {
name: "monthly-cap".to_string(),
tested_value: "1000".to_string(),
}),
ConfigSlot::new(SlotType::ChannelBinding {
name: "notify-channel".to_string(),
}),
]
}
#[test]
fn aggregates_secret_endpoint_and_auth_mode_into_deterministic_order() {
let secret = ConfigSlot::new(SlotType::Secret {
name: "TFL_API_KEY".to_string(),
});
let endpoint = ConfigSlot::new(SlotType::Endpoint {
name: "backend.base_url".to_string(),
tested_value: "https://api.tfl.gov.uk".to_string(),
});
let auth_mode = ConfigSlot::new(SlotType::AuthMode {
name: "backend.auth.type".to_string(),
tested_value: "api_key".to_string(),
});
let result = aggregate([&secret, &endpoint, &auth_mode, &endpoint.clone()]).unwrap();
assert_eq!(result.len(), 3);
let keys: Vec<(&str, &str)> = result.iter().map(|c| c.slot.key()).collect();
assert_eq!(
keys,
vec![
("auth_mode", "backend.auth.type"),
("endpoint", "backend.base_url"),
("secret", "TFL_API_KEY"),
]
);
}
proptest! {
#[test]
fn aggregate_ordering_is_stable_under_permutation(seed in proptest::collection::vec(0u32..1000, 8)) {
let slots: Vec<ConfigSlot> = one_slot_per_variant();
prop_assert_eq!(slots.len(), 8);
let mut indices: Vec<usize> = (0..8).collect();
indices.sort_by_key(|&i| seed[i]);
let permuted: Vec<&ConfigSlot> = indices.iter().map(|&i| &slots[i]).collect();
let baseline = aggregate(slots.iter()).unwrap();
let shuffled = aggregate(permuted).unwrap();
prop_assert_eq!(baseline.len(), 8);
prop_assert_eq!(baseline, shuffled);
}
}
}