@@ -96,6 +96,58 @@ def test_checkpoint_copy_is_suppressed_before_allocation_when_it_exceeds_store_b
9696 assert not memory .allow_checkpoint (cache )
9797
9898
99+ def retained_prefix_memory (budget ):
100+ """An in-flight cache and an unrelated retained prefix compete for the same MLX budget."""
101+
102+ work = populated (64 )
103+ store = CheckpointStore (3 , copier = lambda cache : cache , budget_bytes = 1 << 20 , sizer = cache_nbytes )
104+ store .insert ([1 ], populated (64 ), last_prompt = [1 ])
105+ runtime = Runtime ()
106+ runtime .cache = 128
107+ runtime .get_active_memory = lambda : runtime .resident + store .nbytes + cache_nbytes (work )
108+ model = SimpleNamespace (args = SimpleNamespace (num_attention_heads = 1 , head_dim = 128 ))
109+ memory = PromptMemory (budget , model , runtime = runtime , store = store , overhead_bytes = 0 ,
110+ bootstrap_bytes = 0 )
111+ memory .begin (64 , 0 , admit = False )
112+ memory .observe_cache (work , workspace = False )
113+ return memory , runtime , store , work
114+
115+
116+ def test_impossible_checkpoint_copy_preserves_retained_prefixes ():
117+ memory , runtime , store , work = retained_prefix_memory (3200 )
118+ size = cache_nbytes (work )
119+ assert memory .projected (64 , current_cache = work , extra_bytes = size ) - runtime .cache - store .nbytes > memory .budget
120+
121+ assert not memory .allow_checkpoint (work )
122+ assert store .match ([1 , 2 ]) is not None
123+ assert store .evictions == 0
124+ assert runtime .cache == 128
125+
126+
127+ def test_impossible_snapshot_load_preserves_retained_prefixes ():
128+ memory , runtime , store , work = retained_prefix_memory (3500 )
129+ size = cache_nbytes (work )
130+ assert memory .projected (64 , extra_bytes = size ) - runtime .cache - store .nbytes > memory .budget
131+
132+ assert not memory .allow_load (size )
133+ assert store .match ([1 , 2 ]) is not None
134+ assert store .evictions == 0
135+ assert runtime .cache == 128
136+
137+
138+ @pytest .mark .parametrize ("kind,budget" , [("checkpoint" , 3400 ), ("load" , 3600 )])
139+ def test_reclaim_still_admits_a_copy_that_can_fit (kind , budget ):
140+ memory , runtime , store , work = retained_prefix_memory (budget )
141+ size = cache_nbytes (work )
142+ assert memory .projected (64 , current_cache = work if kind == "checkpoint" else None ,
143+ extra_bytes = size ) > memory .budget
144+
145+ allowed = memory .allow_checkpoint (work ) if kind == "checkpoint" else memory .allow_load (size )
146+ assert allowed
147+ assert runtime .cache == 0
148+ assert store .evictions == 1
149+
150+
99151def test_retained_prefixes_are_evicted_before_refusing_the_next_request ():
100152 cache = populated ()
101153 runtime = Runtime ()
0 commit comments