dynamo-llm 1.0.2

Dynamo LLM Library
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

//! Typed builder for constructing [`PhysicalLayout`](crate::block_manager::v2::layout::PhysicalLayout)
//! instances with strongly-typed configuration, layout selection, and memory provisioning.
//!
//! The builder enforces the three steps required to materialize a physical layout:
//! 1. Provide a [`LayoutConfig`]
//! 2. Select a concrete layout (fully contiguous or layer separate)
//! 3. Specify memory backing (either by allocating or by supplying existing regions)
//!
//! NIXL registration is always enabled. Callers must provide a [`nixl_sys::Agent`], and any memory
//! supplied to the builder must implement [`NixlCompatible`].

use crate::block_manager::v2::physical::layout::physical::PhysicalLayout;

use super::{
    BlockDimension, FullyContiguousLayout, LayerSeparateLayout, Layout, LayoutConfig, MemoryRegion,
    physical::NixlMetadata,
};

use crate::block_manager::v2::memory::{
    DiskStorage, NixlCompatible, NixlDescriptor, OffsetMemoryRegion, OwnedMemoryRegion,
    RegisteredView, StorageKind, SystemStorage, register_with_nixl,
};
use anyhow::{Result, anyhow, bail};
#[allow(unused_imports)]
use nixl_sys::Agent as RawNixlAgent;
use nixl_sys::MemType;
use std::marker::PhantomData;
use std::path::PathBuf;
use std::sync::Arc;

use crate::block_manager::v2::memory::{DeviceStorage, PinnedStorage};

use crate::block_manager::v2::physical::transfer::nixl_agent::NixlAgent;

const REGION_ALIGNMENT: usize = 512;

/// Layout selection exposed by the builder.
#[derive(Debug, Clone)]
pub enum LayoutKind {
    FullyContiguous,
    LayerSeparate { block_dim: BlockDimension },
}

/// Allocation strategies for builder-managed memory.
#[derive(Debug, Clone)]
enum AllocationKind {
    System,
    Pinned { numa_aware: bool },

    Device { device_id: u32 },
    Disk { path: Option<PathBuf> },
}

/// Memory provisioning plan (either provided regions or an allocation request).
#[derive(Debug, Clone)]
enum MemoryPlan {
    Provided(Vec<MemoryEntry>),
    Allocate(AllocationKind),
}

/// Memory tenancy captured during the build process.
#[derive(Debug, Clone)]
struct MemoryEntry {
    region: OwnedMemoryRegion,
    descriptor: Option<NixlDescriptor>,
}

impl MemoryEntry {
    fn new(region: OwnedMemoryRegion, descriptor: Option<NixlDescriptor>) -> Self {
        Self { region, descriptor }
    }

    fn ensure_registered(mut self) -> Result<Self> {
        if self.descriptor.is_none() {
            self.descriptor = self.region.nixl_descriptor();
        }

        #[cfg(not(test))]
        {
            // In production, require NIXL registration
            if self.descriptor.is_none() {
                bail!(
                    "memory region {} is not registered with NIXL",
                    self.region.addr()
                );
            }
        }

        // In test builds, allow None descriptors for local-only layouts
        Ok(self)
    }
}

/// Marker types for the builder state machine.
pub struct NoConfig;
pub struct HasConfig;

pub struct NoLayout;
pub struct HasLayout;

pub struct NoMemory;
pub struct HasMemory;

/// Default builder state type alias.
pub type PhysicalLayoutBuilderDefault = PhysicalLayoutBuilder<NoConfig, NoLayout, NoMemory>;

/// Typed builder enforcing configuration, layout selection, and memory provisioning phases.
pub struct PhysicalLayoutBuilder<C, L, M> {
    agent: NixlAgent,
    config: Option<LayoutConfig>,
    layout_kind: Option<LayoutKind>,
    memory_plan: Option<MemoryPlan>,
    _config: PhantomData<C>,
    _layout: PhantomData<L>,
    _memory: PhantomData<M>,
}

impl PhysicalLayoutBuilder<NoConfig, NoLayout, NoMemory> {
    /// Create a new builder in its initial state.
    pub fn new(agent: NixlAgent) -> Self {
        Self {
            agent,
            config: None,
            layout_kind: None,
            memory_plan: None,
            _config: PhantomData,
            _layout: PhantomData,
            _memory: PhantomData,
        }
    }
}

impl<C, L, M> PhysicalLayoutBuilder<C, L, M> {
    fn into_parts(
        self,
    ) -> (
        NixlAgent,
        Option<LayoutConfig>,
        Option<LayoutKind>,
        Option<MemoryPlan>,
    ) {
        (self.agent, self.config, self.layout_kind, self.memory_plan)
    }

    fn from_parts<C2, L2, M2>(
        agent: NixlAgent,
        config: Option<LayoutConfig>,
        layout_kind: Option<LayoutKind>,
        memory_plan: Option<MemoryPlan>,
    ) -> PhysicalLayoutBuilder<C2, L2, M2> {
        PhysicalLayoutBuilder {
            agent,
            config,
            layout_kind,
            memory_plan,
            _config: PhantomData,
            _layout: PhantomData,
            _memory: PhantomData,
        }
    }
}

impl<L, M> PhysicalLayoutBuilder<NoConfig, L, M> {
    /// Attach the [`LayoutConfig`] required to size the layout and allocations.
    pub fn with_config(self, config: LayoutConfig) -> PhysicalLayoutBuilder<HasConfig, L, M> {
        let (agent, _config, layout_kind, memory_plan) = self.into_parts();
        PhysicalLayoutBuilder::<HasConfig, L, M>::from_parts(
            agent,
            Some(config),
            layout_kind,
            memory_plan,
        )
    }
}

impl<M> PhysicalLayoutBuilder<HasConfig, NoLayout, M> {
    /// Select the fully contiguous layout variant.
    pub fn fully_contiguous(self) -> PhysicalLayoutBuilder<HasConfig, HasLayout, M> {
        let (agent, config, _layout, memory_plan) = self.into_parts();
        PhysicalLayoutBuilder::<HasConfig, HasLayout, M>::from_parts(
            agent,
            config,
            Some(LayoutKind::FullyContiguous),
            memory_plan,
        )
    }

    /// Select the layer-separate layout variant with the provided block dimension ordering.
    pub fn layer_separate(
        self,
        block_dim: BlockDimension,
    ) -> PhysicalLayoutBuilder<HasConfig, HasLayout, M> {
        let (agent, config, _layout, memory_plan) = self.into_parts();
        PhysicalLayoutBuilder::<HasConfig, HasLayout, M>::from_parts(
            agent,
            config,
            Some(LayoutKind::LayerSeparate { block_dim }),
            memory_plan,
        )
    }
}

impl PhysicalLayoutBuilder<HasConfig, HasLayout, NoMemory> {
    fn set_memory_plan(
        self,
        plan: MemoryPlan,
    ) -> PhysicalLayoutBuilder<HasConfig, HasLayout, HasMemory> {
        let (agent, config, layout_kind, _memory) = self.into_parts();
        PhysicalLayoutBuilder::<HasConfig, HasLayout, HasMemory>::from_parts(
            agent,
            config,
            layout_kind,
            Some(plan),
        )
    }

    pub fn allocate_system(self) -> PhysicalLayoutBuilder<HasConfig, HasLayout, HasMemory> {
        self.set_memory_plan(MemoryPlan::Allocate(AllocationKind::System))
    }

    /// Allocate pinned (page-locked) host memory.
    pub fn allocate_pinned(
        self,
        numa_aware: bool,
    ) -> PhysicalLayoutBuilder<HasConfig, HasLayout, HasMemory> {
        self.set_memory_plan(MemoryPlan::Allocate(AllocationKind::Pinned { numa_aware }))
    }

    /// Allocate device memory on the specified CUDA device (or the context device if `None`).
    pub fn allocate_device(
        self,
        device_id: u32,
    ) -> PhysicalLayoutBuilder<HasConfig, HasLayout, HasMemory> {
        self.set_memory_plan(MemoryPlan::Allocate(AllocationKind::Device { device_id }))
    }

    /// Allocate disk-backed storage. When `path` is `None`, a temporary file is used.
    pub fn allocate_disk(
        self,
        path: Option<PathBuf>,
    ) -> PhysicalLayoutBuilder<HasConfig, HasLayout, HasMemory> {
        self.set_memory_plan(MemoryPlan::Allocate(AllocationKind::Disk { path }))
    }

    /// Use existing NIXL-compatible memory regions supplied by the caller.
    pub fn with_memory_regions<S>(
        self,
        regions: Vec<S>,
    ) -> Result<PhysicalLayoutBuilder<HasConfig, HasLayout, HasMemory>>
    where
        S: MemoryRegion + NixlCompatible + 'static,
    {
        let (agent, config, layout_kind, _memory) = self.into_parts();
        let entries = register_existing_regions(&agent, regions)?;
        Ok(
            PhysicalLayoutBuilder::<HasConfig, HasLayout, HasMemory>::from_parts(
                agent,
                config,
                layout_kind,
                Some(MemoryPlan::Provided(entries)),
            ),
        )
    }

    /// Use pre-registered memory regions (already wrapped in `Arc<dyn MemoryRegion>`).
    ///
    /// All regions must already expose a NIXL descriptor.
    pub fn with_registered_regions(
        self,
        regions: Vec<OwnedMemoryRegion>,
    ) -> Result<PhysicalLayoutBuilder<HasConfig, HasLayout, HasMemory>> {
        let entries = regions
            .into_iter()
            .enumerate()
            .map(|(index, region)| {
                let descriptor = region.nixl_descriptor().ok_or_else(|| {
                    anyhow!(
                        "provided memory region at index {} is not NIXL registered",
                        index
                    )
                })?;
                Ok(MemoryEntry::new(region, Some(descriptor)))
            })
            .collect::<Result<Vec<_>>>()?;

        let (agent, config, layout_kind, _memory) = self.into_parts();
        Ok(
            PhysicalLayoutBuilder::<HasConfig, HasLayout, HasMemory>::from_parts(
                agent,
                config,
                layout_kind,
                Some(MemoryPlan::Provided(entries)),
            ),
        )
    }
}

impl PhysicalLayoutBuilder<HasConfig, HasLayout, HasMemory> {
    /// Finalize the builder, constructing the [`PhysicalLayout`].
    pub fn build(self) -> Result<PhysicalLayout> {
        let (agent, config, layout_kind, memory_plan) = self.into_parts();

        let config = config.ok_or_else(|| anyhow!("layout config missing despite type state"))?;
        let layout_kind =
            layout_kind.ok_or_else(|| anyhow!("layout kind missing despite type state"))?;
        let memory_plan =
            memory_plan.ok_or_else(|| anyhow!("memory plan missing despite type state"))?;

        let required_sizes = compute_allocation_sizes(&config, &layout_kind)?;
        let entries = resolve_memory_plan(&agent, memory_plan, &required_sizes)?;

        validate_memory_sizes(&entries, &required_sizes)?;
        let kind = derive_storage_kind(&entries)?;
        let metadata = derive_nixl_metadata(&agent, &entries)?;

        let layout: Arc<dyn Layout> = match layout_kind {
            LayoutKind::FullyContiguous => {
                let entry = entries.first().ok_or_else(|| {
                    anyhow!("fully contiguous layout requires a single memory region")
                })?;
                let layout = FullyContiguousLayout::new(config.clone(), Arc::clone(&entry.region))?;
                Arc::new(layout)
            }
            LayoutKind::LayerSeparate { block_dim } => {
                let regions: Vec<OwnedMemoryRegion> = entries
                    .iter()
                    .map(|entry| Arc::clone(&entry.region))
                    .collect();
                let layout = LayerSeparateLayout::new(config.clone(), regions, block_dim)?;
                Arc::new(layout)
            }
        };

        Ok(PhysicalLayout::new_local(layout, kind, metadata))
    }
}

fn register_existing_regions<S>(agent: &NixlAgent, regions: Vec<S>) -> Result<Vec<MemoryEntry>>
where
    S: MemoryRegion + NixlCompatible + 'static,
{
    regions
        .into_iter()
        .map(|region| register_storage(region, agent))
        .collect()
}

fn resolve_memory_plan(
    agent: &NixlAgent,
    plan: MemoryPlan,
    sizes: &[usize],
) -> Result<Vec<MemoryEntry>> {
    match plan {
        MemoryPlan::Provided(entries) => {
            if entries.len() != sizes.len() {
                bail!(
                    "provided memory count ({}) does not match required allocations ({})",
                    entries.len(),
                    sizes.len()
                );
            }
            entries
                .into_iter()
                .map(MemoryEntry::ensure_registered)
                .collect()
        }
        MemoryPlan::Allocate(strategy) => allocate_regions(agent, strategy, sizes),
    }
}

fn allocate_regions(
    agent: &NixlAgent,
    strategy: AllocationKind,
    sizes: &[usize],
) -> Result<Vec<MemoryEntry>> {
    if sizes.is_empty() {
        return Ok(Vec::new());
    }

    let reserve_size = total_allocation_size(sizes, REGION_ALIGNMENT)?;

    let base_entry = match strategy {
        AllocationKind::System => allocate_system_entry(reserve_size, agent)?,
        AllocationKind::Pinned { numa_aware } => {
            allocate_pinned_entry(reserve_size, agent, numa_aware)?
        }

        AllocationKind::Device { device_id } => {
            allocate_device_entry(reserve_size, agent, device_id)?
        }
        AllocationKind::Disk { path } => allocate_disk_entry(reserve_size, agent, path)?,
    };

    create_offset_entries(base_entry, sizes, REGION_ALIGNMENT)
}

fn allocate_system_entry(size: usize, agent: &NixlAgent) -> Result<MemoryEntry> {
    let storage = SystemStorage::new(size)
        .map_err(|e| anyhow!("failed to allocate system memory ({size} bytes): {e}"))?;
    register_storage(storage, agent)
}

fn allocate_pinned_entry(size: usize, agent: &NixlAgent, _numa_aware: bool) -> Result<MemoryEntry> {
    let storage = PinnedStorage::new(size)
        .map_err(|e| anyhow!("failed to allocate pinned memory ({size} bytes): {e}"))?;
    register_storage(storage, agent)
}

fn allocate_device_entry(size: usize, agent: &NixlAgent, device_id: u32) -> Result<MemoryEntry> {
    let storage = DeviceStorage::new(size, device_id).map_err(|e| {
        anyhow!("failed to allocate device memory ({size} bytes) on device {device_id}: {e}")
    })?;
    register_storage(storage, agent)
}

fn allocate_disk_entry(
    size: usize,
    agent: &NixlAgent,
    path: Option<PathBuf>,
) -> Result<MemoryEntry> {
    let storage = if let Some(path) = path {
        DiskStorage::new_at(&path, size)
            .map_err(|e| anyhow!("failed to allocate disk storage at {}: {e}", path.display()))?
    } else {
        DiskStorage::new(size).map_err(|e| anyhow!("failed to allocate disk storage: {e}"))?
    };
    register_storage(storage, agent)
}

// When testing, we allow unregistered layouts to help with test time. NIXL + UCX is very expensive to setup
// so we only use that backend when it's needed.
#[cfg(test)]
fn register_storage<S>(storage: S, agent: &NixlAgent) -> Result<MemoryEntry>
where
    S: MemoryRegion + NixlCompatible + 'static,
{
    let storage_kind = storage.storage_kind();

    // Determine if registration is needed based on storage type and available backends
    let should_register = match storage_kind {
        StorageKind::System | StorageKind::Pinned => {
            // System/Pinned memory needs UCX for remote transfers
            agent.has_backend("UCX") || agent.has_backend("POSIX")
        }
        StorageKind::Device(_) => {
            // Device memory needs UCX for remote transfers OR GDS for direct disk transfers
            agent.has_backend("UCX") || agent.has_backend("GDS_MT")
        }
        StorageKind::Disk(_) => {
            // Disk storage needs POSIX for regular I/O OR GDS for GPU direct I/O
            agent.has_backend("POSIX") || agent.has_backend("GDS_MT")
        }
    };

    if !should_register {
        // Skip registration - only local non-NIXL transfers will be used
        let region: OwnedMemoryRegion = Arc::new(storage);
        return Ok(MemoryEntry::new(region, None));
    }

    // Register with NIXL using the appropriate backend
    match register_with_nixl(storage, agent.raw_agent(), None) {
        Ok(registered) => {
            let descriptor = registered.descriptor();
            let region: OwnedMemoryRegion = Arc::new(registered);
            Ok(MemoryEntry::new(region, Some(descriptor)))
        }
        Err(_storage) => bail!("failed to register memory with NIXL agent {}", agent.name()),
    }
}

// Production builds always register
#[cfg(not(test))]
fn register_storage<S>(storage: S, agent: &NixlAgent) -> Result<MemoryEntry>
where
    S: MemoryRegion + NixlCompatible + 'static,
{
    // Production builds always register for safety
    match register_with_nixl(storage, agent.raw_agent(), None) {
        Ok(registered) => {
            let descriptor = registered.descriptor();
            let region: OwnedMemoryRegion = Arc::new(registered);
            Ok(MemoryEntry::new(region, Some(descriptor)))
        }
        Err(_storage) => bail!("failed to register memory with NIXL agent {}", agent.name()),
    }
}

fn create_offset_entries(
    base_entry: MemoryEntry,
    sizes: &[usize],
    alignment: usize,
) -> Result<Vec<MemoryEntry>> {
    if sizes.is_empty() {
        return Ok(Vec::new());
    }

    let base_region = base_entry.region;
    let base_descriptor = base_entry.descriptor;
    let base_addr = base_region.addr();
    let base_len = base_region.size();

    let mut entries = Vec::with_capacity(sizes.len());
    let mut offset = 0usize;

    for (index, &size) in sizes.iter().enumerate() {
        let region = if index == 0 && offset == 0 && size == base_len && sizes.len() == 1 {
            Arc::clone(&base_region)
        } else {
            let view = OffsetMemoryRegion::new(Arc::clone(&base_region), offset, size)
                .map_err(|e| anyhow!("failed to create offset region: {e}"))?;
            Arc::new(view) as OwnedMemoryRegion
        };

        let descriptor = base_descriptor
            .as_ref()
            .map(|descriptor| derive_descriptor(descriptor, offset, size))
            .transpose()?;

        entries.push(MemoryEntry::new(region, descriptor));

        offset = offset
            .checked_add(size)
            .ok_or_else(|| anyhow!("offset computation overflow"))?;

        if index + 1 < sizes.len() && alignment > 1 {
            let current_addr = base_addr
                .checked_add(offset)
                .ok_or_else(|| anyhow!("address computation overflow"))?;
            let aligned_addr = align_up(current_addr, alignment)?;
            offset = aligned_addr
                .checked_sub(base_addr)
                .ok_or_else(|| anyhow!("alignment subtraction overflow"))?;
        }
    }

    if offset > base_len {
        bail!(
            "allocated base region ({base_len} bytes) is insufficient for {offset} bytes with padding"
        );
    }

    Ok(entries)
}

fn derive_descriptor(base: &NixlDescriptor, offset: usize, size: usize) -> Result<NixlDescriptor> {
    let mut descriptor = base.clone();
    descriptor.size = size;
    if descriptor.mem_type != MemType::File {
        descriptor.addr = descriptor
            .addr
            .checked_add(offset as u64)
            .ok_or_else(|| anyhow!("descriptor address overflow"))?;
    }
    Ok(descriptor)
}

fn compute_allocation_sizes(config: &LayoutConfig, kind: &LayoutKind) -> Result<Vec<usize>> {
    match kind {
        LayoutKind::FullyContiguous => {
            let factors = [
                config.num_blocks,
                config.num_layers,
                config.outer_dim,
                config.page_size,
                config.inner_dim,
                config.dtype_width_bytes,
            ];
            let total = mul_chain(&factors)?;
            Ok(vec![total])
        }
        LayoutKind::LayerSeparate { .. } => {
            let factors = [
                config.num_blocks,
                config.outer_dim,
                config.page_size,
                config.inner_dim,
                config.dtype_width_bytes,
            ];
            let per_layer = mul_chain(&factors)?;
            Ok(vec![per_layer; config.num_layers])
        }
    }
}

fn mul_chain(factors: &[usize]) -> Result<usize> {
    factors.iter().try_fold(1usize, |acc, &value| {
        acc.checked_mul(value)
            .ok_or_else(|| anyhow!("allocation size overflow during layout computation"))
    })
}

fn total_allocation_size(sizes: &[usize], alignment: usize) -> Result<usize> {
    if sizes.is_empty() {
        return Ok(0);
    }

    let mut total = *sizes
        .first()
        .ok_or_else(|| anyhow!("allocation requires at least one region"))?;

    for size in sizes.iter().skip(1) {
        total = total
            .checked_add(*size)
            .ok_or_else(|| anyhow!("allocation size overflow during aggregation"))?;
        if alignment > 1 {
            total = total
                .checked_add(alignment - 1)
                .ok_or_else(|| anyhow!("allocation alignment padding overflow"))?;
        }
    }

    Ok(total)
}

fn align_up(value: usize, alignment: usize) -> Result<usize> {
    if alignment <= 1 {
        return Ok(value);
    }
    let remainder = value % alignment;
    if remainder == 0 {
        Ok(value)
    } else {
        value
            .checked_add(alignment - remainder)
            .ok_or_else(|| anyhow!("alignment overflow"))
    }
}

fn validate_memory_sizes(entries: &[MemoryEntry], required: &[usize]) -> Result<()> {
    for (entry, &required_size) in entries.iter().zip(required.iter()) {
        if entry.region.size() < required_size {
            bail!(
                "memory region too small: required {} bytes, available {} bytes",
                required_size,
                entry.region.size()
            );
        }
    }
    Ok(())
}

fn derive_storage_kind(entries: &[MemoryEntry]) -> Result<StorageKind> {
    let first = entries
        .first()
        .ok_or_else(|| anyhow!("no memory regions available to determine storage location"))?;
    let first_kind = first.region.storage_kind();

    for entry in entries.iter().skip(1) {
        let kind = entry.region.storage_kind();
        if kind != first_kind {
            bail!(
                "all memory regions must share the same storage location (found {:?} and {:?})",
                first_kind,
                kind
            );
        }
    }

    Ok(first_kind)
}

fn derive_nixl_metadata(agent: &NixlAgent, entries: &[MemoryEntry]) -> Result<NixlMetadata> {
    // Try to find a descriptor from entries
    let descriptor_opt = entries.iter().find_map(|entry| entry.descriptor.clone());

    #[cfg(test)]
    {
        // In test builds, allow layouts without NIXL registration
        // Use defaults for local-only transfers
        if let Some(descriptor) = descriptor_opt {
            Ok(NixlMetadata::new(
                agent.name().to_string(),
                descriptor.mem_type,
                descriptor.device_id,
            ))
        } else {
            // Use placeholder metadata for unregistered layouts
            let first_entry = entries
                .first()
                .ok_or_else(|| anyhow!("no memory entries"))?;
            let storage_kind = first_entry.region.storage_kind();
            let (mem_type, device_id) = match storage_kind {
                StorageKind::System => (MemType::Dram, 0),
                StorageKind::Pinned => (MemType::Dram, 0),
                StorageKind::Device(id) => (MemType::Vram, id as u64),
                StorageKind::Disk(id) => (MemType::File, id),
            };
            Ok(NixlMetadata::new(
                agent.name().to_string(),
                mem_type,
                device_id,
            ))
        }
    }

    #[cfg(not(test))]
    {
        let descriptor = descriptor_opt
            .ok_or_else(|| anyhow!("memory entries missing NIXL registration metadata"))?;
        Ok(NixlMetadata::new(
            agent.name().to_string(),
            descriptor.mem_type,
            descriptor.device_id,
        ))
    }
}

#[cfg(all(test, feature = "testing-nixl"))]
mod tests {
    use super::super::{BlockDimension, LayoutConfig};
    use super::*;

    use crate::block_manager::v2::memory::{MemoryRegion, OwnedMemoryRegion, StorageKind};
    use nixl_sys::MemType;
    use std::any::Any;
    use std::sync::Arc;

    #[derive(Debug)]
    struct TestRegisteredRegion {
        data: Vec<u8>,
        kind: StorageKind,
        descriptor: NixlDescriptor,
    }

    impl TestRegisteredRegion {
        fn new(size: usize, kind: StorageKind, mem_type: MemType, device_id: u64) -> Self {
            let data = vec![0u8; size];
            let addr = data.as_ptr() as u64;
            let descriptor = NixlDescriptor {
                addr,
                size,
                mem_type,
                device_id,
            };
            Self {
                data,
                kind,
                descriptor,
            }
        }
    }

    impl MemoryRegion for TestRegisteredRegion {
        fn addr(&self) -> usize {
            self.data.as_ptr() as usize
        }

        fn size(&self) -> usize {
            self.data.len()
        }

        fn storage_kind(&self) -> StorageKind {
            self.kind
        }

        fn as_any(&self) -> &dyn Any {
            self
        }

        fn nixl_descriptor(&self) -> Option<NixlDescriptor> {
            Some(self.descriptor.clone())
        }
    }

    fn make_layout_config() -> LayoutConfig {
        LayoutConfig::builder()
            .num_blocks(2)
            .num_layers(3)
            .outer_dim(2)
            .page_size(4)
            .inner_dim(8)
            .dtype_width_bytes(2)
            .build()
            .unwrap()
    }

    fn fully_contiguous_size(cfg: &LayoutConfig) -> usize {
        cfg.num_blocks
            * cfg.num_layers
            * cfg.outer_dim
            * cfg.page_size
            * cfg.inner_dim
            * cfg.dtype_width_bytes
    }

    fn per_layer_size(cfg: &LayoutConfig) -> usize {
        cfg.num_blocks * cfg.outer_dim * cfg.page_size * cfg.inner_dim * cfg.dtype_width_bytes
    }

    #[test]
    fn builds_fully_contiguous_from_registered_regions() {
        let agent = NixlAgent::require_backends("builder-test-fully", &[])
            .expect("failed to create wrapped agent");
        let cfg = make_layout_config();

        let required = fully_contiguous_size(&cfg);
        let region = Arc::new(TestRegisteredRegion::new(
            required,
            StorageKind::System,
            MemType::Dram,
            0,
        )) as OwnedMemoryRegion;

        let physical = PhysicalLayoutBuilder::new(agent.clone())
            .with_config(cfg.clone())
            .fully_contiguous()
            .with_registered_regions(vec![region])
            .expect("registered regions accepted")
            .build()
            .expect("builder should succeed");

        assert_eq!(physical.location(), StorageKind::System);
        assert!(physical.layout().as_ref().is_fully_contiguous());
        assert_eq!(physical.layout().config().num_blocks, cfg.num_blocks);
        assert_eq!(physical.layout().config().num_layers, cfg.num_layers);

        let metadata = physical.nixl_metadata();
        assert_eq!(metadata.agent_name(), agent.name());
        assert_eq!(metadata.mem_type(), MemType::Dram);
    }

    #[test]
    fn builds_layer_separate_from_registered_regions() {
        let agent = NixlAgent::require_backends("builder-test-layer", &[])
            .expect("failed to create wrapped agent");
        let cfg = make_layout_config();

        let per_layer = per_layer_size(&cfg);
        let regions: Vec<OwnedMemoryRegion> = (0..cfg.num_layers)
            .map(|_| {
                Arc::new(TestRegisteredRegion::new(
                    per_layer,
                    StorageKind::System,
                    MemType::Dram,
                    0,
                )) as OwnedMemoryRegion
            })
            .collect();

        let physical = PhysicalLayoutBuilder::new(agent.clone())
            .with_config(cfg.clone())
            .layer_separate(BlockDimension::BlockIsFirstDim)
            .with_registered_regions(regions)
            .expect("registered layer regions accepted")
            .build()
            .expect("builder should succeed");

        assert_eq!(physical.location(), StorageKind::System);
        assert!(!physical.layout().as_ref().is_fully_contiguous());
        assert_eq!(physical.layout().config().num_layers, cfg.num_layers);

        let metadata = physical.nixl_metadata();
        assert_eq!(metadata.agent_name(), agent.name());
        assert_eq!(metadata.mem_type(), MemType::Dram);
    }
}

// fn context_device_id(ctx: &TransferContext) -> u32 {
//     ctx.stream().context().ordinal() as u32
// }