#![allow(clippy::disallowed_methods)]
use super::*;
use crate::adapter::net::behavior::org::{current_timestamp, OrgKeypair};
use crate::adapter::net::behavior::org_grant::{GrantRights, GrantTargetScope, OrgAudienceSecret};
use crate::adapter::net::behavior::org_grant_registry::{
validate_consumer_record, PreparedInstall,
};
use crate::adapter::net::behavior::org_routing::RegistryWork;
use crate::adapter::net::behavior::org_routing_registry::{
DemandHandle, GrantArtifactFence, GrantMovementFence, NodeOrgRoutingRegistry, RegistryMetrics,
ScopedDiscoveryAuthorityStamp, ScopedSourceFacts, SlotSource, SourceCommitPin, SourceFacts,
SourceSnapshot, SourceToken, MAX_NODE_SLOTS,
};
use std::time::Duration;
struct InertSource;
struct InertSnapshot;
impl SourceSnapshot for InertSnapshot {
fn token(&self) -> SourceToken {
SourceToken::new(vec![0])
}
fn providers(&self, _key: &SlotKey) -> ScopedSourceFacts {
ScopedSourceFacts {
facts: SourceFacts::Unserved,
authority: ScopedDiscoveryAuthorityStamp::Owner,
authority_deadline: u64::MAX,
grant_fence: GrantArtifactFence::Publication(0),
}
}
}
impl SlotSource for InertSource {
fn snapshot(&self, _keys: &[SlotKey]) -> Box<dyn SourceSnapshot> {
Box::new(InertSnapshot)
}
fn pin_if_current(
&self,
_keys: &[SlotKey],
_expected: &SourceToken,
) -> Option<Box<dyn SourceCommitPin + '_>> {
None
}
}
struct Fixture {
registry: Arc<NodeOrgRoutingRegistry>,
metrics: Arc<RegistryMetrics>,
}
fn fixture() -> Fixture {
let metrics: Arc<RegistryMetrics> = Arc::default();
let registry = NodeOrgRoutingRegistry::new(
Arc::new(InertSource),
Arc::<RegistryWork>::default(),
metrics.clone(),
);
Fixture { registry, metrics }
}
impl Fixture {
fn state(&self, credentials: FamilyDiscoveryCredentials) -> OrgRoutingState {
OrgRoutingState::new(self.registry.new_family().expect("family"), credentials)
}
}
fn consumer_org() -> OrgKeypair {
OrgKeypair::from_bytes([0xA1; 32])
}
fn provider_org() -> OrgKeypair {
OrgKeypair::from_bytes([0xB2; 32])
}
fn cap(tag: &str) -> CapabilityAuthorityId {
CapabilityAuthorityId::for_tag(tag)
}
const OWNER_HANDLE: [u8; 32] = [0x0E; 32];
fn credentials(grants: Vec<Arc<OrgCapabilityGrant>>) -> FamilyDiscoveryCredentials {
FamilyDiscoveryCredentials {
acting_org: consumer_org().org_id(),
owner_audience_handle: OWNER_HANDLE,
grants,
}
}
fn owner_key(capability: &CapabilityAuthorityId) -> SlotKey {
SlotKey {
scope: PrivateAudienceScope::new(CapabilityAudienceScope::Owner {
org_id: consumer_org().org_id(),
audience_handle: OWNER_HANDLE,
})
.expect("owner scopes are private"),
capability: *capability,
}
}
fn grant_key(grant: &OrgCapabilityGrant) -> SlotKey {
SlotKey {
scope: PrivateAudienceScope::new(CapabilityAudienceScope::Grant {
grant_id: grant.grant_id,
audience_handle: grant
.discovery
.as_ref()
.expect("a DISCOVER grant carries a binding")
.audience_handle,
})
.expect("grant scopes are private"),
capability: grant.capability,
}
}
fn issue(
capability: CapabilityAuthorityId,
rights: GrantRights,
) -> (Arc<OrgCapabilityGrant>, Option<OrgAudienceSecret>) {
let (grant, secret) = OrgCapabilityGrant::try_issue(
&provider_org(),
consumer_org().org_id(),
capability,
rights,
GrantTargetScope::AnyNodeOwnedBy(provider_org().org_id()),
3600,
)
.expect("issue");
(Arc::new(grant), secret)
}
fn issue_reusing_id(
capability: CapabilityAuthorityId,
grant_id: [u8; 32],
) -> (Arc<OrgCapabilityGrant>, OrgAudienceSecret) {
let now = current_timestamp();
let (secret, binding) = OrgAudienceSecret::mint(grant_id);
let grant = OrgCapabilityGrant::issue_at(
&provider_org(),
grant_id,
consumer_org().org_id(),
capability,
GrantRights::DISCOVER,
GrantTargetScope::AnyNodeOwnedBy(provider_org().org_id()),
Some(binding),
now.saturating_sub(60),
now + 3600,
u64::from(grant_id[0]) ^ now,
);
(Arc::new(grant), secret)
}
fn lease(
snapshot: &ConsumerGrantSnapshot,
grant: &OrgCapabilityGrant,
secret: OrgAudienceSecret,
install_seq: u64,
) -> ConsumerGrantSnapshot {
let now = current_timestamp();
let record = validate_consumer_record(grant.clone(), secret, &consumer_org().org_id(), now, 60)
.expect("consumer record valid");
match snapshot
.prepare_install(record, now)
.expect("room reserved")
{
PreparedInstall::Ready(slot) => ConsumerGrantSnapshot::finish_install(*slot, install_seq)
.stamped(GrantMovementFence::Publication(install_seq)),
PreparedInstall::Noop => panic!("the witness installs a fresh grant"),
}
}
fn remove(
snapshot: &ConsumerGrantSnapshot,
grant_id: &[u8; 32],
revision: u64,
) -> ConsumerGrantSnapshot {
snapshot
.without(grant_id)
.expect("the record was there")
.stamped(GrantMovementFence::Publication(revision))
}
#[test]
fn a_leased_discover_grant_is_a_demand_beside_owner() {
let capability = cap("nrpc:read");
let (grant, secret) = issue(capability, GrantRights::DISCOVER.union(GrantRights::INVOKE));
let leased = lease(
&ConsumerGrantSnapshot::empty(),
&grant,
secret.expect("DISCOVER mints a secret"),
1,
);
let keys = demand_set_for(&credentials(vec![grant.clone()]), &capability, &leased)
.expect("the family has an owner scope");
assert_eq!(
keys,
vec![owner_key(&capability), grant_key(&grant)],
"Owner first, then the leased Grant audience"
);
}
#[test]
fn a_discover_grant_with_no_installed_audience_is_not_a_demand() {
let capability = cap("nrpc:read");
let (unleased, unleased_secret) = issue(capability, GrantRights::DISCOVER);
let unleased_secret = unleased_secret.expect("DISCOVER mints a secret");
let (leased_grant, leased_secret) = issue(capability, GrantRights::DISCOVER);
let leased = lease(
&ConsumerGrantSnapshot::empty(),
&leased_grant,
leased_secret.expect("DISCOVER mints a secret"),
1,
);
let keys = demand_set_for(
&credentials(vec![unleased.clone(), leased_grant.clone()]),
&capability,
&leased,
)
.expect("owner scope");
assert_eq!(
keys,
vec![owner_key(&capability), grant_key(&leased_grant)],
"the unleased DISCOVER grant contributes no demand"
);
assert!(
!keys.contains(&grant_key(&unleased)),
"and specifically not a permanently-Unserved contributor for it"
);
assert_eq!(
classify(&unleased, &capability, &consumer_org().org_id(), &leased),
Some(GrantDemand::NotLeased),
"DISCOVER it has; the audience it does not"
);
let both = lease(&leased, &unleased, unleased_secret, 2);
let keys = demand_set_for(
&credentials(vec![unleased.clone(), leased_grant.clone()]),
&capability,
&both,
)
.expect("owner scope");
assert_eq!(keys.len(), 3, "leasing it makes it a demand: {keys:?}");
assert!(keys.contains(&grant_key(&unleased)));
}
#[test]
fn an_invoke_only_grant_is_not_a_source_demand() {
let capability = cap("nrpc:read");
let (discover, discover_secret) = issue(capability, GrantRights::DISCOVER);
let leased = lease(
&ConsumerGrantSnapshot::empty(),
&discover,
discover_secret.expect("DISCOVER mints a secret"),
1,
);
let (invoke_only, secret) = issue(capability, GrantRights::INVOKE);
assert!(
secret.is_none() && invoke_only.discovery.is_none(),
"an INVOKE-only grant carries no discovery binding at all"
);
assert_eq!(
classify(&invoke_only, &capability, &consumer_org().org_id(), &leased),
Some(GrantDemand::NotDiscovery),
"excluded for carrying no DISCOVER right — NOT for being unleased"
);
assert_eq!(
classify(&discover, &capability, &consumer_org().org_id(), &leased),
Some(GrantDemand::Leased(
discover
.discovery
.as_ref()
.expect("binding")
.audience_handle
)),
"the control: the DISCOVER grant beside it IS a demand"
);
let creds = credentials(vec![invoke_only.clone(), discover.clone()]);
let keys = demand_set_for(&creds, &capability, &leased).expect("owner scope");
assert_eq!(
keys,
vec![owner_key(&capability), grant_key(&discover)],
"exactly two demands: Owner and the DISCOVER audience"
);
assert!(
creds
.grants
.iter()
.any(|g| g.grant_id == invoke_only.grant_id),
"and the INVOKE-only grant is RETAINED for the projection to match"
);
let f = fixture();
let state = f.state(creds);
assert_eq!(state.route_handle(&capability, &leased), RouteLookup::Warm);
assert_eq!(state.handles(), 2, "Owner + the leased DISCOVER audience");
assert_eq!(f.registry.retained_slots(), 2);
}
#[test]
fn demands_are_exact_on_capability_and_grantee() {
let capability = cap("nrpc:read");
let (mine, mine_secret) = issue(capability, GrantRights::DISCOVER);
let (other_cap, other_secret) = issue(cap("nrpc:write"), GrantRights::DISCOVER);
let leased = lease(
&ConsumerGrantSnapshot::empty(),
&mine,
mine_secret.expect("secret"),
1,
);
let leased = lease(&leased, &other_cap, other_secret.expect("secret"), 2);
let keys = demand_set_for(
&credentials(vec![mine.clone(), other_cap.clone()]),
&capability,
&leased,
)
.expect("owner scope");
assert_eq!(keys, vec![owner_key(&capability), grant_key(&mine)]);
let (foreign, foreign_secret) = OrgCapabilityGrant::try_issue(
&provider_org(),
OrgKeypair::from_bytes([0xC3; 32]).org_id(),
capability,
GrantRights::DISCOVER,
GrantTargetScope::AnyNodeOwnedBy(provider_org().org_id()),
3600,
)
.map(|(g, s)| (Arc::new(g), s))
.expect("issue");
let now = current_timestamp();
let record = validate_consumer_record(
(*foreign).clone(),
foreign_secret.expect("secret"),
&OrgKeypair::from_bytes([0xC3; 32]).org_id(),
now,
60,
)
.expect("valid for ITS grantee");
let leased = match leased.prepare_install(record, now).expect("room") {
PreparedInstall::Ready(slot) => ConsumerGrantSnapshot::finish_install(*slot, 3),
PreparedInstall::Noop => panic!("fresh"),
};
let keys = demand_set_for(
&credentials(vec![mine.clone(), foreign]),
&capability,
&leased,
)
.expect("owner scope");
assert_eq!(
keys,
vec![owner_key(&capability), grant_key(&mine)],
"another org's grant is not this family's demand"
);
}
#[test]
fn a_rotated_audience_handle_is_not_leased_under_its_own_id() {
let capability = cap("nrpc:read");
let (grant, secret) = issue(capability, GrantRights::DISCOVER);
let leased = lease(
&ConsumerGrantSnapshot::empty(),
&grant,
secret.expect("secret"),
1,
);
let (rotated, _successor_secret) = issue_reusing_id(capability, grant.grant_id);
assert_eq!(rotated.grant_id, grant.grant_id, "the id is REUSED");
assert_ne!(
rotated.discovery.as_ref().expect("binding").audience_handle,
grant.discovery.as_ref().expect("binding").audience_handle,
"under a different handle"
);
let keys = demand_set_for(&credentials(vec![rotated.clone()]), &capability, &leased)
.expect("owner scope");
assert_eq!(
keys,
vec![owner_key(&capability)],
"the id is installed, but under a different handle — not leased"
);
}
#[test]
fn a_warmed_lookup_takes_no_lock() {
let capability = cap("nrpc:read");
let f = fixture();
let state = f.state(credentials(Vec::new()));
let leased = ConsumerGrantSnapshot::empty();
assert_eq!(state.route_handle(&capability, &leased), RouteLookup::Warm);
let after_miss = state.mutate_acquisitions();
assert_eq!(after_miss, 1, "the MISS takes it exactly once");
for _ in 0..1_000 {
assert!(state.warm(&capability).is_some());
assert_eq!(state.route_handle(&capability, &leased), RouteLookup::Warm);
}
assert_eq!(
state.mutate_acquisitions(),
after_miss,
"and a thousand warmed lookups take it not once more"
);
}
#[test]
fn a_warmed_lookup_completes_while_the_mutation_lock_is_held() {
let capability = cap("nrpc:read");
let f = fixture();
let state = Arc::new(f.state(credentials(Vec::new())));
let leased = ConsumerGrantSnapshot::empty();
assert_eq!(state.route_handle(&capability, &leased), RouteLookup::Warm);
let held = state.mutate_lock_for_test().lock();
let (tx, rx) = std::sync::mpsc::channel();
let contender = {
let state = state.clone();
std::thread::spawn(move || {
let blocked = state.mutate_lock_for_test().try_lock().is_none();
tx.send(blocked).expect("acknowledge");
blocked
})
};
assert!(
rx.recv_timeout(Duration::from_secs(5))
.expect("the contender must report within the bound"),
"the lock this witness holds must be the REAL one — try_lock has to fail"
);
let handle = state.warm(&capability).expect("warm read under contention");
assert_eq!(handle.capability(), &capability);
assert_eq!(
handle.demands().len(),
1,
"Owner only, for a grantless family"
);
assert_eq!(state.route_handle(&capability, &leased), RouteLookup::Warm);
drop(held);
assert!(contender.join().expect("contender joins"));
}
#[test]
fn concurrent_misses_acquire_one_demand_set() {
let capability = cap("nrpc:read");
let f = fixture();
let mut grants = Vec::new();
let mut leased = ConsumerGrantSnapshot::empty();
for i in 0..2u32 {
let (grant, secret) = issue(capability, GrantRights::DISCOVER);
leased = lease(&leased, &grant, secret.expect("secret"), u64::from(i) + 1);
grants.push(grant);
}
let state = Arc::new(f.state(credentials(grants)));
for i in 0..60u32 {
assert_eq!(
state.route_handle(&cap(&format!("nrpc:fill{i}")), &leased),
RouteLookup::Warm
);
}
assert_eq!(state.handles(), 60);
let before = state.mutate_acquisitions();
let leased = Arc::new(leased);
let start = Arc::new(std::sync::Barrier::new(4));
let threads: Vec<_> = (0..4)
.map(|_| {
let state = state.clone();
let start = start.clone();
let leased = leased.clone();
std::thread::spawn(move || {
start.wait();
state.acquire(&capability, &leased)
})
})
.collect();
for t in threads {
assert_eq!(
t.join().expect("join"),
RouteLookup::Warm,
"every rival adopts the winner's entry; none spends the budget again"
);
}
assert_eq!(
state.mutate_acquisitions() - before,
4,
"all four genuinely entered the mutation section"
);
assert_eq!(state.entries(), 61, "one new entry, not four");
assert_eq!(state.handles(), 63, "Owner + two leased audiences, once");
assert_eq!(f.registry.retained_slots(), 63);
assert_eq!(
f.metrics.refused_family_at_capacity(),
0,
"no rival was refused at the registry"
);
assert_eq!(
state.route_handle(&cap("nrpc:after"), &leased),
RouteLookup::Warm,
"a transient over-spend would have been refused above"
);
assert_eq!(state.handles(), 64);
}
#[test]
fn a_spent_family_budget_refuses_from_the_registry_every_time() {
let f = fixture();
let state = f.state(credentials(Vec::new()));
let leased = ConsumerGrantSnapshot::empty();
for i in 0..64u32 {
assert_eq!(
state.route_handle(&cap(&format!("nrpc:c{i}")), &leased),
RouteLookup::Warm
);
}
assert_eq!(state.handles(), 64, "the budget is exactly spent");
assert_eq!(state.entries(), 64, "64 grantless capabilities fit");
for i in 0..3u32 {
assert_eq!(
state.route_handle(&cap(&format!("nrpc:over{i}")), &leased),
RouteLookup::Cold(ColdReason::Refused(DemandRefused::FamilyAtCapacity)),
);
}
assert_eq!(
f.metrics.refused_family_at_capacity(),
3,
"every attempt is the registry's refusal, not a replayed one"
);
assert_eq!(
state.route_handle(&cap("nrpc:c0"), &leased),
RouteLookup::Warm
);
}
#[test]
fn a_wide_refusal_does_not_poison_residual_capacity() {
let f = fixture();
let wide = cap("nrpc:wide");
let mut grants = Vec::new();
let mut leased = ConsumerGrantSnapshot::empty();
for i in 0..2u32 {
let (grant, secret) = issue(wide, GrantRights::DISCOVER);
leased = lease(&leased, &grant, secret.expect("secret"), u64::from(i) + 1);
grants.push(grant);
}
let state = f.state(credentials(grants));
fill_to_total(&state, &leased, 62);
let entries = state.entries();
assert_eq!(
state.route_handle(&wide, &leased),
RouteLookup::Cold(ColdReason::Refused(DemandRefused::FamilyAtCapacity)),
"a width-3 set does not fit in two handles"
);
assert_eq!(state.handles(), 62, "and it retained none of them");
assert_eq!(state.entries(), entries, "and published no entry");
assert_eq!(
state.route_handle(&cap("nrpc:narrow"), &leased),
RouteLookup::Warm,
"a wide refusal must not poison residual capacity"
);
assert_eq!(state.handles(), 63);
assert_eq!(state.entries(), entries + 1);
}
#[test]
fn the_family_bound_counts_demands_not_capabilities() {
let f = fixture();
let mut grants = Vec::new();
let mut leased = ConsumerGrantSnapshot::empty();
for i in 0..33u32 {
let (grant, secret) = issue(cap(&format!("nrpc:c{i}")), GrantRights::DISCOVER);
leased = lease(
&leased,
&grant,
secret.expect("DISCOVER mints a secret"),
u64::from(i) + 1,
);
grants.push(grant);
}
let state = f.state(credentials(grants));
for i in 0..32u32 {
assert_eq!(
state.route_handle(&cap(&format!("nrpc:c{i}")), &leased),
RouteLookup::Warm
);
}
assert_eq!(state.handles(), 64, "two demands per capability");
assert_eq!(state.entries(), 32, "so 32 capabilities, not 64");
assert_eq!(
state.route_handle(&cap("nrpc:c32"), &leased),
RouteLookup::Cold(ColdReason::Refused(DemandRefused::FamilyAtCapacity)),
"the 33rd needs two more handles and there are none"
);
assert!(
state.entries() <= MAX_CAPABILITY_ENTRIES_PER_FAMILY,
"the entry ceiling is structural, never separately enforced"
);
}
#[test]
fn a_full_node_refuses_every_attempt_until_a_retirement() {
let f = fixture();
let mut held = Vec::new();
let mut fillers = Vec::new();
for chunk in 0..4u32 {
let filler = f.registry.new_family().expect("family");
for i in 0..64u32 {
held.push(
filler
.demand(SlotKey {
scope: PrivateAudienceScope::new(CapabilityAudienceScope::Grant {
grant_id: [0x5A; 32],
audience_handle: [0x5A; 32],
})
.expect("private"),
capability: cap(&format!("nrpc:fill{}", chunk * 64 + i)),
})
.expect("fill"),
);
}
fillers.push(filler);
}
assert_eq!(f.registry.retained_slots(), MAX_NODE_SLOTS);
let state = f.state(credentials(Vec::new()));
let leased = ConsumerGrantSnapshot::empty();
let capability = cap("nrpc:read");
for attempt in 1..=3u64 {
assert_eq!(
state.route_handle(&capability, &leased),
RouteLookup::Cold(ColdReason::Refused(DemandRefused::NodeAtCapacity))
);
assert_eq!(
f.metrics.refused_node_at_capacity(),
attempt,
"every attempt is the registry's refusal, not a replayed one"
);
}
held.pop();
assert_eq!(f.registry.retained_slots(), MAX_NODE_SLOTS - 1);
assert_eq!(
state.route_handle(&capability, &leased),
RouteLookup::Warm,
"one retirement is the whole recovery story"
);
assert_eq!(state.entries(), 1);
}
#[test]
fn a_narrowed_demand_warms_on_a_full_node_without_a_retirement() {
let f = fixture();
let capability = cap("nrpc:read");
let (grant, secret) = issue(capability, GrantRights::DISCOVER);
let leased = lease(
&ConsumerGrantSnapshot::empty(),
&grant,
secret.expect("DISCOVER mints a secret"),
1,
);
let mut held = Vec::new();
let mut fillers = Vec::new();
for chunk in 0..4u32 {
let filler = f.registry.new_family().expect("family");
for i in 0..64u32 {
let key = if (chunk, i) == (0, 0) {
owner_key(&capability)
} else {
SlotKey {
scope: PrivateAudienceScope::new(CapabilityAudienceScope::Grant {
grant_id: [0x5A; 32],
audience_handle: [0x5A; 32],
})
.expect("private"),
capability: cap(&format!("nrpc:fill{}", chunk * 64 + i)),
}
};
held.push(filler.demand(key).expect("fill"));
}
fillers.push(filler);
}
assert_eq!(f.registry.retained_slots(), MAX_NODE_SLOTS);
let state = f.state(credentials(vec![grant.clone()]));
assert_eq!(
state.route_handle(&capability, &leased),
RouteLookup::Cold(ColdReason::Refused(DemandRefused::NodeAtCapacity)),
"Owner + Grant needs a slot a full node cannot create"
);
let generation = f.registry.node_capacity_generation();
let narrowed = remove(&leased, &grant.grant_id, 2);
assert_eq!(
state.route_handle(&capability, &narrowed),
RouteLookup::Warm,
"the narrowed set creates no slot, so the full node cannot refuse it"
);
assert_eq!(
f.registry.node_capacity_generation(),
generation,
"and it warmed without a single retirement"
);
assert_eq!(state.entries(), 1);
assert_eq!(state.handles(), 1, "Owner alone; the Grant scope is gone");
assert_eq!(
f.registry.retained_slots(),
MAX_NODE_SLOTS,
"it SHARES the owner slot rather than creating a 257th"
);
drop(held);
}
#[test]
fn identity_exhaustion_refuses_a_set_that_needs_a_new_slot() {
let f = fixture();
let state = f.state(credentials(Vec::new()));
let leased = ConsumerGrantSnapshot::empty();
f.registry.exhaust_ids_for_test();
assert_eq!(
state.route_handle(&cap("nrpc:read"), &leased),
RouteLookup::Cold(ColdReason::Refused(DemandRefused::IdSpaceExhausted))
);
assert_eq!(f.metrics.refused_id_space_exhausted(), 1);
}
#[test]
fn identity_exhaustion_does_not_refuse_a_set_of_existing_slots() {
let f = fixture();
let capability = cap("nrpc:read");
let holder = f.registry.new_family().expect("family");
let _preheld = holder.demand(owner_key(&capability)).expect("pre-retains");
let state = f.state(credentials(Vec::new()));
let leased = ConsumerGrantSnapshot::empty();
f.registry.exhaust_ids_for_test();
assert_eq!(
state.route_handle(&cap("nrpc:unrelated"), &leased),
RouteLookup::Cold(ColdReason::Refused(DemandRefused::IdSpaceExhausted))
);
assert_eq!(
state.route_handle(&capability, &leased),
RouteLookup::Warm,
"no identity is allocated for a slot that already exists"
);
assert_eq!(state.handles(), 1);
assert_eq!(
f.registry.retained_slots(),
1,
"it SHARES the pre-retained slot rather than creating one"
);
}
#[test]
fn a_refused_entry_retains_no_partial_demand() {
let f = fixture();
let mut grants = Vec::new();
let mut leased = ConsumerGrantSnapshot::empty();
for i in 0..2u32 {
let (grant, secret) = issue(cap("nrpc:wide"), GrantRights::DISCOVER);
leased = lease(&leased, &grant, secret.expect("secret"), u64::from(i) + 1);
grants.push(grant);
}
let state = f.state(credentials(grants));
let leased_ref = &leased;
for i in 0..63u32 {
assert_eq!(
state.route_handle(&cap(&format!("nrpc:c{i}")), leased_ref),
RouteLookup::Warm
);
}
assert_eq!(state.handles(), 63);
let slots = f.registry.retained_slots();
let identities = f.registry.allocated_ids_for_test();
assert_eq!(
state.route_handle(&cap("nrpc:wide"), leased_ref),
RouteLookup::Cold(ColdReason::Refused(DemandRefused::FamilyAtCapacity))
);
assert_eq!(state.handles(), 63, "not one handle of the set was kept");
assert_eq!(
f.registry.retained_slots(),
slots,
"and no slot was created"
);
assert_eq!(state.entries(), 63, "and no index entry was published");
assert!(
state.warm(&cap("nrpc:wide")).is_none(),
"a refused capability is not warm"
);
assert_eq!(
f.registry.allocated_ids_for_test(),
identities,
"a refused entry consumes no identity either"
);
}
fn fill_to_total(state: &OrgRoutingState, leased: &ConsumerGrantSnapshot, target: usize) {
let mut seed = 0u32;
while state.handles() < target {
assert_eq!(
state.route_handle(&cap(&format!("nrpc:top{seed}")), leased),
RouteLookup::Warm
);
seed += 1;
}
assert_eq!(state.handles(), target);
}
fn retained_grant_scopes(
state: &OrgRoutingState,
capability: &CapabilityAuthorityId,
) -> Vec<([u8; 32], [u8; 32])> {
state
.warm(capability)
.expect("warm")
.demanded()
.iter()
.filter_map(|key| match key.scope.scope() {
CapabilityAudienceScope::Grant {
grant_id,
audience_handle,
} => Some((*grant_id, *audience_handle)),
_ => None,
})
.collect()
}
#[test]
fn a_newly_leased_audience_joins_a_warmed_entry() {
let f = fixture();
let capability = cap("nrpc:read");
let (grant, secret) = issue(capability, GrantRights::DISCOVER);
let state = f.state(credentials(vec![grant.clone()]));
let unleased = ConsumerGrantSnapshot::empty();
assert_eq!(
state.route_handle(&capability, &unleased),
RouteLookup::Warm
);
assert_eq!(
state.warm(&capability).expect("warm").demands().len(),
1,
"W-N1 — an uninstalled audience is not a demand"
);
assert_eq!(state.handles(), 1);
let leased = lease(&unleased, &grant, secret.expect("secret"), 1);
assert_eq!(state.route_handle(&capability, &leased), RouteLookup::Warm);
let entry = state.warm(&capability).expect("warm");
assert_eq!(
entry.demands().len(),
2,
"Owner + the newly leased Grant audience"
);
assert_eq!(
entry.demanded(),
&[owner_key(&capability), grant_key(&grant)],
"and it is the EXACT scope that was leased"
);
assert_eq!(state.handles(), 2, "the superseded set was released");
assert_eq!(state.entries(), 1, "one entry, re-derived — not two");
assert_eq!(f.registry.retained_slots(), 2);
}
#[test]
fn a_removed_audience_leaves_a_warmed_entry() {
let f = fixture();
let capability = cap("nrpc:read");
let (grant, secret) = issue(capability, GrantRights::DISCOVER);
let leased = lease(
&ConsumerGrantSnapshot::empty(),
&grant,
secret.expect("secret"),
1,
);
let state = f.state(credentials(vec![grant.clone()]));
assert_eq!(state.route_handle(&capability, &leased), RouteLookup::Warm);
assert_eq!(state.handles(), 2);
assert_eq!(
retained_grant_scopes(&state, &capability),
vec![(
grant.grant_id,
grant.discovery.expect("binding").audience_handle
)]
);
let removed = remove(&leased, &grant.grant_id, 100);
assert_eq!(state.route_handle(&capability, &removed), RouteLookup::Warm);
assert_eq!(
state.warm(&capability).expect("warm").demanded(),
&[owner_key(&capability)],
"Owner alone — the obsolete Grant scope is gone"
);
assert!(
retained_grant_scopes(&state, &capability).is_empty(),
"an obsolete scope is not retained as the current complete demand set"
);
assert_eq!(state.handles(), 1, "and its handle was released");
assert_eq!(
f.registry.retained_slots(),
1,
"the last reference retired the node slot"
);
}
#[test]
fn a_rotated_audience_replaces_the_scope_it_supersedes() {
let f = fixture();
let capability = cap("nrpc:read");
let (original, original_secret) = issue(capability, GrantRights::DISCOVER);
let (rotated, successor_secret) = issue_reusing_id(capability, original.grant_id);
let original_secret = original_secret.expect("DISCOVER mints a secret");
let original_handle = original.discovery.expect("binding").audience_handle;
let rotated_handle = rotated.discovery.expect("binding").audience_handle;
assert_ne!(original_handle, rotated_handle);
assert_eq!(original.grant_id, rotated.grant_id);
let leased = lease(
&ConsumerGrantSnapshot::empty(),
&original,
original_secret,
1,
);
let state = f.state(credentials(vec![original.clone(), rotated.clone()]));
assert_eq!(state.route_handle(&capability, &leased), RouteLookup::Warm);
assert_eq!(
retained_grant_scopes(&state, &capability),
vec![(original.grant_id, original_handle)],
"the ORIGINAL audience is what is leased"
);
let rotated_lease = lease(
&remove(&leased, &original.grant_id, 100),
&rotated,
successor_secret,
2,
);
assert_eq!(
state.route_handle(&capability, &rotated_lease),
RouteLookup::Warm
);
assert_eq!(
retained_grant_scopes(&state, &capability),
vec![(original.grant_id, rotated_handle)],
"the id is unchanged, so ONLY the whole-scope comparison can see this"
);
assert_eq!(state.handles(), 2, "Owner + exactly one audience");
assert_eq!(
f.registry.retained_slots(),
2,
"the rotated-away slot retired; it did not accumulate beside its successor"
);
}
#[test]
fn a_rotated_away_scope_is_not_retained_under_its_own_id() {
let f = fixture();
let capability = cap("nrpc:read");
let (original, original_secret) = issue(capability, GrantRights::DISCOVER);
let original_handle = original.discovery.expect("binding").audience_handle;
let leased = lease(
&ConsumerGrantSnapshot::empty(),
&original,
original_secret.expect("secret"),
1,
);
let state = f.state(credentials(vec![original.clone()]));
assert_eq!(state.route_handle(&capability, &leased), RouteLookup::Warm);
assert_eq!(
retained_grant_scopes(&state, &capability),
vec![(original.grant_id, original_handle)]
);
assert_eq!(state.handles(), 2);
let (successor, successor_secret) = issue_reusing_id(capability, original.grant_id);
assert_ne!(
successor.discovery.expect("binding").audience_handle,
original_handle
);
let rotated = lease(
&remove(&leased, &original.grant_id, 100),
&successor,
successor_secret,
2,
);
assert!(
rotated.get(&original.grant_id).is_some(),
"precondition: the ID is still installed — an id-keyed check sees nothing wrong"
);
assert_eq!(state.route_handle(&capability, &rotated), RouteLookup::Warm);
assert!(
retained_grant_scopes(&state, &capability).is_empty(),
"the rotated-away scope is not retained under its own id"
);
assert_eq!(
state.warm(&capability).expect("warm").demanded(),
&[owner_key(&capability)]
);
assert_eq!(state.handles(), 1);
assert_eq!(f.registry.retained_slots(), 1);
}
#[test]
fn concurrent_rederivations_spend_one_demand_set() {
let f = fixture();
let capability = cap("nrpc:read");
let (grant, secret) = issue(capability, GrantRights::DISCOVER);
let state = Arc::new(f.state(credentials(vec![grant.clone()])));
let unleased = ConsumerGrantSnapshot::empty();
assert_eq!(
state.route_handle(&capability, &unleased),
RouteLookup::Warm
);
for i in 0..61u32 {
assert_eq!(
state.route_handle(&cap(&format!("nrpc:fill{i}")), &unleased),
RouteLookup::Warm
);
}
assert_eq!(state.handles(), 62);
let leased = Arc::new(lease(&unleased, &grant, secret.expect("secret"), 1));
let before = state.mutate_acquisitions();
let start = Arc::new(std::sync::Barrier::new(4));
let threads: Vec<_> = (0..4)
.map(|_| {
let state = state.clone();
let start = start.clone();
let leased = leased.clone();
std::thread::spawn(move || {
start.wait();
state.acquire(&capability, &leased)
})
})
.collect();
for t in threads {
assert_eq!(
t.join().expect("join"),
RouteLookup::Warm,
"every rival adopts the winner's re-derivation"
);
}
assert_eq!(
state.mutate_acquisitions() - before,
4,
"all four genuinely entered the mutation section"
);
assert_eq!(
f.metrics.refused_family_at_capacity(),
0,
"a duplicate re-derivation would have overrun the budget and been refused"
);
assert_eq!(state.handles(), 63, "Owner + the new audience, once");
assert_eq!(state.entries(), 62, "one entry per capability, re-derived");
assert_eq!(
state.warm(&capability).expect("warm").demanded(),
&[owner_key(&capability), grant_key(&grant)]
);
assert_eq!(
state
.warm(&capability)
.expect("warm")
.demands()
.held_for_test(),
vec![owner_key(&capability), grant_key(&grant)],
"the surviving set owes exactly what it names"
);
assert_eq!(
state.route_handle(&cap("nrpc:after"), &leased),
RouteLookup::Warm,
"a duplicate transfer would have been refused above"
);
assert_eq!(state.handles(), 64);
}
#[test]
fn a_refused_rederivation_leaves_the_entry_exactly_as_it_was() {
let f = fixture();
let capability = cap("nrpc:read");
let (grant, secret) = issue(capability, GrantRights::DISCOVER);
let state = f.state(credentials(vec![grant.clone()]));
let unleased = ConsumerGrantSnapshot::empty();
assert_eq!(
state.route_handle(&capability, &unleased),
RouteLookup::Warm
);
for i in 0..63u32 {
assert_eq!(
state.route_handle(&cap(&format!("nrpc:c{i}")), &unleased),
RouteLookup::Warm
);
}
assert_eq!(state.handles(), 64);
let entries = state.entries();
let slots = f.registry.retained_slots();
let leased = lease(&unleased, &grant, secret.expect("secret"), 1);
assert_eq!(
state.route_handle(&capability, &leased),
RouteLookup::Cold(ColdReason::Refused(DemandRefused::FamilyAtCapacity)),
"the upgrade is refused, and refusal is what the caller is told"
);
assert_eq!(
state.handles(),
64,
"nothing was released for a refused set"
);
assert_eq!(state.entries(), entries);
assert_eq!(f.registry.retained_slots(), slots);
assert_eq!(
state.warm(&capability).expect("still retained").demanded(),
&[owner_key(&capability)],
"the entry is exactly what it was, still retained, still Owner-only"
);
assert_eq!(
state.route_handle(&capability, &leased),
RouteLookup::Cold(ColdReason::Refused(DemandRefused::FamilyAtCapacity))
);
assert_eq!(state.handles(), 64);
}
fn fill_node_to(f: &Fixture, target: usize) -> Vec<DemandHandle> {
let mut held = Vec::new();
let mut family = f.registry.new_family().expect("family");
let mut in_family = 0usize;
let mut seed = 0u32;
while f.registry.retained_slots() < target {
if in_family == MAX_HANDLES_PER_FAMILY {
family = f.registry.new_family().expect("family");
in_family = 0;
}
held.push(
family
.demand(SlotKey {
scope: PrivateAudienceScope::new(CapabilityAudienceScope::Grant {
grant_id: [0xF1; 32],
audience_handle: [0xF1; 32],
})
.expect("private"),
capability: cap(&format!("nrpc:nodefill{seed}")),
})
.expect("fill"),
);
in_family += 1;
seed += 1;
}
assert_eq!(f.registry.retained_slots(), target);
held
}
#[test]
fn a_narrowing_replacement_at_the_family_bound_is_charged_net() {
let f = fixture();
let changing = cap("nrpc:changing");
let (grant, secret) = issue(changing, GrantRights::DISCOVER);
let leased = lease(
&ConsumerGrantSnapshot::empty(),
&grant,
secret.expect("secret"),
1,
);
let state = f.state(credentials(vec![grant.clone()]));
assert_eq!(state.route_handle(&changing, &leased), RouteLookup::Warm);
assert_eq!(state.handles(), 2, "Owner + one leased audience");
fill_to_total(&state, &leased, 64);
assert_eq!(state.handles(), 64, "the family is EXACTLY at its bound");
let removed = remove(&leased, &grant.grant_id, 100);
assert_eq!(
state.route_handle(&changing, &removed),
RouteLookup::Warm,
"replacement capacity must be charged net of the entry it supersedes"
);
assert_eq!(state.handles(), 63);
assert_eq!(
state.warm(&changing).expect("warm").demanded(),
&[owner_key(&changing)],
"and the obsolete Grant scope is gone"
);
assert_eq!(f.metrics.refused_family_at_capacity(), 0);
}
#[test]
fn a_same_width_rotation_at_the_family_bound_is_charged_net() {
let f = fixture();
let changing = cap("nrpc:changing");
let (old_grant, old_secret) = issue(changing, GrantRights::DISCOVER);
let (new_grant, new_secret) = issue(changing, GrantRights::DISCOVER);
let leased = lease(
&ConsumerGrantSnapshot::empty(),
&old_grant,
old_secret.expect("secret"),
1,
);
let state = f.state(credentials(vec![old_grant.clone(), new_grant.clone()]));
assert_eq!(state.route_handle(&changing, &leased), RouteLookup::Warm);
fill_to_total(&state, &leased, 64);
assert_eq!(state.handles(), 64);
let slots_before = f.registry.retained_slots();
let rotated = lease(
&remove(&leased, &old_grant.grant_id, 100),
&new_grant,
new_secret.expect("secret"),
2,
);
assert_eq!(
state.route_handle(&changing, &rotated),
RouteLookup::Warm,
"a same-width rotation neither grows nor shrinks the footprint"
);
assert_eq!(state.handles(), 64, "still exactly at the bound");
assert_eq!(
state.warm(&changing).expect("warm").demanded(),
&[owner_key(&changing), grant_key(&new_grant)],
"the successor audience is retained"
);
assert!(
!state
.warm(&changing)
.expect("warm")
.demanded()
.contains(&grant_key(&old_grant)),
"and the superseded audience is not"
);
assert_eq!(
f.registry.retained_slots(),
slots_before,
"one slot retired as one was created"
);
assert_eq!(f.metrics.refused_family_at_capacity(), 0);
}
#[test]
fn a_rotation_at_the_node_bound_retires_the_slot_it_transfers() {
let f = fixture();
let changing = cap("nrpc:changing");
let (old_grant, old_secret) = issue(changing, GrantRights::DISCOVER);
let (new_grant, new_secret) = issue(changing, GrantRights::DISCOVER);
let leased = lease(
&ConsumerGrantSnapshot::empty(),
&old_grant,
old_secret.expect("secret"),
1,
);
let state = f.state(credentials(vec![old_grant.clone(), new_grant.clone()]));
assert_eq!(state.route_handle(&changing, &leased), RouteLookup::Warm);
let _fillers = fill_node_to(&f, MAX_NODE_SLOTS);
assert_eq!(f.registry.retained_slots(), MAX_NODE_SLOTS);
let rotated = lease(
&remove(&leased, &old_grant.grant_id, 100),
&new_grant,
new_secret.expect("secret"),
2,
);
assert_eq!(
state.route_handle(&changing, &rotated),
RouteLookup::Warm,
"the old exact slot retires as the new one is created"
);
assert_eq!(
f.registry.retained_slots(),
MAX_NODE_SLOTS,
"the node's final retained count is unchanged"
);
assert_eq!(
state.warm(&changing).expect("warm").demanded(),
&[owner_key(&changing), grant_key(&new_grant)]
);
assert_eq!(f.metrics.refused_node_at_capacity(), 0);
}
#[test]
fn a_rotation_at_the_node_bound_refuses_when_the_old_slot_is_shared() {
let f = fixture();
let changing = cap("nrpc:changing");
let (old_grant, old_secret) = issue(changing, GrantRights::DISCOVER);
let (new_grant, new_secret) = issue(changing, GrantRights::DISCOVER);
let leased = lease(
&ConsumerGrantSnapshot::empty(),
&old_grant,
old_secret.expect("secret"),
1,
);
let state = f.state(credentials(vec![old_grant.clone(), new_grant.clone()]));
assert_eq!(state.route_handle(&changing, &leased), RouteLookup::Warm);
let sharer = f.registry.new_family().expect("family");
let _shared = sharer
.demand(grant_key(&old_grant))
.expect("the slot is already retained, so this shares it");
let _fillers = fill_node_to(&f, MAX_NODE_SLOTS);
let handles_before = state.handles();
let entries_before = state.entries();
let rotated = lease(
&remove(&leased, &old_grant.grant_id, 100),
&new_grant,
new_secret.expect("secret"),
2,
);
assert_eq!(
state.route_handle(&changing, &rotated),
RouteLookup::Cold(ColdReason::Refused(DemandRefused::NodeAtCapacity)),
"the shared old slot frees nothing, so the new one is genuinely a 257th"
);
assert_eq!(f.registry.retained_slots(), MAX_NODE_SLOTS, "no slot moved");
assert_eq!(state.handles(), handles_before, "no handle moved");
assert_eq!(state.entries(), entries_before);
assert_eq!(
state.warm(&changing).expect("still retained").demanded(),
&[owner_key(&changing), grant_key(&old_grant)],
"and the superseded entry is exactly what it was"
);
}
#[test]
fn identity_exhaustion_during_a_replacement_refuses_with_no_effect() {
let f = fixture();
let changing = cap("nrpc:changing");
let (old_grant, old_secret) = issue(changing, GrantRights::DISCOVER);
let (new_grant, new_secret) = issue(changing, GrantRights::DISCOVER);
let leased = lease(
&ConsumerGrantSnapshot::empty(),
&old_grant,
old_secret.expect("secret"),
1,
);
let state = f.state(credentials(vec![old_grant.clone(), new_grant.clone()]));
assert_eq!(state.route_handle(&changing, &leased), RouteLookup::Warm);
let handles_before = state.handles();
let slots_before = f.registry.retained_slots();
f.registry.exhaust_ids_for_test();
let rotated = lease(
&remove(&leased, &old_grant.grant_id, 100),
&new_grant,
new_secret.expect("secret"),
2,
);
assert_eq!(
state.route_handle(&changing, &rotated),
RouteLookup::Cold(ColdReason::Refused(DemandRefused::IdSpaceExhausted)),
);
assert_eq!(f.metrics.refused_id_space_exhausted(), 1);
assert_eq!(state.handles(), handles_before, "nothing was released");
assert_eq!(f.registry.retained_slots(), slots_before);
assert_eq!(
state.warm(&changing).expect("still retained").demanded(),
&[owner_key(&changing), grant_key(&old_grant)],
"the old complete entry survives an exhausted replacement"
);
}
#[test]
fn a_narrowing_replacement_needs_no_identity_after_exhaustion() {
let f = fixture();
let changing = cap("nrpc:changing");
let (grant, secret) = issue(changing, GrantRights::DISCOVER);
let leased = lease(
&ConsumerGrantSnapshot::empty(),
&grant,
secret.expect("secret"),
1,
);
let state = f.state(credentials(vec![grant.clone()]));
assert_eq!(state.route_handle(&changing, &leased), RouteLookup::Warm);
assert_eq!(state.handles(), 2);
f.registry.exhaust_ids_for_test();
let removed = remove(&leased, &grant.grant_id, 100);
assert_eq!(
state.route_handle(&changing, &removed),
RouteLookup::Warm,
"shedding a scope creates no slot, so exhaustion cannot refuse it"
);
assert_eq!(state.handles(), 1);
assert_eq!(
state.warm(&changing).expect("warm").demanded(),
&[owner_key(&changing)]
);
assert_eq!(f.metrics.refused_id_space_exhausted(), 0);
}
#[test]
fn a_shared_old_replacement_succeeds_when_the_sharer_releases() {
let f = fixture();
let capability = cap("nrpc:changing");
let (old_grant, old_secret) = issue(capability, GrantRights::DISCOVER);
let (new_grant, new_secret) = issue(capability, GrantRights::DISCOVER);
let leased = lease(
&ConsumerGrantSnapshot::empty(),
&old_grant,
old_secret.expect("secret"),
1,
);
let state = f.state(credentials(vec![old_grant.clone(), new_grant.clone()]));
assert_eq!(state.route_handle(&capability, &leased), RouteLookup::Warm);
let sharer = f.registry.new_family().expect("family");
let shared = sharer.demand(grant_key(&old_grant)).expect("shares");
let _fillers = fill_node_to(&f, MAX_NODE_SLOTS);
let generation = f.registry.node_capacity_generation();
let rotated = lease(
&remove(&leased, &old_grant.grant_id, 100),
&new_grant,
new_secret.expect("secret"),
101,
);
assert_eq!(
state.route_handle(&capability, &rotated),
RouteLookup::Cold(ColdReason::Refused(DemandRefused::NodeAtCapacity)),
"the shared old slot frees nothing, so the new one is a 257th"
);
drop(shared);
assert_eq!(
f.registry.node_capacity_generation(),
generation,
"no retirement, so no capacity movement"
);
assert_eq!(
state.route_handle(&capability, &rotated),
RouteLookup::Warm,
"but the projection changed, and the replacement must be retried"
);
}
#[test]
fn the_under_lock_miss_race_retains_the_newest_snapshot() {
let f = fixture();
let capability = cap("nrpc:read");
let (grant, secret) = issue(capability, GrantRights::DISCOVER);
let state = f.state(credentials(vec![grant.clone()]));
let older = ConsumerGrantSnapshot::empty().stamped(GrantMovementFence::Publication(3));
let newer = lease(&older, &grant, secret.expect("secret"), 8);
assert_eq!(state.acquire(&capability, &newer), RouteLookup::Warm);
assert_eq!(
state.warm(&capability).expect("warm").demanded(),
&[owner_key(&capability), grant_key(&grant)]
);
assert_eq!(
state.acquire(&capability, &older),
RouteLookup::Cold(ColdReason::SnapshotSuperseded),
"the loser must not act on a view the family has moved past"
);
assert_eq!(
state.warm(&capability).expect("warm").demanded(),
&[owner_key(&capability), grant_key(&grant)],
"and the newest exact set is what stays retained"
);
assert_eq!(state.handles(), 2);
}
#[test]
fn the_under_lock_miss_recheck_validates_the_callers_snapshot() {
let f = fixture();
let capability = cap("nrpc:read");
let (grant, secret) = issue(capability, GrantRights::DISCOVER);
let state = f.state(credentials(vec![grant.clone()]));
let older = ConsumerGrantSnapshot::empty();
assert_eq!(state.route_handle(&capability, &older), RouteLookup::Warm);
assert_eq!(state.warm(&capability).expect("warm").demands().len(), 1);
let newer = lease(&older, &grant, secret.expect("secret"), 5);
assert_eq!(state.acquire(&capability, &newer), RouteLookup::Warm);
assert_eq!(
state.warm(&capability).expect("warm").demanded(),
&[owner_key(&capability), grant_key(&grant)],
"the loser of the race must not adopt an entry stale for ITS snapshot"
);
}
#[test]
fn the_under_lock_miss_recheck_sees_a_removal() {
let f = fixture();
let capability = cap("nrpc:read");
let (grant, secret) = issue(capability, GrantRights::DISCOVER);
let leased = lease(
&ConsumerGrantSnapshot::empty(),
&grant,
secret.expect("secret"),
1,
);
let state = f.state(credentials(vec![grant.clone()]));
assert_eq!(state.route_handle(&capability, &leased), RouteLookup::Warm);
assert_eq!(state.handles(), 2);
let removed = remove(&leased, &grant.grant_id, 100);
assert_eq!(state.acquire(&capability, &removed), RouteLookup::Warm);
assert_eq!(
state.warm(&capability).expect("warm").demanded(),
&[owner_key(&capability)]
);
}
#[test]
fn the_under_lock_miss_recheck_sees_a_rotation() {
let f = fixture();
let capability = cap("nrpc:read");
let (old_grant, old_secret) = issue(capability, GrantRights::DISCOVER);
let (new_grant, new_secret) = issue(capability, GrantRights::DISCOVER);
let leased = lease(
&ConsumerGrantSnapshot::empty(),
&old_grant,
old_secret.expect("secret"),
1,
);
let state = f.state(credentials(vec![old_grant.clone(), new_grant.clone()]));
assert_eq!(state.route_handle(&capability, &leased), RouteLookup::Warm);
let rotated = lease(
&remove(&leased, &old_grant.grant_id, 100),
&new_grant,
new_secret.expect("secret"),
101,
);
assert_eq!(state.acquire(&capability, &rotated), RouteLookup::Warm);
assert_eq!(
state.warm(&capability).expect("warm").demanded(),
&[owner_key(&capability), grant_key(&new_grant)]
);
}
#[test]
fn a_stalled_older_install_cannot_overwrite_a_newer_removal() {
let f = fixture();
let capability = cap("nrpc:read");
let (grant, secret) = issue(capability, GrantRights::DISCOVER);
let state = f.state(credentials(vec![grant.clone()]));
let older = lease(
&ConsumerGrantSnapshot::empty(),
&grant,
secret.expect("secret"),
5,
);
let newer = remove(&older, &grant.grant_id, 9);
assert_eq!(state.route_handle(&capability, &newer), RouteLookup::Warm);
assert_eq!(
state.warm(&capability).expect("warm").demanded(),
&[owner_key(&capability)]
);
assert_eq!(
state.route_handle(&capability, &older),
RouteLookup::Cold(ColdReason::SnapshotSuperseded),
"a stalled older snapshot must neither be served nor act"
);
assert_eq!(
state.warm(&capability).expect("warm").demanded(),
&[owner_key(&capability)],
"and the newer retained set is untouched"
);
assert_eq!(state.handles(), 1);
}
#[test]
fn a_stalled_older_removal_cannot_overwrite_a_newer_install() {
let f = fixture();
let capability = cap("nrpc:read");
let (grant, secret) = issue(capability, GrantRights::DISCOVER);
let state = f.state(credentials(vec![grant.clone()]));
let installed = lease(
&ConsumerGrantSnapshot::empty(),
&grant,
secret.expect("secret"),
9,
);
let older_absent = ConsumerGrantSnapshot::empty().stamped(GrantMovementFence::Publication(5));
assert_eq!(
state.route_handle(&capability, &installed),
RouteLookup::Warm
);
assert_eq!(state.handles(), 2);
assert_eq!(
state.route_handle(&capability, &older_absent),
RouteLookup::Cold(ColdReason::SnapshotSuperseded),
);
assert_eq!(state.handles(), 2, "the newer install survives");
assert_eq!(
state.warm(&capability).expect("warm").demanded(),
&[owner_key(&capability), grant_key(&grant)]
);
}
#[test]
fn a_terminal_snapshot_cannot_be_overwritten_by_an_ordinary_one() {
let f = fixture();
let capability = cap("nrpc:read");
let (grant, secret) = issue(capability, GrantRights::DISCOVER);
let state = f.state(credentials(vec![grant.clone()]));
let installed = lease(
&ConsumerGrantSnapshot::empty(),
&grant,
secret.expect("secret"),
5,
);
let terminal = installed
.without(&grant.grant_id)
.expect("the record was there")
.stamped(GrantMovementFence::Terminal);
assert_eq!(
state.route_handle(&capability, &terminal),
RouteLookup::Warm
);
assert_eq!(
state.warm(&capability).expect("warm").demanded(),
&[owner_key(&capability)]
);
assert_eq!(
state.route_handle(&capability, &installed),
RouteLookup::Cold(ColdReason::SnapshotSuperseded),
"no ordinary publication can follow a terminal one"
);
assert_eq!(state.handles(), 1);
}
#[test]
fn two_snapshots_at_one_revision_are_refused_as_an_invariant_breach() {
let f = fixture();
let capability = cap("nrpc:read");
let (grant, secret) = issue(capability, GrantRights::DISCOVER);
let state = f.state(credentials(vec![grant.clone()]));
let absent = ConsumerGrantSnapshot::empty().stamped(GrantMovementFence::Publication(7));
assert_eq!(state.route_handle(&capability, &absent), RouteLookup::Warm);
assert_eq!(state.handles(), 1);
let forged = lease(
&ConsumerGrantSnapshot::empty(),
&grant,
secret.expect("secret"),
1,
)
.stamped(GrantMovementFence::Publication(7));
assert_eq!(
state.route_handle(&capability, &forged),
RouteLookup::Cold(ColdReason::SnapshotSuperseded),
"one transition identity, two contents — fail closed"
);
assert_eq!(state.handles(), 1, "and nothing moved");
}
#[test]
fn unrelated_newer_movement_advances_freshness_without_churn() {
let f = fixture();
let capability = cap("nrpc:read");
let (grant, secret) = issue(capability, GrantRights::DISCOVER);
let (unrelated, unrelated_secret) = issue(cap("nrpc:other"), GrantRights::DISCOVER);
let state = f.state(credentials(vec![grant.clone(), unrelated.clone()]));
let older = lease(
&ConsumerGrantSnapshot::empty(),
&grant,
secret.expect("secret"),
5,
);
assert_eq!(state.route_handle(&capability, &older), RouteLookup::Warm);
let acquisitions = state.mutate_acquisitions();
let handles = state.handles();
let newer = lease(&older, &unrelated, unrelated_secret.expect("secret"), 9);
assert_eq!(state.route_handle(&capability, &newer), RouteLookup::Warm);
assert_eq!(
state.mutate_acquisitions(),
acquisitions,
"an irrelevant movement re-derives nothing and takes no lock"
);
assert_eq!(state.handles(), handles);
assert_eq!(
state.route_handle(&capability, &older),
RouteLookup::Cold(ColdReason::SnapshotSuperseded),
"freshness must advance even when demand does not"
);
}
#[test]
fn a_current_warmed_entry_with_a_leased_audience_takes_no_lock() {
let f = fixture();
let capability = cap("nrpc:read");
let (grant, secret) = issue(capability, GrantRights::DISCOVER);
let leased = lease(
&ConsumerGrantSnapshot::empty(),
&grant,
secret.expect("secret"),
1,
);
let state = f.state(credentials(vec![grant]));
assert_eq!(state.route_handle(&capability, &leased), RouteLookup::Warm);
let after_miss = state.mutate_acquisitions();
assert_eq!(after_miss, 1);
for _ in 0..1_000 {
assert_eq!(state.route_handle(&capability, &leased), RouteLookup::Warm);
}
assert_eq!(
state.mutate_acquisitions(),
after_miss,
"a current entry is answered without the mutation lock, Grant plane and all"
);
}
#[test]
fn the_capability_index_derives_exactly_what_the_full_scan_derives() {
let f = fixture();
let read = cap("nrpc:read");
let write = cap("nrpc:write");
let mut grants = Vec::new();
let mut leased = ConsumerGrantSnapshot::empty();
let mut seq = 0u64;
for _ in 0..2 {
let (grant, secret) = issue(read, GrantRights::DISCOVER);
seq += 1;
leased = lease(&leased, &grant, secret.expect("secret"), seq);
grants.push(grant);
}
grants.push(issue(read, GrantRights::INVOKE).0);
grants.push(issue(read, GrantRights::DISCOVER).0);
let (leased_write, secret) = issue(write, GrantRights::DISCOVER);
leased = lease(&leased, &leased_write, secret.expect("secret"), seq + 1);
grants.push(leased_write);
let credentials = credentials(grants);
let state = f.state(credentials.clone());
for capability in [read, write, cap("nrpc:absent")] {
assert_eq!(
state.demand_set(&capability, &leased),
demand_set_for(&credentials, &capability, &leased),
"the index is a filter of the credential set, never a second rule"
);
}
}
#[test]
fn dropping_the_state_releases_every_demand() {
let capability = cap("nrpc:read");
let f = fixture();
let (grant, secret) = issue(capability, GrantRights::DISCOVER);
let leased = lease(
&ConsumerGrantSnapshot::empty(),
&grant,
secret.expect("secret"),
1,
);
let state = f.state(credentials(vec![grant]));
assert_eq!(state.route_handle(&capability, &leased), RouteLookup::Warm);
assert_eq!(f.registry.retained_slots(), 2);
drop(state);
assert_eq!(
f.registry.retained_slots(),
0,
"ownership is the whole lifecycle — no separate teardown to forget"
);
assert_eq!(f.metrics.slots_retired(), 2);
}