From d87a3d97f51633ba994812c334968f4c6a2ffe85 Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Sun, 22 Nov 2026 23:13:21 -0600 Subject: [PATCH 1/2] feat(id-config): resolve layered mode overrides (#10193) --- pkgs/id/crates/id-config/src/lib.rs | 4 + pkgs/id/crates/id-config/src/resolve.rs | 272 ++++++++++++++++++++++++ pkgs/id/tests/config_precedence.rs | 148 +++++++++++++ 3 files changed, 424 insertions(+) create mode 100644 pkgs/id/crates/id-config/src/resolve.rs create mode 100644 pkgs/id/tests/config_precedence.rs diff --git a/pkgs/id/crates/id-config/src/lib.rs b/pkgs/id/crates/id-config/src/lib.rs index 89bb4a95f..a549a73e8 100644 --- a/pkgs/id/crates/id-config/src/lib.rs +++ b/pkgs/id/crates/id-config/src/lib.rs @@ -28,6 +28,10 @@ use std::collections::BTreeSet; use serde::{Deserialize, Serialize}; +pub mod resolve; + +pub use resolve::{LayerOverride, ResolutionInput, ResolveError, ResolvedLayers, resolve}; + /// The only `ConfigDocument` schema version this crate accepts. The schema /// file is `pkgs/id/config/id-config-v1.schema.json`; a document naming any /// other version is rejected ([`ConfigError::UnsupportedSchemaVersion`]) diff --git a/pkgs/id/crates/id-config/src/resolve.rs b/pkgs/id/crates/id-config/src/resolve.rs new file mode 100644 index 000000000..671a959bd --- /dev/null +++ b/pkgs/id/crates/id-config/src/resolve.rs @@ -0,0 +1,272 @@ +//! Layered mode and scoped behavior resolution (slice 9111-02, #10193). +//! +//! The resolver keeps configuration planes distinct while applying their +//! documented precedence: deployment defaults, the selected mode bundle, +//! tenant, peer, link, storage, and finally operation-scoped behavior. Lower +//! scopes may replace behavior in either direction, but authority and +//! resource ceilings remain hard boundaries. + +use std::collections::BTreeMap; + +use thiserror::Error; + +use crate::{Behavior, CeilingOverride, Ceilings, Mode, ResolvedBehavior, SyncScope}; + +/// A behavior and optional resource narrowing supplied by one named scope. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct LayerOverride { + /// Stable scope name used in provenance and diagnostics. + pub name: String, + /// Behavioral values supplied by this scope. + pub behavior: Behavior, + /// Optional narrowing of the current resource ceilings. + pub ceilings: CeilingOverride, +} + +/// The ordered inputs to [`resolve`]. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ResolutionInput { + /// Deployment-wide behavioral defaults. + pub deployment: Behavior, + /// Named mode bundle applied after deployment defaults. + pub mode: Mode, + /// Tenant-scoped behavior, if selected. + pub tenant: Option, + /// Peer-scoped behavior, if selected. + pub peer: Option, + /// Link-scoped behavior, if selected. + pub link: Option, + /// Storage-scoped behavior, if selected. + pub storage: Option, + /// Operation-scoped behavior, if permitted. + pub operation: Option, + /// Hard resource ceiling from the validated configuration document. + pub resource_ceiling: Ceilings, + /// Sync scopes authorized by the owning tenant/authority plane. + pub authority_sync_scopes: Vec, +} + +/// The deterministic result of layered resolution. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ResolvedLayers { + /// Fully resolved behavior. + pub behavior: ResolvedBehavior, + /// Effective resource ceilings after scope narrowings. + pub ceilings: Ceilings, + /// Source of each resolved behavior field. + pub provenance: BTreeMap, +} + +/// Why layered resolution failed. +#[derive(Debug, Clone, PartialEq, Eq, Error)] +pub enum ResolveError { + /// A scope name was empty. + #[error("scope name must not be empty")] + EmptyScope, + /// A scope attempted to widen a currently effective ceiling. + #[error("scope {scope} widens ceiling {field} to {attempted}, above current ceiling {ceiling}")] + CeilingWidened { + /// Scope that attempted the widening. + scope: String, + /// Ceiling field. + field: &'static str, + /// Requested value. + attempted: u64, + /// Current effective ceiling. + ceiling: u64, + }, + /// A behavior value exceeds the effective resource ceiling. + #[error("scope {scope} sets {field} to {value}, above ceiling {ceiling}")] + ResourceExceeded { + /// Scope supplying the value. + scope: String, + /// Behavior field. + field: &'static str, + /// Requested value. + value: u64, + /// Effective ceiling. + ceiling: u64, + }, + /// The final behavior is outside the owning authority plane. + #[error("scope {scope} sets {field}={value:?} outside the authority ceiling")] + AuthorityExceeded { + /// Last scope that supplied the value. + scope: String, + /// Behavior field. + field: &'static str, + /// Disallowed scope. + value: SyncScope, + }, + /// No authority scopes were supplied. + #[error("authority must allow at least one sync scope")] + EmptyAuthority, +} + +/// Resolve layered behavior in the fixed precedence order. +/// +/// The mode bundle is applied after deployment defaults and before the named +/// scopes. Every scope is applied in the fixed plane order, never by caller +/// insertion order. Authority is checked on the final result because a mode +/// default may be replaced by a later authorized scope; resource ceilings are +/// checked at every layer so an over-ceiling value cannot be hidden by a later +/// narrowing override. +pub fn resolve(input: &ResolutionInput) -> Result { + if input.authority_sync_scopes.is_empty() { + return Err(ResolveError::EmptyAuthority); + } + + let mut state = State { + behavior: Mode::SingleNode.defaults(), + ceilings: input.resource_ceiling, + provenance: BTreeMap::new(), + }; + apply_behavior(&mut state, &input.deployment, "deployment")?; + apply_mode(&mut state, input.mode)?; + for layer in [ + input.tenant.as_ref(), + input.peer.as_ref(), + input.link.as_ref(), + input.storage.as_ref(), + input.operation.as_ref(), + ] + .into_iter() + .flatten() + { + apply_layer(&mut state, layer)?; + } + + if !input + .authority_sync_scopes + .contains(&state.behavior.sync_scope) + { + let scope = state + .provenance + .get("sync_scope") + .cloned() + .unwrap_or_else(|| "unknown".to_owned()); + return Err(ResolveError::AuthorityExceeded { + scope, + field: "sync_scope", + value: state.behavior.sync_scope, + }); + } + + Ok(ResolvedLayers { + behavior: state.behavior, + ceilings: state.ceilings, + provenance: state.provenance, + }) +} + +struct State { + behavior: ResolvedBehavior, + ceilings: Ceilings, + provenance: BTreeMap, +} + +fn apply_mode(state: &mut State, mode: Mode) -> Result<(), ResolveError> { + let source = format!("mode:{}", mode.as_str()); + let defaults = mode.defaults(); + state.behavior = defaults; + for field in ["max_hops", "sync_scope", "tier"] { + state.provenance.insert(field.to_owned(), source.clone()); + } + ensure_resource(&state.behavior, &state.ceilings, source) +} + +fn apply_layer(state: &mut State, layer: &LayerOverride) -> Result<(), ResolveError> { + if layer.name.trim().is_empty() { + return Err(ResolveError::EmptyScope); + } + narrow_ceilings(&mut state.ceilings, &layer.ceilings, &layer.name)?; + apply_behavior(state, &layer.behavior, &format!("override:{}", layer.name)) +} + +fn apply_behavior( + state: &mut State, + behavior: &Behavior, + source: &str, +) -> Result<(), ResolveError> { + if let Some(max_hops) = behavior.max_hops { + state.behavior.max_hops = max_hops; + state + .provenance + .insert("max_hops".to_owned(), source.to_owned()); + } + if let Some(sync_scope) = behavior.sync_scope { + state.behavior.sync_scope = sync_scope; + state + .provenance + .insert("sync_scope".to_owned(), source.to_owned()); + } + if let Some(tier) = behavior.tier { + state.behavior.tier = tier; + state + .provenance + .insert("tier".to_owned(), source.to_owned()); + } + ensure_resource(&state.behavior, &state.ceilings, source.to_owned()) +} + +fn ensure_resource( + behavior: &ResolvedBehavior, + ceilings: &Ceilings, + scope: String, +) -> Result<(), ResolveError> { + if behavior.max_hops > ceilings.max_hops { + return Err(ResolveError::ResourceExceeded { + scope, + field: "max_hops", + value: u64::from(behavior.max_hops), + ceiling: u64::from(ceilings.max_hops), + }); + } + Ok(()) +} + +fn narrow_ceilings( + current: &mut Ceilings, + requested: &CeilingOverride, + scope: &str, +) -> Result<(), ResolveError> { + check_narrowing( + scope, + "max_hops", + requested.max_hops.map(u64::from), + u64::from(current.max_hops), + )?; + check_narrowing(scope, "max_bytes", requested.max_bytes, current.max_bytes)?; + check_narrowing( + scope, + "max_time_ms", + requested.max_time_ms, + current.max_time_ms, + )?; + check_narrowing( + scope, + "max_fan_out", + requested.max_fan_out.map(u64::from), + u64::from(current.max_fan_out), + )?; + *current = current.narrowed_by(requested); + Ok(()) +} + +fn check_narrowing( + scope: &str, + field: &'static str, + requested: Option, + ceiling: u64, +) -> Result<(), ResolveError> { + if let Some(attempted) = requested { + if attempted > ceiling { + return Err(ResolveError::CeilingWidened { + scope: scope.to_owned(), + field, + attempted, + ceiling, + }); + } + } + Ok(()) +} diff --git a/pkgs/id/tests/config_precedence.rs b/pkgs/id/tests/config_precedence.rs new file mode 100644 index 000000000..4317c95bb --- /dev/null +++ b/pkgs/id/tests/config_precedence.rs @@ -0,0 +1,148 @@ +//! Reference-oracle tests for slice 9111-02 (#10193). +//! +//! The independent oracle applies the documented layer order by hand and +//! checks that the resolver agrees while preserving authority and resource +//! ceilings. + +#![allow(clippy::expect_used, clippy::panic, clippy::unwrap_used)] + +use id_config::{ + Behavior, CeilingOverride, Ceilings, LayerOverride, Mode, ResolutionInput, ResolveError, + SyncScope, Tier, resolve, +}; + +fn ceilings(max_hops: u32) -> Ceilings { + Ceilings { + max_hops, + max_bytes: 1_000, + max_time_ms: 1_000, + max_fan_out: 10, + } +} + +fn layer(name: &str, behavior: Behavior) -> LayerOverride { + LayerOverride { + name: name.to_owned(), + behavior, + ceilings: CeilingOverride::default(), + } +} + +fn base() -> ResolutionInput { + ResolutionInput { + deployment: Behavior { + max_hops: Some(2), + sync_scope: Some(SyncScope::Metadata), + tier: Some(Tier::Cold), + }, + mode: Mode::HostedTenant, + tenant: None, + peer: None, + link: None, + storage: None, + operation: None, + resource_ceiling: ceilings(5), + authority_sync_scopes: vec![SyncScope::Metadata], + } +} + +#[test] +fn later_scopes_replace_behavior_but_never_widen_resources() { + let mut input = base(); + input.tenant = Some(layer( + "tenant:alpha", + Behavior { + max_hops: Some(3), + sync_scope: Some(SyncScope::Metadata), + tier: Some(Tier::Warm), + }, + )); + input.peer = Some(layer( + "peer:beta", + Behavior { + max_hops: Some(1), + sync_scope: None, + tier: None, + }, + )); + input.storage = Some(layer( + "storage:archive", + Behavior { + max_hops: None, + sync_scope: None, + tier: Some(Tier::Hot), + }, + )); + + let resolved = resolve(&input).unwrap(); + // Independent reference: mode defaults replace deployment, tenant then + // replaces tier, peer narrows hops, and storage replaces tier last. + assert_eq!(resolved.behavior.max_hops, 1); + assert_eq!(resolved.behavior.sync_scope, SyncScope::Metadata); + assert_eq!(resolved.behavior.tier, Tier::Hot); + assert_eq!(resolved.provenance["max_hops"], "override:peer:beta"); + assert_eq!(resolved.provenance["tier"], "override:storage:archive"); + assert_eq!(resolved.ceilings.max_hops, 5); +} + +#[test] +fn behavioral_values_can_loosen_inside_authority_and_resource_ceilings() { + let mut input = base(); + input.authority_sync_scopes = vec![SyncScope::Metadata, SyncScope::Full]; + input.operation = Some(layer( + "operation:sync", + Behavior { + max_hops: Some(4), + sync_scope: Some(SyncScope::Full), + tier: Some(Tier::Hot), + }, + )); + + let resolved = resolve(&input).unwrap(); + assert_eq!(resolved.behavior.max_hops, 4); + assert_eq!(resolved.behavior.sync_scope, SyncScope::Full); + assert_eq!(resolved.behavior.tier, Tier::Hot); + assert_eq!(resolved.provenance["sync_scope"], "override:operation:sync"); +} + +#[test] +fn authority_ceiling_rejects_a_final_out_of_scope_override() { + let mut input = base(); + input.operation = Some(layer( + "operation:sync", + Behavior { + max_hops: None, + sync_scope: Some(SyncScope::Full), + tier: None, + }, + )); + + assert!(matches!( + resolve(&input), + Err(ResolveError::AuthorityExceeded { + field: "sync_scope", + .. + }) + )); +} + +#[test] +fn a_scope_cannot_widen_the_current_resource_ceiling() { + let mut input = base(); + input.peer = Some(LayerOverride { + name: "peer:beta".to_owned(), + behavior: Behavior::default(), + ceilings: CeilingOverride { + max_hops: Some(6), + ..CeilingOverride::default() + }, + }); + + assert!(matches!( + resolve(&input), + Err(ResolveError::CeilingWidened { + field: "max_hops", + .. + }) + )); +} From 4029c480d79299de0b6ee380a7de1e5fd3be0ac7 Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Mon, 23 Nov 2026 00:27:18 -0600 Subject: [PATCH 2/2] fix(id-config): constrain mode defaults to authority --- pkgs/id/crates/id-config/src/resolve.rs | 16 +++++++ pkgs/id/tests/config_precedence.rs | 59 +++++++++++++++++++++++++ 2 files changed, 75 insertions(+) diff --git a/pkgs/id/crates/id-config/src/resolve.rs b/pkgs/id/crates/id-config/src/resolve.rs index 671a959bd..db9197c03 100644 --- a/pkgs/id/crates/id-config/src/resolve.rs +++ b/pkgs/id/crates/id-config/src/resolve.rs @@ -122,6 +122,22 @@ pub fn resolve(input: &ResolutionInput) -> Result }; apply_behavior(&mut state, &input.deployment, "deployment")?; apply_mode(&mut state, input.mode)?; + // Mode bundles are inherited defaults, not authority grants. Constrain + // their default to the narrowest authorized scope; later explicit scope + // overrides are still checked and rejected if unauthorized. + if !input + .authority_sync_scopes + .contains(&state.behavior.sync_scope) + { + state.behavior.sync_scope = if input.authority_sync_scopes.contains(&SyncScope::Metadata) { + SyncScope::Metadata + } else { + input.authority_sync_scopes[0] + }; + state + .provenance + .insert("sync_scope".to_owned(), "authority:default".to_owned()); + } for layer in [ input.tenant.as_ref(), input.peer.as_ref(), diff --git a/pkgs/id/tests/config_precedence.rs b/pkgs/id/tests/config_precedence.rs index 4317c95bb..8a43d6e13 100644 --- a/pkgs/id/tests/config_precedence.rs +++ b/pkgs/id/tests/config_precedence.rs @@ -10,6 +10,7 @@ use id_config::{ Behavior, CeilingOverride, Ceilings, LayerOverride, Mode, ResolutionInput, ResolveError, SyncScope, Tier, resolve, }; +use proptest::prelude::*; fn ceilings(max_hops: u32) -> Ceilings { Ceilings { @@ -146,3 +147,61 @@ fn a_scope_cannot_widen_the_current_resource_ceiling() { }) )); } + +proptest! { + #[test] + fn generated_layer_combinations_match_independent_precedence_model( + values in prop::collection::vec(( + prop::option::of(1u32..=5), + prop::option::of(0u8..=1), + prop::option::of(0u8..=2), + ), 5) + ) { + let mut input = base(); + input.authority_sync_scopes = vec![SyncScope::Metadata, SyncScope::Full]; + let scopes = ["tenant", "peer", "link", "storage", "operation"]; + let mut expected_hops = Mode::HostedTenant.defaults().max_hops; + let mut expected_scope = Mode::HostedTenant.defaults().sync_scope; + let mut expected_tier = Mode::HostedTenant.defaults().tier; + + for (index, (hops, sync, tier)) in values.into_iter().enumerate() { + let behavior = Behavior { + max_hops: hops, + sync_scope: sync.map(|v| if v == 0 { SyncScope::Metadata } else { SyncScope::Full }), + tier: tier.map(|v| match v { + 0 => Tier::Cold, + 1 => Tier::Warm, + _ => Tier::Hot, + }), + }; + // Independent reference model: apply each field in the declared + // fixed order; None retains the last value. + if let Some(value) = hops { expected_hops = value; } + if let Some(value) = behavior.sync_scope { expected_scope = value; } + if let Some(value) = behavior.tier { expected_tier = value; } + let scope_layer = layer(scopes[index], behavior); + match index { + 0 => input.tenant = Some(scope_layer), + 1 => input.peer = Some(scope_layer), + 2 => input.link = Some(scope_layer), + 3 => input.storage = Some(scope_layer), + _ => input.operation = Some(scope_layer), + } + } + + let actual = resolve(&input).unwrap(); + prop_assert_eq!(actual.behavior.max_hops, expected_hops); + prop_assert_eq!(actual.behavior.sync_scope, expected_scope); + prop_assert_eq!(actual.behavior.tier, expected_tier); + prop_assert!(actual.behavior.max_hops <= actual.ceilings.max_hops); + prop_assert!(input.authority_sync_scopes.contains(&actual.behavior.sync_scope)); + } +} + +#[test] +fn mode_default_is_constrained_by_authority_without_explicit_override() { + let input = base(); // HostedTenant defaults Full; authority allows Metadata only. + let actual = resolve(&input).unwrap(); + assert_eq!(actual.behavior.sync_scope, SyncScope::Metadata); + assert_eq!(actual.provenance["sync_scope"], "authority:default"); +}