From 99d6f4e158611b144ee5e371833cbea02089dbdf Mon Sep 17 00:00:00 2001 From: Shuwen Wang <47200617+alphabetc1@users.noreply.github.com> Date: Sat, 10 Oct 2026 22:43:49 +0800 Subject: [PATCH] [MemCache] refactor: require an anchored lock receipt for non-root releases (#41452) --- .../sglang/srt/mem_cache/base_prefix_cache.py | 3 +- .../unified_cache/unified_tree_core.py | 4 +- .../src/tests/components/full.rs | 29 +++- .../src/tests/components/swa.rs | 127 ++++++++++++++++- .../src/tests/unified_tree_core.rs | 24 +++- .../src/unified_tree_core.rs | 21 ++- .../test_rust_tree_core_integration.py | 7 +- .../test_unified_radix_cache_unittest.py | 131 +++++++++++++++++- 8 files changed, 302 insertions(+), 44 deletions(-) diff --git a/python/sglang/srt/mem_cache/base_prefix_cache.py b/python/sglang/srt/mem_cache/base_prefix_cache.py index c58f387ca2..a78cb581f3 100644 --- a/python/sglang/srt/mem_cache/base_prefix_cache.py +++ b/python/sglang/srt/mem_cache/base_prefix_cache.py @@ -218,8 +218,7 @@ class DecLockRefParams: A segment release requires its component's boundary entry; a missing entry must not be treated as a lock reaching the root. ``node_id`` is - ``None`` only for receipts that never came from a unified-tree acquire - (legacy caches, session sentinels). + ``None`` only for legacy caches; the unified tree rejects such a receipt. """ node_id: Optional[int] = None diff --git a/python/sglang/srt/mem_cache/unified_cache/unified_tree_core.py b/python/sglang/srt/mem_cache/unified_cache/unified_tree_core.py index 68f97bd604..bca490ea9f 100644 --- a/python/sglang/srt/mem_cache/unified_cache/unified_tree_core.py +++ b/python/sglang/srt/mem_cache/unified_cache/unified_tree_core.py @@ -696,8 +696,8 @@ class UnifiedTreeCore(UnifiedTreeCoreInterface): @staticmethod def _assert_receipt_anchor(node: UnifiedTreeNode, params: DecLockRefParams) -> None: """A receipt releases only the node its acquire returned; a mispaired - node would silently release (or steal) another holder's segment.""" - assert params.node_id is None or params.node_id == node.id, ( + or unanchored one would silently release (or steal) another holder's segment.""" + assert params.node_id == node.id, ( f"lock receipt anchored on node {params.node_id} released on node {node.id}" ) diff --git a/rust/sglang-radix-tree/src/tests/components/full.rs b/rust/sglang-radix-tree/src/tests/components/full.rs index e4de3ae28c..58da8ade48 100644 --- a/rust/sglang-radix-tree/src/tests/components/full.rs +++ b/rust/sglang-radix-tree/src/tests/components/full.rs @@ -865,11 +865,7 @@ fn lock_round_trips_on_a_root_anchor_are_noops() { assert_eq!(tc.arena.device_lock_ref(root, FULL), 1); tc.dec_lock_ref( tc.arena.node(root).id, - /* params = */ - &DecLockRefParams { - skipped_lock_components: ComponentSet::EMPTY, - ..Default::default() - }, + /* params = */ &result.to_dec_params(), /* skip_swa = */ false, ) .expect("live test node"); @@ -904,6 +900,7 @@ fn lock_walks_stop_at_the_root_of_a_salted_chain() { tc.arena.node(n1).id, /* params = */ &DecLockRefParams { + node_id: Some(tc.arena.node(n1).id), skipped_lock_components: ComponentSet::EMPTY, ..Default::default() }, @@ -946,6 +943,7 @@ fn lock_walks_treat_a_present_but_empty_value_as_device_on() { tc.arena.node(n1).id, /* params = */ &DecLockRefParams { + node_id: Some(tc.arena.node(n1).id), skipped_lock_components: ComponentSet::EMPTY, ..Default::default() }, @@ -968,6 +966,7 @@ fn dec_lock_ref_unlocks_and_restores_sizes() { tc.arena.node(n2).id, /* params = */ &DecLockRefParams { + node_id: Some(tc.arena.node(n2).id), skipped_lock_components: ComponentSet::EMPTY, ..Default::default() }, @@ -1022,6 +1021,7 @@ fn dec_lock_ref_replays_the_skip_set() { .inc_lock_ref(tc.arena.node(n3).id, ComponentSet::EMPTY) .expect("live test node"); let params = DecLockRefParams { + node_id: Some(tc.arena.node(n3).id), skipped_lock_components: result.skipped_lock_components, ..Default::default() }; @@ -1093,6 +1093,7 @@ fn temp_lock_counts_the_evicted_anchor_and_mirrors_on_release() { assert_eq!(tc.arena.device_lock_ref(a, FULL), 2); // Each release takes back exactly its own refs. let temp_params = DecLockRefParams { + node_id: Some(tc.arena.node(anchor).id), skipped_lock_components: temp_lock.skipped_lock_components, ..Default::default() }; @@ -1106,6 +1107,7 @@ fn temp_lock_counts_the_evicted_anchor_and_mirrors_on_release() { assert_eq!(tc.arena.device_lock_ref(y, FULL), 1); assert_eq!(tc.arena.device_lock_ref(a, FULL), 1); let second_params = DecLockRefParams { + node_id: Some(tc.arena.node(anchor).id), skipped_lock_components: second_lock.skipped_lock_components, ..Default::default() }; @@ -1153,6 +1155,7 @@ fn dec_lock_ref_panics_on_double_release() { tc.arena.node(n2).id, /* params = */ &DecLockRefParams { + node_id: Some(tc.arena.node(n2).id), skipped_lock_components: ComponentSet::EMPTY, ..Default::default() }, @@ -1163,6 +1166,7 @@ fn dec_lock_ref_panics_on_double_release() { tc.arena.node(n2).id, /* params = */ &DecLockRefParams { + node_id: Some(tc.arena.node(n2).id), skipped_lock_components: ComponentSet::EMPTY, ..Default::default() }, @@ -1181,6 +1185,7 @@ fn dec_lock_ref_with_skip_swa_still_releases_full() { tc.arena.node(n2).id, /* params = */ &DecLockRefParams { + node_id: Some(tc.arena.node(n2).id), skipped_lock_components: ComponentSet::EMPTY, ..Default::default() }, @@ -1203,6 +1208,7 @@ fn nested_locks_release_pairwise() { tc.arena.node(n2).id, /* params = */ &DecLockRefParams { + node_id: Some(tc.arena.node(n2).id), skipped_lock_components: ComponentSet::EMPTY, ..Default::default() }, @@ -1217,6 +1223,7 @@ fn nested_locks_release_pairwise() { tc.arena.node(n2).id, /* params = */ &DecLockRefParams { + node_id: Some(tc.arena.node(n2).id), skipped_lock_components: ComponentSet::EMPTY, ..Default::default() }, @@ -1238,6 +1245,7 @@ fn dec_lock_ref_panics_on_an_unlocked_node() { tc.arena.node(n2).id, /* params = */ &DecLockRefParams { + node_id: Some(tc.arena.node(n2).id), skipped_lock_components: ComponentSet::EMPTY, ..Default::default() }, @@ -1310,6 +1318,7 @@ fn dec_lock_ref_panics_on_protected_underflow() { tc.arena.node(n2).id, /* params = */ &DecLockRefParams { + node_id: Some(tc.arena.node(n2).id), skipped_lock_components: ComponentSet::EMPTY, ..Default::default() }, @@ -1486,8 +1495,14 @@ fn dec_host_lock_ref_unpins_and_restores_the_h_leaf_set() { fn dec_host_lock_ref_on_an_unlocked_anchor_is_a_noop() { let mut tc = core(); let node = host_lock_anchor(&mut tc); - tc.dec_host_lock_ref(tc.arena.node(node).id, &DecLockRefParams::default()) - .expect("live test node"); + tc.dec_host_lock_ref( + tc.arena.node(node).id, + &DecLockRefParams { + node_id: Some(tc.arena.node(node).id), + ..Default::default() + }, + ) + .expect("live test node"); assert_eq!(tc.arena.host_lock_ref(node, FULL), 0); } diff --git a/rust/sglang-radix-tree/src/tests/components/swa.rs b/rust/sglang-radix-tree/src/tests/components/swa.rs index 563e96026c..ef7c8fabb0 100644 --- a/rust/sglang-radix-tree/src/tests/components/swa.rs +++ b/rust/sglang-radix-tree/src/tests/components/swa.rs @@ -2018,6 +2018,104 @@ fn inc_host_lock_ref_runs_full_and_swa_host_arms_together() { assert!(tc.evictable_host_leaves.contains(c)); } +#[test] +fn unanchored_receipts_are_rejected_before_any_release() { + use std::panic::{AssertUnwindSafe, catch_unwind}; + + let mut tc = swa_core(/* window = */ 2, /* page_size = */ 1); + let [a, b, c] = chain(&mut tc); + for node in [a, b, c] { + store_swa_device(&mut tc, node); + set_swa_host(&mut tc, node); + } + tc.arena + .set_host_value(c, FULL, Tensor::from_slice(&[0i64])); + let leaf = tc.arena.node(c).id; + let device_lock = tc + .inc_lock_ref(leaf, ComponentSet::EMPTY) + .expect("live test node"); + let host_lock = tc.inc_host_lock_ref(leaf).expect("live test node"); + let unanchored = |lock: &IncLockRefResult| DecLockRefParams { + node_id: None, + ..lock.to_dec_params() + }; + let lock_state = |tc: &UnifiedTreeCore>| { + let refs: Vec<_> = [a, b, c] + .into_iter() + .flat_map(|n| [FULL, SWA].map(|ct| (n, ct))) + .map(|(n, ct)| { + ( + tc.arena.device_lock_ref(n, ct), + tc.arena.host_lock_ref(n, ct), + ) + }) + .collect(); + let sizes = ( + tc.protected_size(), + tc.swa_protected_size(), + tc.swa_evictable_size(), + ); + (refs, sizes) + }; + let before = lock_state(&tc); + let mut device_frees = HashMap::new(); + let mut host_frees = HashMap::new(); + + assert!( + catch_unwind(AssertUnwindSafe(|| { + tc.dec_lock_ref(leaf, &unanchored(&device_lock), /* skip_swa = */ false) + })) + .is_err() + ); + assert!( + catch_unwind(AssertUnwindSafe(|| { + tc.dec_host_lock_ref(leaf, &unanchored(&host_lock)) + })) + .is_err() + ); + assert!( + catch_unwind(AssertUnwindSafe(|| { + tc.dec_swa_lock_only( + leaf, + &unanchored(&device_lock), + &mut device_frees, + &mut host_frees, + ) + })) + .is_err() + ); + assert!( + catch_unwind(AssertUnwindSafe(|| { + tc.dec_window_lock_only( + leaf, + SWA, + &unanchored(&device_lock), + &mut device_frees, + &mut host_frees, + ) + })) + .is_err() + ); + assert_eq!(lock_state(&tc), before); + assert!(device_frees.is_empty() && host_frees.is_empty()); + + // The anchored receipts still release exactly what was acquired. + tc.dec_lock_ref( + leaf, + &device_lock.to_dec_params(), + /* skip_swa = */ false, + ) + .expect("live test node"); + tc.dec_host_lock_ref(leaf, &host_lock.to_dec_params()) + .expect("live test node"); + for node in [a, b, c] { + for ct in [FULL, SWA] { + assert_eq!(tc.arena.device_lock_ref(node, ct), 0); + assert_eq!(tc.arena.host_lock_ref(node, ct), 0); + } + } +} + #[test] fn dec_host_lock_ref_with_the_inner_uuid_leaves_an_outer_window_pinned() { let mut tc = swa_core(/* window = */ 2, /* page_size = */ 1); @@ -2581,7 +2679,10 @@ fn dec_window_lock_only_ignores_root_and_skipped_window() { tc.dec_window_lock_only( tc.arena.node(tc.arena.root()).id, SWA, - &DecLockRefParams::default(), + &DecLockRefParams { + node_id: Some(tc.arena.node(tc.arena.root()).id), + ..Default::default() + }, &mut device_frees, &mut host_frees, ) @@ -2661,10 +2762,14 @@ fn dec_swa_lock_only_evicts_a_fully_unlocked_device_leaf() { .set_device_value(node, FULL, Tensor::from_slice(&vec![9i64; len])); } let swa = swa_component(2); + let c_id = tc.arena.node(c).id; let result = swa.acquire_component_lock( &mut tc, c, - IncLockRefResult::default(), + IncLockRefResult { + node_id: Some(c_id), + ..Default::default() + }, /* lock_host = */ false, ); let mut device_frees = HashMap::new(); @@ -2695,6 +2800,7 @@ fn dec_swa_lock_only_is_a_noop_without_the_swa_component() { tc.dec_swa_lock_only( tc.arena.node(root).id, &DecLockRefParams { + node_id: Some(tc.arena.node(root).id), skipped_lock_components: ComponentSet::EMPTY, ..Default::default() }, @@ -2815,16 +2921,23 @@ fn dec_swa_lock_only_releases_the_window_exactly_once() { store_swa_device(&mut tc, b); store_swa_device(&mut tc, c); let swa = swa_component(2); + let c_id = tc.arena.node(c).id; let first = swa.acquire_component_lock( &mut tc, c, - IncLockRefResult::default(), + IncLockRefResult { + node_id: Some(c_id), + ..Default::default() + }, /* lock_host = */ false, ); let _ = swa.acquire_component_lock( &mut tc, c, - IncLockRefResult::default(), + IncLockRefResult { + node_id: Some(c_id), + ..Default::default() + }, /* lock_host = */ false, ); let mut device_frees = HashMap::new(); @@ -2863,10 +2976,14 @@ fn dec_swa_lock_only_leaves_out_of_window_swa_locks_alone() { store_swa_device(&mut tc, b); store_swa_device(&mut tc, c); let swa = swa_component(2); + let c_id = tc.arena.node(c).id; let result = swa.acquire_component_lock( &mut tc, c, - IncLockRefResult::default(), + IncLockRefResult { + node_id: Some(c_id), + ..Default::default() + }, /* lock_host = */ false, ); // A holds a lock beyond the window (e.g. another request's window). diff --git a/rust/sglang-radix-tree/src/tests/unified_tree_core.rs b/rust/sglang-radix-tree/src/tests/unified_tree_core.rs index 36076a57db..036694e2d9 100644 --- a/rust/sglang-radix-tree/src/tests/unified_tree_core.rs +++ b/rust/sglang-radix-tree/src/tests/unified_tree_core.rs @@ -518,6 +518,7 @@ fn dec_lock_ref_skip_swa_skips_the_swa_component() { tc.arena.node(n1).id, /* params = */ &DecLockRefParams { + node_id: Some(tc.arena.node(n1).id), skipped_lock_components: ComponentSet::EMPTY, ..Default::default() }, @@ -558,6 +559,7 @@ fn dec_lock_ref_without_skip_swa_reaches_every_component() { tc.arena.node(n1).id, /* params = */ &DecLockRefParams { + node_id: Some(tc.arena.node(n1).id), skipped_lock_components: ComponentSet::EMPTY, ..Default::default() }, @@ -639,6 +641,7 @@ fn dec_swa_lock_only_dispatches_lower_priority_releases() { let _ = tc.dec_swa_lock_only( tc.arena.node(root).id, &DecLockRefParams { + node_id: Some(tc.arena.node(root).id), component_lock_uuids: HashMap::from([(SWA.idx() as u8, Some(7))]), skipped_lock_components: ComponentSet::EMPTY, ..Default::default() @@ -673,10 +676,14 @@ fn dec_swa_lock_only_returns_device_frees_in_the_device_dict() { swa_sliding_window_size: Some(2), ..Default::default() }); + let a_id = tc.arena.node(a).id; let result = swa.acquire_component_lock( &mut tc, a, - IncLockRefResult::default(), + IncLockRefResult { + node_id: Some(a_id), + ..Default::default() + }, /* lock_host = */ false, ); let mut device_frees = HashMap::new(); @@ -4474,6 +4481,7 @@ fn commit_load_back_reattaches_device_slices_and_restores_the_match() { tc.arena.node(child).id, /* params = */ &DecLockRefParams { + node_id: Some(tc.arena.node(child).id), skipped_lock_components: ComponentSet::EMPTY, ..Default::default() }, @@ -7399,6 +7407,11 @@ fn sanity_check_passes_on_a_healthy_tree() { .id, /* params = */ &DecLockRefParams { + node_id: Some( + tc.arena + .node(tc.arena.resolve(leaf).expect("live test node")) + .id, + ), skipped_lock_components: ComponentSet::EMPTY, ..Default::default() }, @@ -8974,16 +8987,13 @@ fn a_zero_length_match_anchors_at_the_root() { .best_match_node_id; assert_eq!(anchor, tc.root_node_handle(Some("salted"))); // The root handle stays valid across a full namespace eviction. - tc.inc_lock_ref(anchor, ComponentSet::EMPTY) + let lock = tc + .inc_lock_ref(anchor, ComponentSet::EMPTY) .expect("live root"); drain_full_device(&mut tc); tc.dec_lock_ref( anchor, - /* params = */ - &DecLockRefParams { - skipped_lock_components: ComponentSet::EMPTY, - ..Default::default() - }, + /* params = */ &lock.to_dec_params(), /* skip_swa = */ false, ) .expect("live root"); diff --git a/rust/sglang-radix-tree/src/unified_tree_core.rs b/rust/sglang-radix-tree/src/unified_tree_core.rs index c828142483..17bed94236 100644 --- a/rust/sglang-radix-tree/src/unified_tree_core.rs +++ b/rust/sglang-radix-tree/src/unified_tree_core.rs @@ -90,8 +90,8 @@ impl IncLockRefResult { /// Receipt required by `dec_lock_ref`. #[derive(Default)] pub struct DecLockRefParams { - /// The node the matching acquire locked; None only for receipts that did - /// not come from this core (a mispaired anchor is a protocol violation). + /// The node the matching acquire locked; a missing or mispaired anchor is + /// a protocol violation. pub node_id: Option, /// Components the matching acquire left untaken. pub skipped_lock_components: ComponentSet, @@ -974,16 +974,15 @@ impl UnifiedTreeCore { Ok(()) } - /// A receipt releases only the node its acquire returned; a mispaired - /// node would silently release (or steal) another holder's segment. + /// A receipt releases only the node its acquire returned; a mispaired or + /// unanchored one would silently release (or steal) another holder's segment. fn assert_receipt_anchor_(&self, node_idx: NodeIdx_, params: &DecLockRefParams) { - if let Some(anchor) = params.node_id { - let node_handle = self.arena.node(node_idx).id; - assert!( - anchor == node_handle, - "lock receipt anchored on node {anchor} released on node {node_handle}" - ); - } + let node_handle = self.arena.node(node_idx).id; + assert!( + params.node_id == Some(node_handle), + "lock receipt anchored on node {:?} released on node {node_handle}", + params.node_id + ); } /// Release each component this receipt acquired. Auxiliaries go first so diff --git a/test/registered/unit/mem_cache/test_rust_tree_core_integration.py b/test/registered/unit/mem_cache/test_rust_tree_core_integration.py index f0fced1eeb..16885de4da 100644 --- a/test/registered/unit/mem_cache/test_rust_tree_core_integration.py +++ b/test/registered/unit/mem_cache/test_rust_tree_core_integration.py @@ -1285,9 +1285,10 @@ def test_empty_match_result_is_root_anchored(swa): assert empty.best_match_node == probe.best_match_node assert empty.last_device_node == probe.last_device_node assert empty.last_host_node == probe.last_host_node - core.dec_lock_ref(empty.best_match_node, DecLockRefParams()) - core.dec_host_lock_ref(empty.best_match_node, DecLockRefParams()) - released = core.dec_swa_lock_only(empty.best_match_node, DecLockRefParams()) + receipt = DecLockRefParams(node_id=empty.best_match_node) + core.dec_lock_ref(empty.best_match_node, receipt) + core.dec_host_lock_ref(empty.best_match_node, receipt) + released = core.dec_swa_lock_only(empty.best_match_node, receipt) assert not released.device_frees assert not released.host_frees core.sanity_check([], []) diff --git a/test/registered/unit/mem_cache/test_unified_radix_cache_unittest.py b/test/registered/unit/mem_cache/test_unified_radix_cache_unittest.py index 7d36bfe8d9..f4775a9f99 100644 --- a/test/registered/unit/mem_cache/test_unified_radix_cache_unittest.py +++ b/test/registered/unit/mem_cache/test_unified_radix_cache_unittest.py @@ -2490,7 +2490,7 @@ class UnifiedRadixCacheSuite: ) cache.sanity_check() - cache.dec_lock_ref(node_a, DecLockRefParams(), skip_swa=True) + cache.dec_lock_ref(node_a, lock_result.to_dec_params(), skip_swa=True) cache.sanity_check() def test_mamba_opt_out_holder_cannot_release_another_holders_mamba_lock(self): @@ -2798,7 +2798,7 @@ class UnifiedRadixCacheSuite: "SWA stays in LRU for drive_eviction to pick later", ) - cache.dec_lock_ref(node_a, DecLockRefParams(), skip_swa=True) + cache.dec_lock_ref(node_a, lock_result.to_dec_params(), skip_swa=True) self.assertTrue(cache.tree_core.is_device_leaf(node_a)) cache.sanity_check() @@ -10458,7 +10458,7 @@ class TestResumableInsertWalkSWA(_InsertWalkSuite): self.assertEqual(_device_lock_ref(cache, node, ComponentType.SWA), 0) self.assertGreaterEqual(_device_lock_ref(cache, node, ComponentType.FULL), 1) - cache.dec_lock_ref(node, DecLockRefParams(), skip_swa=True) + cache.dec_lock_ref(node, lock_result.to_dec_params(), skip_swa=True) cache.sanity_check() @@ -11414,6 +11414,8 @@ class TestSegmentLockProtocol(_InsertWalkSuite): cfg = CacheConfig( components=(ComponentType.FULL, ComponentType.SWA), sliding_window_size=8 ) + _backup_node = UnifiedRadixCacheSuite._backup_node + _path_chain = UnifiedRadixCacheSuite._path_chain @staticmethod def _swa_ref(cache, node_id): @@ -11531,11 +11533,24 @@ class TestSegmentLockProtocol(_InsertWalkSuite): cache, _, _ = build_fixture(self.cfg) core = cache.tree_core root = cache.root_node_handle() - core.dec_lock_ref(root, DecLockRefParams()) - core.dec_host_lock_ref(root, DecLockRefParams()) - released = core.dec_swa_lock_only(root, DecLockRefParams()) + receipt = DecLockRefParams(node_id=root) + core.dec_lock_ref(root, receipt) + core.dec_host_lock_ref(root, receipt) + released = core.dec_swa_lock_only(root, receipt) self.assertFalse(released.device_frees) self.assertFalse(released.host_frees) + released = core.dec_window_lock_only(root, ComponentType.SWA, receipt) + self.assertFalse(released.device_frees) + self.assertFalse(released.host_frees) + cache.sanity_check() + + def test_root_acquire_receipt_releases_on_root(self): + """A cold request locks the root, so its receipt is anchored on root.""" + cache, _, _ = build_fixture(self.cfg) + root = cache.root_node_handle() + lock = cache.inc_lock_ref(root).to_dec_params() + self.assertEqual(lock.node_id, root) + cache.dec_lock_ref(root, lock) cache.sanity_check() def test_release_with_incorrect_root_boundary_fails_loud(self): @@ -11550,7 +11565,10 @@ class TestSegmentLockProtocol(_InsertWalkSuite): self._assert_protocol_violation( lambda: cache.dec_lock_ref( - leaf, DecLockRefParams(component_lock_uuids={ComponentType.SWA: None}) + leaf, + DecLockRefParams( + node_id=leaf, component_lock_uuids={ComponentType.SWA: None} + ), ), "lock_ref=0", ) @@ -11574,6 +11592,105 @@ class TestSegmentLockProtocol(_InsertWalkSuite): "lock receipt anchored on node", ) + def _locked_path_state(self, cache, allocator, leaf): + """Every lock count on the leaf's path plus every free-slot count.""" + refs = [ + (_device_lock_ref(cache, n, ct), _host_lock_ref(cache, n, ct)) + for n in self._full_path(cache, leaf) + for ct in self.cfg.components + ] + free_slots = [ + allocator.full_attn_allocator.available_size(), + allocator.swa_attn_allocator.available_size(), + ] + if cache.cache_controller is not None: + free_slots.append(cache.cache_controller.mem_pool_host.available_size()) + return refs, free_slots + + def _leaf_with_lock_path(self, *, hicache=False): + cache, allocator, req_to_token_pool = build_fixture(self.cfg) + if hicache: + self._init_hicache(cache, write_policy="write_back") + seq = self._make_seq(1, 2 * self.cfg.sliding_window_size) + self._insert(cache, allocator, req_to_token_pool, seq) + leaf = self._match_leaf(cache, seq) + self.assertFalse(cache.tree_core.is_root(leaf)) + return cache, allocator, leaf + + def _assert_unanchored_release_rejected( + self, cache, allocator, leaf, release, unlock + ): + """The anchor check runs before any lock count or free list changes.""" + before = self._locked_path_state(cache, allocator, leaf) + self._assert_protocol_violation(release, "lock receipt anchored on node") + if cache._tree_core_backend == "rust": + # A Rust panic poisons the core; the crate's own test checks state. + return + self.assertEqual(self._locked_path_state(cache, allocator, leaf), before) + unlock() + cache.sanity_check() + + def test_unanchored_device_release_fails_loud(self): + """#41261 replay: a receipt that lost its anchor must not walk the + node's segment and drop locks other holders own.""" + cache, allocator, leaf = self._leaf_with_lock_path() + lock = cache.inc_lock_ref(leaf).to_dec_params() + self._assert_unanchored_release_rejected( + cache, + allocator, + leaf, + lambda: cache.dec_lock_ref(leaf, replace(lock, node_id=None)), + lambda: cache.dec_lock_ref(leaf, lock), + ) + + def test_unanchored_host_release_fails_loud(self): + cache, allocator, leaf = self._leaf_with_lock_path(hicache=True) + self._backup_node(cache, leaf) + lock = cache.inc_host_lock_ref(leaf).to_dec_params() + self._assert_unanchored_release_rejected( + cache, + allocator, + leaf, + lambda: cache.dec_host_lock_ref(leaf, replace(lock, node_id=None)), + lambda: cache.dec_host_lock_ref(leaf, lock), + ) + + def test_unanchored_swa_only_release_fails_loud(self): + cache, allocator, leaf = self._leaf_with_lock_path() + lock = cache.inc_lock_ref(leaf).to_dec_params() + self._assert_unanchored_release_rejected( + cache, + allocator, + leaf, + lambda: cache.tree_core.dec_swa_lock_only( + leaf, replace(lock, node_id=None) + ), + lambda: cache.dec_lock_ref(leaf, lock), + ) + + def test_unanchored_window_only_release_fails_loud(self): + cache, allocator, leaf = self._leaf_with_lock_path() + lock = cache.inc_lock_ref(leaf).to_dec_params() + self._assert_unanchored_release_rejected( + cache, + allocator, + leaf, + lambda: cache.tree_core.dec_window_lock_only( + leaf, ComponentType.SWA, replace(lock, node_id=None) + ), + lambda: cache.dec_lock_ref(leaf, lock), + ) + + def test_unanchored_root_release_fails_loud(self): + """Every acquire anchors its receipt, root included; an unanchored + receipt lost its anchor upstream even where releasing is a no-op.""" + cache, _, _ = build_fixture(self.cfg) + root = cache.root_node_handle() + self._assert_protocol_violation( + lambda: cache.tree_core.dec_lock_ref(root, DecLockRefParams()), + "lock receipt anchored on node", + ) + def test_double_release_fails_loud(self): cache, allocator, req_to_token_pool = build_fixture(self.cfg) seq = self._make_seq(1, 2 * self.cfg.sliding_window_size)