From 786726907c7a73b9a03c6ed195bc33ff1e84d85e Mon Sep 17 00:00:00 2001 From: Brad Seiler Date: Fri, 20 Nov 2026 10:31:32 -0500 Subject: [PATCH] test(relay): cover member-cache invalidation routes and refill orders (#9748) ## Summary Add 54 cases that verify a relay cache refill cannot restore stale channel membership after invalidation. The cases cover stale grants and denials, reader and community isolation, and three orders in which reads can finish. The publish-wrapper cases exercise the local cache drop. The receiving handlers are tested separately. Both unit-test runners select the new cases. ### Related issue Test coverage for #9735 and #9742. ### Testing The read-cache lane passed all 26 tests on the reviewed tree. Both runners selected all three new tests. The draft will remain open while repository CI and human confirmation are pending. For manual verification, run `cargo test -p buzz-relay --lib state::tests::member_channel_invalidation_tests:: -- --nocapture` and expect three passes. Generated with Codex Signed-off-by: Brad Seiler --- Justfile | 2 +- crates/buzz-relay/src/state.rs | 64 +---- .../member_channel_invalidation_tests.rs | 236 ++++++++++++++++++ scripts/run-tests.sh | 4 +- 4 files changed, 241 insertions(+), 65 deletions(-) create mode 100644 crates/buzz-relay/src/state/tests/member_channel_invalidation_tests.rs diff --git a/Justfile b/Justfile index 7df65e3c24..410d47d862 100644 --- a/Justfile +++ b/Justfile @@ -666,7 +666,7 @@ test-unit: # overlong-host rejection and the ban disconnect's restriction-cache # drop. Infra-free; the # database URL refuses at once. Keep scripts/run-tests.sh in step. - cargo nextest run -p buzz-relay --lib -E 'test(=state::tests::admitted_index_follows_every_key_change) + test(/^shared_reads::tests::/) + test(/^membership_cache::tests::/) + test(/^community_active::tests::/) + test(=state::tests::concurrent_open_channel_misses_share_the_in_flight_read) + test(=state::tests::a_member_read_that_straddles_an_invalidation_is_not_cached) + test(=state::tests::a_member_snapshot_ages_from_its_read_not_its_insert) + test(=state::tests::overlapping_member_reads_cache_the_first_to_finish) + test(=state::tests::an_open_read_that_straddles_an_invalidation_is_not_cached) + test(=state::tests::concurrent_restriction_and_host_misses_share_the_in_flight_read) + test(=tenant::tests::app_state_resolver_serves_fresh_cached_hosts_only) + test(=tenant::tests::an_overlong_host_fails_closed_before_the_resolver) + test(=state::tests::disconnect_drops_the_cached_restriction_row)' + cargo nextest run -p buzz-relay --lib -E 'test(=state::tests::admitted_index_follows_every_key_change) + test(/^shared_reads::tests::/) + test(/^membership_cache::tests::/) + test(/^community_active::tests::/) + test(=state::tests::concurrent_open_channel_misses_share_the_in_flight_read) + test(/^state::tests::member_channel_invalidation_tests::/) + test(=state::tests::a_member_snapshot_ages_from_its_read_not_its_insert) + test(=state::tests::overlapping_member_reads_cache_the_first_to_finish) + test(=state::tests::an_open_read_that_straddles_an_invalidation_is_not_cached) + test(=state::tests::concurrent_restriction_and_host_misses_share_the_in_flight_read) + test(=tenant::tests::app_state_resolver_serves_fresh_cached_hosts_only) + test(=tenant::tests::an_overlong_host_fails_closed_before_the_resolver) + test(=state::tests::disconnect_drops_the_cached_restriction_row)' # Retain partially consumed mesh receives across housekeeping ticks. cargo nextest run -p buzz-relay --lib -E 'test(=mesh_boot::tests::demo_echo_retains_pending_receive_across_housekeeping_ticks)' # boot_lifecycle spawns the real relay binary and asserts its startup diff --git a/crates/buzz-relay/src/state.rs b/crates/buzz-relay/src/state.rs index b6f9ced80f..5d281a9aab 100644 --- a/crates/buzz-relay/src/state.rs +++ b/crates/buzz-relay/src/state.rs @@ -4768,69 +4768,7 @@ pub(crate) mod tests { panic!("the refill never started"); } - /// A member-channels read that straddles an invalidation of its key, - /// per user or community-wide, answers its own request but is not - /// cached, so a removal is not undone by a read that began before it. A - /// read with no invalidation is cached. - /// Mutation: publish without checking the load token, or drop the token - /// invalidation from either path → RED. - #[tokio::test] - async fn a_member_read_that_straddles_an_invalidation_is_not_cached() { - use buzz_db::channel_members::ChannelSet; - let state = test_state().await; - let community = CommunityId::from_uuid(Uuid::from_u128(0xAAAA)); - let pubkey = vec![7u8; 32]; - let key = (community, pubkey.clone()); - let revoked = Uuid::from_u128(1); - let stale = ChannelSet { - implicit: Vec::new(), - named_only: vec![(revoked, "system".to_owned())], - }; - let invalidations: [&dyn Fn(); 2] = [ - &|| state.invalidate_membership_local(community, revoked, &pubkey), - &|| state.invalidate_all_accessible_channels_local(community), - ]; - for (path, invalidate) in invalidations.into_iter().enumerate() { - let (release, held) = tokio::sync::oneshot::channel::<()>(); - let read = { - let stale = stale.clone(); - async move { - held.await.ok(); - Ok(read_now(stale)) - } - }; - let task = { - let state = state.clone(); - let key = key.clone(); - tokio::spawn(async move { state.member_channels(key, read).await }) - }; - until_loading(&state.member_channels_loads, &key).await; - invalidate(); - release.send(()).expect("read is waiting"); - let answered = task.await.expect("join").expect("read"); - assert_eq!( - *answered, stale, - "path {path}: the read answers its request" - ); - assert!( - state.member_channels_cache.get(&key).is_none(), - "path {path}: a read that straddles an invalidation is not cached" - ); - } - let fresh = ChannelSet::default(); - state - .member_channels(key.clone(), async { Ok(read_now(ChannelSet::default())) }) - .await - .expect("read"); - assert_eq!( - state - .member_channels_cache - .get(&key) - .map(|member| (*member.set).clone()), - Some(fresh), - "a read with no invalidation is cached" - ); - } + mod member_channel_invalidation_tests; /// Overlapping member reads for one key share a load token, so the first /// to finish is cached even while a later miss is still reading. Main diff --git a/crates/buzz-relay/src/state/tests/member_channel_invalidation_tests.rs b/crates/buzz-relay/src/state/tests/member_channel_invalidation_tests.rs new file mode 100644 index 0000000000..e868312ed7 --- /dev/null +++ b/crates/buzz-relay/src/state/tests/member_channel_invalidation_tests.rs @@ -0,0 +1,236 @@ +//! Membership discovery must not cache a snapshot from before invalidation. + +use super::*; +use buzz_db::channel_members::ChannelSet; + +type Key = (CommunityId, Vec); + +#[derive(Clone, Copy, Debug)] +enum Route { + MembershipLocal, + MembershipPublish, + MembershipReceived, + AccessibleLocal, + AccessiblePublish, + AccessibleReceived, + DeletedLocal, + DeletedPublish, + DeletedReceived, +} + +impl Route { + fn apply(self, state: &AppState, community: CommunityId, channel: Uuid, reader: &[u8]) { + let tenant = TenantContext::resolved(community, "cache.example.org"); + match self { + Self::MembershipLocal => state.invalidate_membership_local(community, channel, reader), + Self::MembershipPublish => state.invalidate_membership(&tenant, channel, reader), + Self::MembershipReceived => state.apply_cache_invalidation( + community, + CacheInvalidation::Membership { + channel_id: channel, + pubkey: reader.to_vec(), + }, + ), + Self::AccessibleLocal => state.invalidate_all_accessible_channels_local(community), + Self::AccessiblePublish => state.invalidate_all_accessible_channels(&tenant), + Self::AccessibleReceived => { + state.apply_cache_invalidation(community, CacheInvalidation::AccessibleAll) + } + Self::DeletedLocal => state.invalidate_channel_deleted_local(community), + Self::DeletedPublish => state.invalidate_channel_deleted(&tenant), + Self::DeletedReceived => { + state.apply_cache_invalidation(community, CacheInvalidation::ChannelDeleted) + } + } + } + + fn reader_only(self) -> bool { + matches!( + self, + Self::MembershipLocal | Self::MembershipPublish | Self::MembershipReceived + ) + } +} + +#[derive(Clone, Copy, Debug)] +enum Replacement { + NotStarted, + Completed, + Reading, +} + +fn cached(state: &AppState, key: &Key) -> Option { + state + .member_channels_cache + .get(key) + .map(|member| (*member.set).clone()) +} + +/// Pause a database snapshot after its connection checkout, before completion. +async fn held_read( + released: tokio::sync::oneshot::Receiver<()>, + set: ChannelSet, +) -> Result, buzz_db::DbError> { + let snapshot = read_now(set); + released.await.expect("release the read"); + Ok(snapshot) +} + +async fn check_routes(replacement: Replacement) { + let state = test_state().await; + for route in [ + Route::MembershipLocal, + Route::MembershipPublish, + Route::MembershipReceived, + Route::AccessibleLocal, + Route::AccessiblePublish, + Route::AccessibleReceived, + Route::DeletedLocal, + Route::DeletedPublish, + Route::DeletedReceived, + ] { + for joined in [false, true] { + let community = CommunityId::from_uuid(Uuid::new_v4()); + let neighbor = CommunityId::from_uuid(Uuid::new_v4()); + let reader = vec![1; 32]; + let key = (community, reader.clone()); + let stream = Uuid::new_v4(); + let channels = ChannelSet { + implicit: vec![stream], + named_only: vec![(Uuid::new_v4(), "system".to_owned())], + }; + let empty = ChannelSet::default(); + let (stale, fresh) = if joined { + (&empty, &channels) + } else { + (&channels, &empty) + }; + let context = format!("{route:?}, {replacement:?}, joined={joined}"); + + // Neither the cached nor in-flight sets of another community may + // be disturbed. A per-reader drop also spares other local readers. + let cached_peer = (community, vec![2; 32]); + let cached_neighbor = (neighbor, reader.clone()); + state.seed_member_channels(cached_peer.clone(), channels.clone()); + state.seed_member_channels(cached_neighbor.clone(), channels.clone()); + let loading_peer = (community, vec![3; 32]); + let loading_neighbor = (neighbor, vec![3; 32]); + let (release_peer, peer_released) = tokio::sync::oneshot::channel(); + let mut peer = Box::pin(state.member_channels( + loading_peer.clone(), + held_read(peer_released, channels.clone()), + )); + let (release_neighbor, neighbor_released) = tokio::sync::oneshot::channel(); + let mut other_community = Box::pin(state.member_channels( + loading_neighbor.clone(), + held_read(neighbor_released, channels.clone()), + )); + assert!(futures_util::poll!(peer.as_mut()).is_pending()); + assert!(futures_util::poll!(other_community.as_mut()).is_pending()); + + let (release_old, old_released) = tokio::sync::oneshot::channel(); + let mut old = Box::pin( + state.member_channels(key.clone(), held_read(old_released, stale.clone())), + ); + assert!(futures_util::poll!(old.as_mut()).is_pending()); + route.apply(&state, community, stream, &reader); + assert_eq!(cached(&state, &key), None, "{context}"); + assert_eq!( + cached(&state, &cached_peer), + route.reader_only().then(|| channels.clone()), + "{context}" + ); + assert_eq!( + cached(&state, &cached_neighbor), + Some(channels.clone()), + "{context}" + ); + + if matches!(replacement, Replacement::Completed) { + let answer = state + .member_channels(key.clone(), async { Ok(read_now(fresh.clone())) }) + .await + .unwrap(); + assert_eq!(*answer, *fresh, "{context}"); + } + let (release_new, new_released) = tokio::sync::oneshot::channel(); + let mut new = Box::pin( + state.member_channels(key.clone(), held_read(new_released, fresh.clone())), + ); + if matches!(replacement, Replacement::Reading) { + assert!(futures_util::poll!(new.as_mut()).is_pending()); + assert!(state.member_channels_loads.is_loading(&key), "{context}"); + } + + release_old.send(()).unwrap(); + assert_eq!( + *old.await.unwrap(), + *stale, + "{context}: old caller keeps its snapshot" + ); + assert_eq!( + cached(&state, &key), + matches!(replacement, Replacement::Completed).then(|| fresh.clone()), + "{context}: old read must neither refill nor overwrite" + ); + if matches!(replacement, Replacement::Reading) { + assert!( + state.member_channels_loads.is_loading(&key), + "{context}: old completion must not consume the new token" + ); + } + release_new.send(()).unwrap(); + assert_eq!(*new.await.unwrap(), *fresh, "{context}"); + assert_eq!( + cached(&state, &key), + Some(fresh.clone()), + "{context}: new snapshot is cached" + ); + let hit = state + .member_channels(key.clone(), async { panic!("a fresh hit must not read") }) + .await + .unwrap(); + assert_eq!(*hit, *fresh, "{context}"); + + release_peer.send(()).unwrap(); + release_neighbor.send(()).unwrap(); + assert_eq!(*peer.await.unwrap(), channels, "{context}"); + assert_eq!(*other_community.await.unwrap(), channels, "{context}"); + assert_eq!( + cached(&state, &loading_peer), + route.reader_only().then(|| channels.clone()), + "{context}: in-flight reader scope" + ); + assert_eq!( + cached(&state, &loading_neighbor), + Some(channels), + "{context}: in-flight community scope" + ); + } + } +} + +/// A read predating any invalidation route may answer its own caller, but +/// cannot refill the dropped set. Covers stale grants and stale denials for +/// both implicit and named-only channels, plus reader/community scoping. +/// Mutation: publish without checking the load token -> RED. +#[tokio::test] +async fn every_route_fences_a_fill_before_the_replacement_starts() { + check_routes(Replacement::NotStarted).await; +} + +/// A pre-invalidation read completing last must not overwrite a new snapshot. +/// Mutation: always run `publish` even when its token is no longer current -> RED. +#[tokio::test] +async fn every_route_preserves_a_completed_replacement() { + check_routes(Replacement::Completed).await; +} + +/// A new read has started but not published when the old read completes. +/// The old completion must neither fill the current generation nor consume +/// its token; the new read alone must cache the post-invalidation snapshot. +/// Mutation: publish using whichever token is current for the key -> RED. +#[tokio::test] +async fn every_route_preserves_a_still_reading_replacement() { + check_routes(Replacement::Reading).await; +} diff --git a/scripts/run-tests.sh b/scripts/run-tests.sh index 193799c3a0..8954836a27 100755 --- a/scripts/run-tests.sh +++ b/scripts/run-tests.sh @@ -422,7 +422,6 @@ run_unit_tests() { community_active::tests::invalidation_fences_an_in_flight_fill_and_its_waiters \ community_active::tests::errors_are_not_cached \ state::tests::concurrent_open_channel_misses_share_the_in_flight_read \ - state::tests::a_member_read_that_straddles_an_invalidation_is_not_cached \ state::tests::a_member_snapshot_ages_from_its_read_not_its_insert \ state::tests::overlapping_member_reads_cache_the_first_to_finish \ state::tests::an_open_read_that_straddles_an_invalidation_is_not_cached \ @@ -431,6 +430,9 @@ run_unit_tests() { tenant::tests::an_overlong_host_fails_closed_before_the_resolver \ state::tests::disconnect_drops_the_cached_restriction_row + run_test_step "buzz-relay member-channel invalidation route tests" \ + cargo test -p buzz-relay --lib state::tests::member_channel_invalidation_tests:: -- --nocapture + run_test_step "buzz-relay membership snapshot tests" \ cargo test -p buzz-relay --lib membership_cache::tests:: -- --nocapture