mlx_native/buffer_pool.rs
1//! [`MlxBufferPool`] — arena-style GPU buffer allocator with reuse.
2//!
3//! Buffers are bucketed by power-of-two sizes. When a buffer is released back
4//! to the pool, it is added to the free list for its size bucket. A subsequent
5//! `alloc` call will reuse a free buffer of compatible (>= requested) size
6//! rather than allocating new Metal memory.
7//!
8//! Two return-path patterns are supported and **must not be mixed within a
9//! single arena cycle**:
10//!
11//! * **Per-buffer** via [`release`](MlxBufferPool::release) — explicit return
12//! of a single buffer to the free list, suitable for ad-hoc patterns where
13//! the caller knows the precise lifetime of each buffer.
14//! * **Arena bulk** via [`reset`](MlxBufferPool::reset) — bulk-return of every
15//! buffer handed out by [`alloc`](MlxBufferPool::alloc) since the previous
16//! reset. Suitable for per-inference / per-decode-token arena patterns
17//! where no individual buffer's lifetime crosses the reset boundary.
18//!
19//! Internally, every `alloc` records an ARC-cloned `metal::Buffer` handle so
20//! that `reset` can bulk-recycle without requiring callers to enumerate every
21//! buffer individually. ARC retain on `metal::Buffer` is cheap (refcount inc).
22
23use std::collections::HashMap;
24
25use crate::buffer::MlxBuffer;
26use crate::device::MlxDevice;
27use crate::dtypes::DType;
28use crate::error::{MlxError, Result};
29
30/// Arena-style buffer pool that reuses Metal buffer allocations.
31///
32/// # Design
33///
34/// * Buffers are bucketed by their allocated size rounded up to the nearest
35/// power of two. This reduces fragmentation at the cost of occasionally
36/// over-allocating by up to 2x.
37/// * `release()` returns a single buffer; `reset()` returns all outstanding
38/// buffers handed out since the last reset.
39/// * The `MlxDevice` is passed in at every [`alloc`] call (rather than stored
40/// in the pool). This keeps the pool free of lifetime parameters so it
41/// can be embedded in any owner struct (e.g. the per-decode-token
42/// `DecodeBuffers` cache in hf2q's qwen35 forward path).
43///
44/// # Why an arena reset matters
45///
46/// In the per-decode-token hot path, each token allocates ~1750 Metal buffers
47/// for scratch / intermediate / parameter storage across attention, FFN, and
48/// linear-attention layers. Direct `MlxDevice::alloc_buffer()` calls hit
49/// Metal's allocator each time (5-30 µs each); pooling reuses the underlying
50/// `metal::Buffer` objects across token boundaries so steady-state allocation
51/// cost amortizes to near zero. See ADR-012 §Optimize / Task #15 for the
52/// MoE dwq46 0.90× parity gap that motivated this work.
53pub struct MlxBufferPool {
54 /// Free buffers keyed by their power-of-two bucket size.
55 free: HashMap<usize, Vec<metal::Buffer>>,
56 /// Buffers handed out by [`alloc`] since the last [`reset`]. Each entry
57 /// holds an ARC-cloned `metal::Buffer` so the pool's reference keeps the
58 /// underlying GPU allocation alive even after the caller's `MlxBuffer`
59 /// goes out of scope. [`reset`] drains this into [`free`].
60 in_use: Vec<(usize, metal::Buffer)>,
61 /// Residency set that owns the allocations registered by this pool.
62 residency_set: Option<crate::residency::ResidencySet>,
63 /// Unique Metal buffers this pool added to the residency set, keyed by
64 /// their stable contents pointer. This avoids double-removing buffers if
65 /// callers mix release/reset despite that pattern being unsupported.
66 resident_buffers: HashMap<usize, metal::Buffer>,
67}
68
69impl Default for MlxBufferPool {
70 fn default() -> Self {
71 Self::new()
72 }
73}
74
75impl MlxBufferPool {
76 /// Create a new empty buffer pool. The Metal device is passed to
77 /// [`alloc`] at every call site, so the pool itself is lifetime-free.
78 pub fn new() -> Self {
79 Self {
80 free: HashMap::new(),
81 in_use: Vec::new(),
82 residency_set: None,
83 resident_buffers: HashMap::new(),
84 }
85 }
86
87 /// Allocate a buffer from the pool.
88 ///
89 /// If a free buffer of compatible size exists in the pool, it is reused
90 /// (with updated dtype/shape metadata). Otherwise a new Metal buffer is
91 /// allocated from `device` at the bucket size so future reuse is
92 /// possible for any request up to that bucket.
93 ///
94 /// Each successful `alloc` registers the buffer in the pool's in-use
95 /// list (ARC clone — cheap), so a subsequent [`reset`] returns it to
96 /// the free list automatically.
97 pub fn alloc(
98 &mut self,
99 device: &MlxDevice,
100 byte_len: usize,
101 dtype: DType,
102 shape: Vec<usize>,
103 ) -> Result<MlxBuffer> {
104 let (buffer, added_residency) = self.alloc_inner(device, byte_len, dtype, shape)?;
105 if added_residency {
106 if let Some(set) = self.residency_set.as_ref() {
107 set.commit();
108 }
109 }
110 Ok(buffer)
111 }
112
113 /// Allocate several buffers and commit residency-set updates once.
114 pub fn alloc_batch<I>(&mut self, device: &MlxDevice, requests: I) -> Result<Vec<MlxBuffer>>
115 where
116 I: IntoIterator<Item = (usize, DType, Vec<usize>)>,
117 {
118 let mut buffers = Vec::new();
119 let mut added_residency = false;
120
121 for (byte_len, dtype, shape) in requests {
122 let (buffer, added) = self.alloc_inner(device, byte_len, dtype, shape)?;
123 added_residency |= added;
124 buffers.push(buffer);
125 }
126
127 if added_residency {
128 if let Some(set) = self.residency_set.as_ref() {
129 set.commit();
130 }
131 }
132
133 Ok(buffers)
134 }
135
136 fn alloc_inner(
137 &mut self,
138 device: &MlxDevice,
139 byte_len: usize,
140 dtype: DType,
141 shape: Vec<usize>,
142 ) -> Result<(MlxBuffer, bool)> {
143 let bucket = bucket_size(byte_len);
144 let mut added_residency = false;
145
146 // Try to reuse a free buffer from this bucket.
147 let metal_buf = self
148 .free
149 .get_mut(&bucket)
150 .and_then(|free_list| free_list.pop());
151
152 let metal_buf = match metal_buf {
153 Some(b) => b,
154 None => {
155 // Fresh allocation at bucket size.
156 let raw = device
157 .metal_device()
158 .new_buffer(bucket as u64, metal::MTLResourceOptions::StorageModeShared);
159 if raw.contents().is_null() {
160 return Err(MlxError::BufferAllocationError { bytes: bucket });
161 }
162 added_residency = self.register_residency_allocation(device, &raw)?;
163 raw
164 }
165 };
166
167 // Track the handout so reset() can recycle it. ARC clone is cheap.
168 self.in_use.push((bucket, metal_buf.clone()));
169
170 Ok((MlxBuffer::from_raw(metal_buf, dtype, shape), added_residency))
171 }
172
173 /// Return a single buffer to the pool's free list for future reuse.
174 ///
175 /// The Metal memory is **not** deallocated — it stays resident on the GPU
176 /// for fast reuse. `release` is the per-buffer alternative to [`reset`];
177 /// see the module docs for guidance on which to use.
178 ///
179 /// **Mixing `release` and `reset` within the same arena cycle is not
180 /// supported** — the pool's in-use list does not deduplicate, so a buffer
181 /// returned via `release` and then bulk-returned via `reset` would land in
182 /// the free list twice (each entry holds an ARC clone of the same Metal
183 /// buffer; the duplication wastes a free-list slot but is not a memory
184 /// leak — both clones drop together once popped). Pick one pattern per
185 /// arena cycle.
186 pub fn release(&mut self, buffer: MlxBuffer) {
187 let bucket = bucket_size(buffer.byte_len());
188 let metal_buf = buffer.into_inner();
189 self.free.entry(bucket).or_default().push(metal_buf);
190 }
191
192 /// Bulk-return every buffer handed out by [`alloc`] since the last reset
193 /// to the pool's free list.
194 ///
195 /// # Caller contract
196 ///
197 /// All `MlxBuffer` values returned by `alloc` since the last reset must be
198 /// out-of-scope (dropped) at the time `reset` is called. Reset transfers
199 /// the pool's ARC clones to the free list, where they become available to
200 /// subsequent [`alloc`] calls. If a caller is still holding an `MlxBuffer`
201 /// and a later `alloc` re-issues the underlying buffer, the two callers
202 /// will share GPU memory (aliasing). The Metal ARC keeps the storage
203 /// alive in either case, but writes from the new caller will be visible
204 /// to the stale caller — a correctness bug, not a memory error.
205 ///
206 /// In Rust's ownership model, locally-bound `MlxBuffer` values fall out of
207 /// scope at the end of their lexical block, making the per-decode-token
208 /// arena pattern safe by construction:
209 ///
210 /// ```ignore
211 /// loop {
212 /// pool.reset(); // start of token — recycle previous token's buffers
213 /// forward_pass(&pool); // many alloc(), no explicit release
214 /// } // forward_pass returns; locals dropped
215 /// ```
216 pub fn reset(&mut self) {
217 for (bucket, metal_buf) in self.in_use.drain(..) {
218 self.free.entry(bucket).or_default().push(metal_buf);
219 }
220 }
221
222 /// Register an externally-allocated buffer with this pool's residency set
223 /// without taking ownership.
224 ///
225 /// # Why this exists
226 ///
227 /// [`alloc`](Self::alloc) bucket-rounds requests up to the next power of
228 /// two, which is acceptable for transient per-token scratch (the worst
229 /// case is ~2× over-allocation on a few megabytes) but unacceptable for
230 /// large static weight tensors. hf2q's Qwen3.5-MoE weight set totals
231 /// ~17.26 GB; bucket-rounding would balloon that to ~25.55 GB
232 /// (+8.3 GB / +48% blowup) — unshippable on a 128 GB unified-memory
233 /// M5 Max once KV cache and intermediates are layered on top.
234 ///
235 /// `register_existing` provides a *residency-only* path: the caller
236 /// allocates the buffer at its exact size via
237 /// [`MlxDevice::alloc_buffer`](crate::MlxDevice::alloc_buffer) (or
238 /// loads it via [`GgufFile::load_tensor_into_pool`](crate::GgufFile::load_tensor_into_pool)),
239 /// retains the [`MlxBuffer`] handle, and asks the pool to add the
240 /// underlying Metal allocation to its residency set so it gets the
241 /// MTLResidencySet hint on the next dispatch.
242 ///
243 /// # Ownership semantics
244 ///
245 /// * The pool **does not** take ownership of the buffer. The caller's
246 /// `MlxBuffer` handle remains the canonical owner.
247 /// * The pool **does not** recycle this buffer on [`reset`](Self::reset)
248 /// (it is not added to `in_use`).
249 /// * The pool **does** include this buffer in its residency set so it
250 /// is hinted-resident on the next encoder dispatch.
251 /// * On pool [`Drop`], the residency-set membership is removed but the
252 /// underlying Metal buffer is **not** freed — the caller's `MlxBuffer`
253 /// handle keeps the ARC alive.
254 ///
255 /// # `HF2Q_NO_RESIDENCY=1` escape hatch
256 ///
257 /// When the environment variable `HF2Q_NO_RESIDENCY=1` is set, the
258 /// process boots its [`MlxDevice`](crate::MlxDevice) without any
259 /// residency set (see `device.rs`). In that mode this method returns
260 /// `Ok(())` without touching anything — operators who suspect a
261 /// residency-induced regression can opt out without recompiling.
262 ///
263 /// # Idempotence
264 ///
265 /// Registering the same buffer twice (identified by its
266 /// `metal::Buffer.contents()` pointer) is a no-op on the second call —
267 /// the residency set membership is tracked in a `HashMap` keyed by
268 /// contents pointer.
269 ///
270 /// # Errors
271 ///
272 /// Returns `MlxError::InvalidArgument` if the buffer was allocated on a
273 /// different `MlxDevice` than any previously registered buffer.
274 pub fn register_existing(
275 &mut self,
276 device: &MlxDevice,
277 buffer: &MlxBuffer,
278 ) -> Result<()> {
279 // ADR-015 iter8e (Phase 3b): MlxDevice::alloc_buffer now
280 // auto-registers each new buffer with the device's residency set
281 // via Arc<MlxBufferStorage>. If this caller's buffer already owns
282 // its registration, short-circuit — re-registering would double-add
283 // and the pool's Drop would issue a stray removeAllocation: against
284 // a buffer the storage's RAII path will also remove.
285 if let Some(buffer_set) = buffer.residency_set() {
286 let Some(device_set) = device.residency_set() else {
287 return Err(MlxError::InvalidArgument(
288 "MlxBuffer is registered with a residency set, but device has none".into(),
289 ));
290 };
291 if !buffer_set.same_owner(device_set) {
292 return Err(MlxError::InvalidArgument(
293 "MlxBufferPool cannot register a buffer from a different residency-enabled device"
294 .into(),
295 ));
296 }
297 // Adopt the buffer's residency set so the pool's same_owner
298 // checks downstream agree, but do NOT add the buffer — it's
299 // already in the set via its own Arc<MlxBufferStorage>.
300 match self.residency_set.as_ref() {
301 Some(pool_set) if !pool_set.same_owner(device_set) => {
302 return Err(MlxError::InvalidArgument(
303 "MlxBufferPool cannot mix residency-enabled devices".into(),
304 ));
305 }
306 Some(_) => {}
307 None => {
308 self.residency_set = Some(device_set.clone());
309 }
310 }
311 return Ok(());
312 }
313
314 let added = self.register_residency_allocation(device, buffer.metal_buffer())?;
315 if added {
316 if let Some(set) = self.residency_set.as_ref() {
317 // Batched-add path: explicit commit (counts in the
318 // commit-call counter) preserves the
319 // `commit_called_after_alloc_batch`-style semantics.
320 set.commit();
321 }
322 }
323 Ok(())
324 }
325
326 /// Return all free buffers' count (for diagnostics).
327 pub fn free_count(&self) -> usize {
328 self.free.values().map(|v| v.len()).sum()
329 }
330
331 /// Total number of bytes held in the free list.
332 pub fn free_bytes(&self) -> usize {
333 self.free
334 .iter()
335 .map(|(&bucket, bufs)| bucket * bufs.len())
336 .sum()
337 }
338
339 /// Number of buffers currently in-use (alloc'd but not yet reset).
340 pub fn in_use_count(&self) -> usize {
341 self.in_use.len()
342 }
343
344 /// Clear all free buffers, releasing Metal memory. Does not affect
345 /// in-use tracking.
346 pub fn clear(&mut self) {
347 let mut removed_any = false;
348
349 if let Some(set) = self.residency_set.as_ref() {
350 for metal_buf in self.free.values().flatten() {
351 let key = buffer_key(metal_buf);
352 if let Some(resident_buf) = self.resident_buffers.remove(&key) {
353 set.remove_allocation(&resident_buf);
354 removed_any = true;
355 }
356 }
357
358 if removed_any {
359 set.commit();
360 }
361 }
362
363 self.free.clear();
364 }
365
366 fn register_residency_allocation(
367 &mut self,
368 device: &MlxDevice,
369 buffer: &metal::Buffer,
370 ) -> Result<bool> {
371 let Some(device_set) = device.residency_set() else {
372 return Ok(false);
373 };
374
375 match self.residency_set.as_ref() {
376 Some(pool_set) if !pool_set.same_owner(device_set) => {
377 return Err(MlxError::InvalidArgument(
378 "MlxBufferPool cannot mix residency-enabled devices".into(),
379 ));
380 }
381 Some(_) => {}
382 None => {
383 self.residency_set = Some(device_set.clone());
384 }
385 }
386
387 let key = buffer_key(buffer);
388 if !self.resident_buffers.contains_key(&key) {
389 device_set.add_allocation(buffer);
390 self.resident_buffers.insert(key, buffer.clone());
391 return Ok(true);
392 }
393
394 Ok(false)
395 }
396
397 fn remove_all_residency_allocations(&mut self) {
398 let Some(set) = self.residency_set.as_ref() else {
399 return;
400 };
401
402 if self.resident_buffers.is_empty() {
403 return;
404 }
405
406 for buffer in self.resident_buffers.values() {
407 set.remove_allocation(buffer);
408 }
409 set.commit();
410 self.resident_buffers.clear();
411 }
412}
413
414impl Drop for MlxBufferPool {
415 fn drop(&mut self) {
416 self.remove_all_residency_allocations();
417 }
418}
419
420/// Round `n` up to the nearest power of two.
421///
422/// Returns 1 for n == 0 (though callers should never request 0 bytes).
423fn bucket_size(n: usize) -> usize {
424 if n <= 1 {
425 return 1;
426 }
427 n.next_power_of_two()
428}
429
430#[inline]
431fn buffer_key(buffer: &metal::Buffer) -> usize {
432 buffer.contents() as usize
433}
434
435#[cfg(test)]
436mod tests {
437 use super::*;
438
439 #[test]
440 fn test_bucket_size_powers() {
441 assert_eq!(bucket_size(0), 1);
442 assert_eq!(bucket_size(1), 1);
443 assert_eq!(bucket_size(2), 2);
444 assert_eq!(bucket_size(3), 4);
445 assert_eq!(bucket_size(4), 4);
446 assert_eq!(bucket_size(5), 8);
447 assert_eq!(bucket_size(1023), 1024);
448 assert_eq!(bucket_size(1024), 1024);
449 assert_eq!(bucket_size(1025), 2048);
450 }
451
452 #[test]
453 fn test_pool_arena_reset_recycles_in_use() {
454 // Per-decode-token arena pattern: alloc many, drop locals, reset, alloc again.
455 // Subsequent allocs must reuse the same Metal buffers (verified by ARC-cloned
456 // contents pointer).
457 let device = MlxDevice::new().expect("device");
458 let mut pool = MlxBufferPool::new();
459
460 // Cycle 1: allocate three buffers in different buckets, then drop them
461 // (locals fall out of scope at the end of the block).
462 let (ptr_a, ptr_b, ptr_c) = {
463 let buf_a = pool.alloc(&device, 1024, DType::F32, vec![256]).expect("alloc a");
464 let buf_b = pool.alloc(&device, 2048, DType::F32, vec![512]).expect("alloc b");
465 let buf_c = pool.alloc(&device, 1024, DType::F32, vec![256]).expect("alloc c");
466 (buf_a.contents_ptr(), buf_b.contents_ptr(), buf_c.contents_ptr())
467 };
468 assert_eq!(pool.in_use_count(), 3);
469 assert_eq!(pool.free_count(), 0);
470
471 // Reset returns all three to free.
472 pool.reset();
473 assert_eq!(pool.in_use_count(), 0);
474 assert_eq!(pool.free_count(), 3);
475
476 // Cycle 2: allocate compatible-bucket buffers, must reuse the same
477 // underlying Metal buffers (contents_ptr equal).
478 let buf_d = pool.alloc(&device, 1024, DType::F32, vec![256]).expect("alloc d");
479 let buf_e = pool.alloc(&device, 2048, DType::F32, vec![512]).expect("alloc e");
480 let ptr_d = buf_d.contents_ptr();
481 let ptr_e = buf_e.contents_ptr();
482
483 // Pointers must come from {a, b, c} — bucket 1024 reuse for d (matches a or c),
484 // bucket 2048 reuse for e (matches b).
485 assert!(
486 ptr_d == ptr_a || ptr_d == ptr_c,
487 "buf_d {:?} must reuse one of a {:?} / c {:?}",
488 ptr_d, ptr_a, ptr_c,
489 );
490 assert_eq!(ptr_e, ptr_b, "buf_e must reuse b (only 2048-bucket buffer)");
491
492 // After cycle-2 alloc, free has 1 (the unused 1024-bucket buffer) + in_use 2.
493 assert_eq!(pool.in_use_count(), 2);
494 assert_eq!(pool.free_count(), 1);
495 }
496
497 #[test]
498 fn test_pool_reset_with_no_alloc_is_idempotent() {
499 // Empty reset must be a no-op. No MlxDevice required — pool
500 // operations on an empty pool don't touch the device; the
501 // smoke check used to live here was incidental and triggered
502 // the unused-variable warning since `device` was bound but
503 // never consumed.
504 let mut pool = MlxBufferPool::new();
505 pool.reset();
506 assert_eq!(pool.in_use_count(), 0);
507 assert_eq!(pool.free_count(), 0);
508 // Multiple resets without intervening alloc — still no-op.
509 pool.reset();
510 pool.reset();
511 assert_eq!(pool.in_use_count(), 0);
512 }
513
514 #[test]
515 fn test_register_existing_does_not_recycle_on_reset() {
516 // Externally-allocated buffer registered via register_existing must
517 // NOT be added to the in_use list — reset() should leave the caller's
518 // ownership intact and the buffer must remain valid after the pool
519 // is dropped.
520 let device = MlxDevice::new().expect("device");
521 let mut pool = MlxBufferPool::new();
522
523 // Allocate the buffer EXTERNALLY (via device.alloc_buffer, not
524 // pool.alloc) — this is the no-bucket-rounding path hf2q uses for
525 // static weight tensors.
526 let external = device
527 .alloc_buffer(4096, DType::U8, vec![4096])
528 .expect("alloc external");
529 let external_ptr = external.contents_ptr();
530
531 // Register with the pool's residency set.
532 pool.register_existing(&device, &external)
533 .expect("register_existing");
534
535 // in_use must remain empty (external buffer is not arena-recycled).
536 assert_eq!(pool.in_use_count(), 0);
537
538 // reset() must be a no-op for externally-registered buffers.
539 pool.reset();
540 assert_eq!(pool.in_use_count(), 0);
541 assert_eq!(pool.free_count(), 0);
542
543 // Drop the pool. The external MlxBuffer must still be valid — its
544 // metal::Buffer ARC is held by `external`, not by the pool.
545 drop(pool);
546 assert_eq!(external.contents_ptr(), external_ptr);
547 // Confirm the buffer is still accessible (no UAF).
548 let slice: &[u8] = external.as_slice().expect("slice still valid");
549 assert_eq!(slice.len(), 4096);
550 }
551
552 #[test]
553 fn test_register_existing_idempotent() {
554 // Registering the same buffer twice must not duplicate the residency
555 // membership (resident_buffers HashMap is keyed by contents pointer).
556 let device = MlxDevice::new().expect("device");
557 let mut pool = MlxBufferPool::new();
558
559 let external = device
560 .alloc_buffer(2048, DType::U8, vec![2048])
561 .expect("alloc external");
562
563 pool.register_existing(&device, &external)
564 .expect("register 1");
565 pool.register_existing(&device, &external)
566 .expect("register 2 (idempotent)");
567
568 // Drop the pool (Drop::drop runs remove_all_residency_allocations).
569 // No double-remove panic is the actual assertion here.
570 drop(pool);
571 // Buffer still valid.
572 let _slice: &[u8] = external.as_slice().expect("still valid");
573 }
574
575 #[test]
576 fn test_register_existing_no_residency_env_is_noop() {
577 // With HF2Q_NO_RESIDENCY=1 the device boots without a residency set,
578 // so register_existing has no set to register against and must
579 // return Ok(()) as a no-op without touching anything.
580 //
581 // This test runs serially with other residency-env tests via the
582 // shared TEST_LOCK in tests/test_residency_set.rs — but unit tests
583 // here run in the same process and could race with that integration
584 // test if both are running. We mitigate by:
585 // 1. Reading + restoring the original env value.
586 // 2. Resetting the residency env-cache flag before AND after.
587 //
588 // The unit-test name is uniquely keyed; cargo test by default
589 // single-threads tests within the same binary only when --test-threads=1
590 // is set. We accept that this test could flake under -j > 1 with
591 // the integration tests; in practice cargo test schedules unit and
592 // integration test binaries separately.
593 let prev = std::env::var("HF2Q_NO_RESIDENCY").ok();
594 crate::residency::reset_residency_env_cache_for_test();
595 std::env::set_var("HF2Q_NO_RESIDENCY", "1");
596
597 let device = MlxDevice::new().expect("device");
598 assert!(
599 !device.residency_sets_enabled(),
600 "device should boot without residency under HF2Q_NO_RESIDENCY=1",
601 );
602
603 let mut pool = MlxBufferPool::new();
604 let external = device
605 .alloc_buffer(1024, DType::U8, vec![1024])
606 .expect("alloc external");
607
608 // register_existing must succeed as a no-op.
609 pool.register_existing(&device, &external)
610 .expect("register_existing under HF2Q_NO_RESIDENCY=1 should succeed");
611
612 // Pool's internal residency_set must remain None.
613 assert!(pool.residency_set.is_none());
614 assert!(pool.resident_buffers.is_empty());
615
616 // Cleanup env.
617 match prev {
618 Some(v) => std::env::set_var("HF2Q_NO_RESIDENCY", v),
619 None => std::env::remove_var("HF2Q_NO_RESIDENCY"),
620 }
621 crate::residency::reset_residency_env_cache_for_test();
622 }
623
624 #[test]
625 fn test_pool_release_remains_supported_for_compat() {
626 // The existing per-buffer release() pattern still works. Mixing
627 // release+reset within the same arena cycle is documented as
628 // unsupported but technically lands a duplicate clone in free —
629 // verify the duplicate is harmless (alloc still picks up a buffer).
630 let device = MlxDevice::new().expect("device");
631 let mut pool = MlxBufferPool::new();
632
633 let buf = pool.alloc(&device, 1024, DType::F32, vec![256]).expect("alloc");
634 assert_eq!(pool.in_use_count(), 1);
635 pool.release(buf);
636 // release() does NOT remove from in_use; that's acceptable per the
637 // documented contract (don't mix patterns). Free has the released one.
638 assert_eq!(pool.free_count(), 1);
639 assert_eq!(pool.in_use_count(), 1);
640
641 // Allocating again pulls from free first.
642 let _buf2 = pool.alloc(&device, 1024, DType::F32, vec![256]).expect("alloc 2");
643 assert_eq!(pool.free_count(), 0);
644 assert_eq!(pool.in_use_count(), 2);
645 }
646}