state.rs 19.8 KB
Newer Older
1
// SPDX-FileCopyrightText: Copyright (c) 2024-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
Ryan Olson's avatar
Ryan Olson committed
2
3
// SPDX-License-Identifier: Apache-2.0

Ryan Olson's avatar
Ryan Olson committed
4
5
6
7
mod local;
mod logical;
mod resources;

Ryan Olson's avatar
Ryan Olson committed
8
9
use super::*;

10
// use super::offload::{OffloadManager, OffloadManagerConfig};
11
use super::{
Ryan Olson's avatar
Ryan Olson committed
12
    block::{
13
14
        Block, GlobalRegistry, ImmutableBlock, MutableBlock, factory::IntoBlocks,
        factory::LocalBlockDataFactory, locality::LocalityProvider,
Ryan Olson's avatar
Ryan Olson committed
15
    },
16
    config::NixlOptions,
17
    events::{EventManager, NullEventManager},
18
19
20
21
22
    locality::LogicalResources,
    offload::{
        OffloadFilters, OffloadManager, OffloadManagerConfig, filter::OffloadFilter,
        request::BlockResult,
    },
23
};
Ryan Olson's avatar
Ryan Olson committed
24
use derive_getters::Dissolve;
Ryan Olson's avatar
Ryan Olson committed
25
use std::sync::Arc;
26
use tokio::runtime::Handle;
Ryan Olson's avatar
Ryan Olson committed
27
use tokio::sync::oneshot;
Ryan Olson's avatar
Ryan Olson committed
28

29
30
use crate::block_manager::kv_consolidator::StorageTier;

Ryan Olson's avatar
Ryan Olson committed
31
32
33
34
pub(crate) struct Resources {
    pub worker_id: WorkerID,
    pub cancellation_token: CancellationToken,
    pub async_rt_handle: Handle,
Ryan Olson's avatar
Ryan Olson committed
35

Ryan Olson's avatar
Ryan Olson committed
36
37
38
39
    // nixl agent/backends for the block manager
    pub nixl_agent: Arc<Option<NixlAgent>>,
    #[expect(dead_code)]
    pub nixl_backends: HashMap<String, Arc<nixl_sys::Backend>>,
Ryan Olson's avatar
Ryan Olson committed
40

Ryan Olson's avatar
Ryan Olson committed
41
42
    // registry for blocks across all storage types
    pub global_registry: GlobalRegistry,
Ryan Olson's avatar
Ryan Olson committed
43

Ryan Olson's avatar
Ryan Olson committed
44
45
    // event manager for block manager events
    pub event_manager: Arc<dyn EventManager>,
46

Ryan Olson's avatar
Ryan Olson committed
47
48
    // config for the block manager
    pub config: KvBlockManagerConfig,
Ryan Olson's avatar
Ryan Olson committed
49
50
}

Ryan Olson's avatar
Ryan Olson committed
51
52
53
#[allow(dead_code)]
pub struct KvBlockManagerState<Locality: LocalityProvider, Metadata: BlockMetadata> {
    resources: Arc<Resources>,
Ryan Olson's avatar
Ryan Olson committed
54

Ryan Olson's avatar
Ryan Olson committed
55
56
57
    disk_pool: Option<Arc<dyn BlockPool<DiskStorage, Locality, Metadata>>>,
    host_pool: Option<Arc<dyn BlockPool<PinnedStorage, Locality, Metadata>>>,
    device_pool: Option<Arc<dyn BlockPool<DeviceStorage, Locality, Metadata>>>,
Ryan Olson's avatar
Ryan Olson committed
58

Ryan Olson's avatar
Ryan Olson committed
59
60
61
62
    local_block_set: NixlBlockSet,
    remote_block_sets: RwLock<HashMap<WorkerID, HashMap<usize, RemoteBlocks>>>,
    offload_manager: Arc<OffloadManager<Locality, Metadata>>,
}
Ryan Olson's avatar
Ryan Olson committed
63

Ryan Olson's avatar
Ryan Olson committed
64
65
66
67
impl<Locality: LocalityProvider, Metadata: BlockMetadata> KvBlockManagerState<Locality, Metadata> {
    pub fn disk(&self) -> Option<&dyn BlockPool<DiskStorage, Locality, Metadata>> {
        self.disk_pool.as_ref().map(|pool| pool.as_ref())
    }
Ryan Olson's avatar
Ryan Olson committed
68

Ryan Olson's avatar
Ryan Olson committed
69
70
71
    pub fn host(&self) -> Option<&dyn BlockPool<PinnedStorage, Locality, Metadata>> {
        self.host_pool.as_ref().map(|pool| pool.as_ref())
    }
72

Ryan Olson's avatar
Ryan Olson committed
73
74
75
    pub fn device(&self) -> Option<&dyn BlockPool<DeviceStorage, Locality, Metadata>> {
        self.device_pool.as_ref().map(|pool| pool.as_ref())
    }
76

Ryan Olson's avatar
Ryan Olson committed
77
78
79
    pub fn worker_id(&self) -> WorkerID {
        self.resources.worker_id
    }
80

Ryan Olson's avatar
Ryan Olson committed
81
82
83
84
85
86
    pub(crate) async fn enqueue_offload_block<S: Storage + 'static>(
        &self,
        block: &ImmutableBlock<S, Locality, Metadata>,
        priority: u64,
    ) -> Result<()> {
        self.offload_manager.offload(block, priority).await?;
Ryan Olson's avatar
Ryan Olson committed
87

Ryan Olson's avatar
Ryan Olson committed
88
89
        Ok(())
    }
90

Ryan Olson's avatar
Ryan Olson committed
91
92
93
94
95
96
97
98
    pub fn onboard_blocks<S: Storage + 'static>(
        &self,
        blocks: Vec<ImmutableBlock<S, Locality, Metadata>>,
        targets: Option<Vec<MutableBlock<DeviceStorage, Locality, Metadata>>>,
    ) -> oneshot::Receiver<BlockResult<DeviceStorage, Locality, Metadata>> {
        self.offload_manager.onboard(blocks, targets)
    }
}
99

Ryan Olson's avatar
Ryan Olson committed
100
101
102
103
impl<R: LogicalResources, Metadata: BlockMetadata>
    KvBlockManagerState<locality::Logical<R>, Metadata>
{
    pub async fn new(config: KvBlockManagerConfig, logical_resources: R) -> Result<Arc<Self>> {
104
        let model_config = config.model.clone();
105
        let mut resources = Resources::new(config).await?;
Ryan Olson's avatar
Ryan Olson committed
106
107
108
109
110
        let block_data_factories =
            logical::LogicalBlockFactories::new(&mut resources, logical_resources)?;

        let (disk_factory, host_factory, device_factory) = block_data_factories.dissolve();

111
        let (disk_pool, disk_blocks, disk_offload_filter) = match disk_factory {
Ryan Olson's avatar
Ryan Olson committed
112
            Some(factory) => {
113
                let (pool, blocks, offload_filter) =
Ryan Olson's avatar
Ryan Olson committed
114
                    create_block_pool::<_, _, Metadata>(factory, &resources, "disk")?;
115
                (Some(pool), Some(blocks), offload_filter)
Ryan Olson's avatar
Ryan Olson committed
116
117
118
            }
            None => {
                tracing::debug!("No disk layout provided; will not allocate disk blocks.");
119
                (None, None, None)
Ryan Olson's avatar
Ryan Olson committed
120
121
            }
        };
Ryan Olson's avatar
Ryan Olson committed
122

123
        let (host_pool, host_blocks, host_offload_filter) = match host_factory {
Ryan Olson's avatar
Ryan Olson committed
124
            Some(factory) => {
125
                let (pool, blocks, offload_filter) =
Ryan Olson's avatar
Ryan Olson committed
126
                    create_block_pool::<_, _, Metadata>(factory, &resources, "host")?;
127
                (Some(pool), Some(blocks), offload_filter)
Ryan Olson's avatar
Ryan Olson committed
128
            }
Ryan Olson's avatar
Ryan Olson committed
129
130
            None => {
                tracing::debug!("No host layout provided; will not allocate host blocks.");
131
                (None, None, None)
Ryan Olson's avatar
Ryan Olson committed
132
133
            }
        };
Ryan Olson's avatar
Ryan Olson committed
134

135
        let (device_pool, device_blocks, device_offload_filter) = match device_factory {
Ryan Olson's avatar
Ryan Olson committed
136
            Some(factory) => {
137
                let (pool, blocks, offload_filter) =
Ryan Olson's avatar
Ryan Olson committed
138
                    create_block_pool::<_, _, Metadata>(factory, &resources, "device")?;
139
                (Some(pool), Some(blocks), offload_filter)
Ryan Olson's avatar
Ryan Olson committed
140
141
142
            }
            None => {
                tracing::debug!("No device layout provided; will not allocate device blocks.");
143
                (None, None, None)
Ryan Olson's avatar
Ryan Olson committed
144
            }
145
146
        };

147
148
149
        // Determine if we should bypass CPU memory (G2) and offload directly from GPU (G1) to Disk (G3)
        let bypass_cpu_mem = config::should_bypass_cpu_cache();

150
151
152
153
154
155
        let offload_filters = OffloadFilters::builder()
            .device(device_offload_filter)
            .host(host_offload_filter)
            .disk(disk_offload_filter)
            .build()?;

156
157
158
159
160
        let offload_config = OffloadManagerConfig {
            nixl_agent: resources.nixl_agent.clone(),
            async_rt_handle: resources.async_rt_handle.clone(),
            cancellation_token: resources.cancellation_token.clone(),
            model_config,
161
            kvbm_metrics: resources.config.kvbm_metrics.clone(),
162
            bypass_cpu_mem,
163
164
        };

Ryan Olson's avatar
Ryan Olson committed
165
166
167
168
        let offload_manager = OffloadManager::new(
            disk_pool.clone(),
            host_pool.clone(),
            device_pool.clone(),
169
            offload_filters,
170
            offload_config,
Ryan Olson's avatar
Ryan Olson committed
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
        )?;

        let resources = Arc::new(resources);

        let state = Arc::new(Self {
            resources: resources.clone(),
            disk_pool,
            host_pool,
            device_pool,
            local_block_set: NixlBlockSet::new(resources.worker_id),
            remote_block_sets: RwLock::new(HashMap::new()),
            offload_manager,
        });

        if let Some(mut blocks) = disk_blocks {
            blocks.iter_mut().for_each(|block| {
                block.set_manager(state.clone());
            });

            state.disk_pool.as_ref().unwrap().add_blocks(blocks).await?;
        }

        if let Some(mut blocks) = host_blocks {
            blocks.iter_mut().for_each(|block| {
                block.set_manager(state.clone());
            });

            state.host_pool.as_ref().unwrap().add_blocks(blocks).await?;
        }

        if let Some(mut blocks) = device_blocks {
            blocks.iter_mut().for_each(|block| {
                block.set_manager(state.clone());
            });

            state
                .device_pool
                .as_ref()
                .unwrap()
                .add_blocks(blocks)
                .await?;
        }

        Ok(state)
    }
}

// move into mod local
// move local block data factory into mod super::block
// create a method on locality to construct a block data factory from a layout builder and resources
// - this will allow us to use the locality abstraction to build our factories and block pools
impl<Metadata: BlockMetadata> KvBlockManagerState<locality::Local, Metadata> {
    pub async fn new(config: KvBlockManagerConfig) -> Result<Arc<Self>> {
224
        let model_config = config.model.clone();
225
        let mut resources = Resources::new(config).await?;
Ryan Olson's avatar
Ryan Olson committed
226
227
228
229
230
        let block_data_factories = local::LocalBlockDataFactories::new(&mut resources)?;

        let (mut local_block_set, disk_factory, host_factory, device_factory) =
            block_data_factories.dissolve();

231
        let (disk_pool, disk_blocks, disk_offload_filter) = match disk_factory {
Ryan Olson's avatar
Ryan Olson committed
232
            Some(factory) => {
233
                let (pool, blocks, offload_filter) =
Ryan Olson's avatar
Ryan Olson committed
234
                    create_block_pool::<_, _, Metadata>(factory, &resources, "disk")?;
235
                (Some(pool), Some(blocks), offload_filter)
Ryan Olson's avatar
Ryan Olson committed
236
237
238
            }
            None => {
                tracing::debug!("No disk layout provided; will not allocate disk blocks.");
239
                (None, None, None)
240
241
242
            }
        };

243
        let (host_pool, host_blocks, host_offload_filter) = match host_factory {
Ryan Olson's avatar
Ryan Olson committed
244
            Some(factory) => {
245
                let (pool, blocks, offload_filter) =
Ryan Olson's avatar
Ryan Olson committed
246
                    create_block_pool::<_, _, Metadata>(factory, &resources, "host")?;
247
                (Some(pool), Some(blocks), offload_filter)
Ryan Olson's avatar
Ryan Olson committed
248
249
            }
            None => {
250
251
                tracing::debug!("No host layout provided; will not allocate host blocks.");
                (None, None, None)
Ryan Olson's avatar
Ryan Olson committed
252
            }
Ryan Olson's avatar
Ryan Olson committed
253
254
        };

255
        let (device_pool, device_blocks, device_offload_filter) = match device_factory {
Ryan Olson's avatar
Ryan Olson committed
256
            Some(factory) => {
257
                let (pool, blocks, offload_filter) =
258
                    create_block_pool::<_, _, Metadata>(factory, &resources, "device")?;
259
                (Some(pool), Some(blocks), offload_filter)
Ryan Olson's avatar
Ryan Olson committed
260
261
            }
            None => {
262
263
                tracing::debug!("No device layout provided; will not allocate device blocks.");
                (None, None, None)
Ryan Olson's avatar
Ryan Olson committed
264
            }
Ryan Olson's avatar
Ryan Olson committed
265
266
267
        };

        // Finalize the local block set by adding NIXL metadata
Ryan Olson's avatar
Ryan Olson committed
268
        if let Some(nixl_agent) = resources.nixl_agent.as_ref() {
Ryan Olson's avatar
Ryan Olson committed
269
270
271
272
            tracing::debug!("Finalize NixlBlockSet: adding NIXL metadata.");
            local_block_set.set_nixl_metadata(nixl_agent.get_local_md()?);
        }

273
274
275
276
277
278
        let offload_filters = OffloadFilters::builder()
            .device(device_offload_filter)
            .host(host_offload_filter)
            .disk(disk_offload_filter)
            .build()?;

279
280
281
        // Determine if we should bypass CPU memory (G2) and offload directly from GPU (G1) to Disk (G3)
        let bypass_cpu_mem = config::should_bypass_cpu_cache();

282
283
284
285
286
        let offload_config = OffloadManagerConfig {
            nixl_agent: resources.nixl_agent.clone(),
            async_rt_handle: resources.async_rt_handle.clone(),
            cancellation_token: resources.cancellation_token.clone(),
            model_config,
287
            kvbm_metrics: resources.config.kvbm_metrics.clone(),
288
            bypass_cpu_mem,
289
290
        };

291
292
293
294
        let offload_manager = OffloadManager::new(
            disk_pool.clone(),
            host_pool.clone(),
            device_pool.clone(),
295
            offload_filters,
296
            offload_config,
297
        )?;
298

Ryan Olson's avatar
Ryan Olson committed
299
300
        let resources = Arc::new(resources);

Ryan Olson's avatar
Ryan Olson committed
301
        let state = Arc::new(Self {
Ryan Olson's avatar
Ryan Olson committed
302
            resources: resources.clone(),
303
            disk_pool,
Ryan Olson's avatar
Ryan Olson committed
304
305
306
307
            host_pool,
            device_pool,
            local_block_set,
            remote_block_sets: RwLock::new(HashMap::new()),
308
            offload_manager,
Ryan Olson's avatar
Ryan Olson committed
309
310
        });

311
312
313
314
315
        if let Some(mut blocks) = disk_blocks {
            blocks.iter_mut().for_each(|block| {
                block.set_manager(state.clone());
            });

Ryan Olson's avatar
Ryan Olson committed
316
            state.disk_pool.as_ref().unwrap().add_blocks(blocks).await?;
317
318
        }

Ryan Olson's avatar
Ryan Olson committed
319
320
321
322
323
        if let Some(mut blocks) = host_blocks {
            blocks.iter_mut().for_each(|block| {
                block.set_manager(state.clone());
            });

Ryan Olson's avatar
Ryan Olson committed
324
            state.host_pool.as_ref().unwrap().add_blocks(blocks).await?;
Ryan Olson's avatar
Ryan Olson committed
325
326
327
328
329
330
331
332
333
334
335
        }

        if let Some(mut blocks) = device_blocks {
            blocks.iter_mut().for_each(|block| {
                block.set_manager(state.clone());
            });

            state
                .device_pool
                .as_ref()
                .unwrap()
Ryan Olson's avatar
Ryan Olson committed
336
337
                .add_blocks(blocks)
                .await?;
Ryan Olson's avatar
Ryan Olson committed
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
        }

        Ok(state)
    }

    /// Exports the local blockset configuration as a serialized object.
    pub fn export_local_blockset(&self) -> Result<SerializedNixlBlockSet> {
        SerializedNixlBlockSet::try_from(&self.local_block_set)
            .context("Failed to serialize local blockset")
    }

    /// Imports a remote blockset configuration from a serialized object.
    // TODO: NIXL will validate the every descriptor list against the memory registration list for
    // a given agent; this is can be an expensive operation. To avoid this, NIXL offers the ability
    // to generate "partial pre-validated (PPV)" descriptor lists. However, to support per-block and per-layer
    // PPV lists we will need as many as `num_layers + 1` PPV lists per block:
    // - one for representing the entire block
    // - one for representing each layer individually
    //
    // A deeper dive into the performance impact of PPV lists is required to determine if this is
    // the best approach.
    //
    // If PPV are valuable, it might be beneficial to lazily instantiate PPV lists when they are
    // needed; alternatively, we could generate the entire PPV list for each block at import time.
    pub fn import_remote_blockset(
        &self,
        serialized_blockset: SerializedNixlBlockSet,
    ) -> Result<()> {
        let remote = NixlBlockSet::try_from(serialized_blockset)
            .context("Failed to deserialize remote blockset")?;

        let (block_sets, metadata, worker_id) = remote.dissolve();
        tracing::debug!("Importing remote blockset from worker {}", worker_id);

        assert_ne!(
Ryan Olson's avatar
Ryan Olson committed
373
            worker_id, self.resources.worker_id,
Ryan Olson's avatar
Ryan Olson committed
374
375
376
377
            "Cannot import blockset from self"
        );

        let agent = self
Ryan Olson's avatar
Ryan Olson committed
378
            .resources
Ryan Olson's avatar
Ryan Olson committed
379
380
            .nixl_agent
            .as_ref()
381
            .as_ref()
Ryan Olson's avatar
Ryan Olson committed
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
            .ok_or_else(|| anyhow::anyhow!("NIXL agent not initialized"))?;

        let mut remote_block_sets = self.remote_block_sets.write().unwrap();

        if remote_block_sets.contains_key(&worker_id) {
            anyhow::bail!(
                "Worker ID {} already exists; cannot update remote blockset",
                worker_id
            );
        }

        let mut inner_map = HashMap::new();

        for (block_set_idx, block_set_layout) in block_sets {
            // Deserialize the individual layout and create RemoteBlocks
            let remote_blocks =
                RemoteBlocks::from_serialized(block_set_layout.clone(), block_set_idx, worker_id)?;

            // check the storage type of the remote blocks
            let layout = remote_blocks.layout();
            let storage = layout.storage();

            let storage = storage
                .first()
                .ok_or_else(|| anyhow::anyhow!("No storage found in remote blockset"))?;

            match storage.mem_type() {
                MemType::Dram => {
                    tracing::trace!(block_set_idx, "Detected Host/DRAM remote descriptor");
                }
                MemType::Vram => {
                    tracing::trace!(block_set_idx, "Detected GPU/Device/VRAM remote descriptor");
                }
                _ => {
                    tracing::warn!(
                        block_set_idx,
                        "Detected unknown remote descriptor; skipping blockset..."
                    );
                    continue;
                }
            }

            inner_map.insert(block_set_idx, remote_blocks);
        }

        let agent_id = agent
            .load_remote_md(&metadata)
            .context("Loading remote metadata")?;

        // try to convert the agent_id (String) to a WorkerID (u64)
        let agent_id: WorkerID =
            agent_id // Assuming agent_id is String here
                .parse() // Parse the String into u64 (WorkerID)
                .context("Failed to parse agent ID string into WorkerID (u64)")?;

        assert_eq!(agent_id, worker_id, "Mismatch with remote worker ID");

        remote_block_sets.insert(worker_id, inner_map);

        Ok(())
    }

    /// Get a [`Vec<RemoteBlock<IsImmutable>>`] from a [`BlockDescriptorList`]
    pub fn get_remote_blocks_immutable(
        &self,
        bds: &BlockDescriptorList,
    ) -> Result<Vec<RemoteBlock<IsImmutable>>> {
        // no checks - we can always create an immutable remote block even if the bds is mutable
        self.get_remote_blocks::<IsImmutable>(bds)
    }

    /// Get a [`Vec<RemoteBlock<IsMutable>>`] from a [`BlockDescriptorList`]
    pub fn get_remote_blocks_mutable(
        &self,
        bds: &BlockDescriptorList,
    ) -> Result<Vec<RemoteBlock<IsMutable>>> {
        if bds.mutability() == BlockMutability::Mutable {
            self.get_remote_blocks::<IsMutable>(bds)
        } else {
            anyhow::bail!("Cannot get mutable remote blocks for immutable block descriptor set");
        }
    }

    /// Generate a [`Vec<RemoteBlock>`] from a [`BlockDescriptorList`]
    fn get_remote_blocks<M: MutabilityKind>(
        &self,
        bds: &BlockDescriptorList,
    ) -> Result<Vec<RemoteBlock<M>>> {
        // Get a read lock on the remote block sets
        let remote_block_sets = self.remote_block_sets.read().unwrap();

        // validate we have loaded a remote blockset for the worker and the specific block_set_idx
        let remote_blocks = remote_block_sets
            .get(&bds.worker_id())
            .and_then(|map| map.get(&bds.block_set_idx()))
            .ok_or_else(|| {
                anyhow::anyhow!(
                    "No remote blockset found for worker {} and block_set_idx {}",
                    bds.worker_id(),
                    bds.block_set_idx()
                )
            })?;

        // Iterate through indices, call .block() for each, and collect results.
        // The collect::<Result<...>>() handles potential errors from .block()
        let blocks: Vec<block::nixl::RemoteBlock<M>> = bds
            .block_indices()
            .iter()
            .map(|block_idx| remote_blocks.block(*block_idx))
            .collect::<Result<Vec<_>, _>>()?;

        Ok(blocks)
    }
}

Ryan Olson's avatar
Ryan Olson committed
497
498
499
impl<Locality: LocalityProvider, Metadata: BlockMetadata> std::fmt::Debug
    for KvBlockManagerState<Locality, Metadata>
{
Ryan Olson's avatar
Ryan Olson committed
500
501
502
503
504
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "KvBlockManagerState")
    }
}

Ryan Olson's avatar
Ryan Olson committed
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
//     if let Some(storage) = config.storage {
//         let mut layout = layout.create_layout(config.layout_type, storage, false)?;
//         if let Some(nixl_agent) = nixl_agent {
//             layout.nixl_register(nixl_agent, None)?;
//         }
//         return Ok(layout.into());
//     }

//     if let Some(allocator) = config.allocator {
//         let mut layout = layout.allocate_layout(config.layout_type, allocator)?;
//         if let Some(nixl_agent) = nixl_agent {
//             layout.nixl_register(nixl_agent, None)?;
//         }
//         return Ok(layout.into());
//     }

//     anyhow::bail!("failed to create layout");
// }

#[expect(clippy::type_complexity)]
pub(crate) fn create_block_pool<S: Storage, L: LocalityProvider, M: BlockMetadata>(
    factory: impl IntoBlocks<S, L>,
    resources: &Resources,
528
    pool_name: &str,
529
530
531
532
533
) -> Result<(
    Arc<dyn BlockPool<S, L, M>>,
    Vec<Block<S, L, M>>,
    Option<Arc<dyn OffloadFilter>>,
)> {
534
535
536
537
538
539
540
    let storage_tier = match pool_name {
        "device" => StorageTier::Device,
        "host" => StorageTier::HostPinned,
        "disk" => StorageTier::Disk,
        _ => anyhow::bail!("unsupported block pool tier: {}", pool_name),
    };

Ryan Olson's avatar
Ryan Olson committed
541
542
543
544
545
    let pool = ManagedBlockPool::<S, L, M>::builder()
        .cancel_token(resources.cancellation_token.clone())
        .global_registry(resources.global_registry.clone())
        .async_runtime(resources.async_rt_handle.clone())
        .event_manager(resources.event_manager.clone())
546
        .storage_tier(storage_tier)
Ryan Olson's avatar
Ryan Olson committed
547
        .build()?;
Ryan Olson's avatar
Ryan Olson committed
548

549
    let offload_filter = factory.offload_filter();
Ryan Olson's avatar
Ryan Olson committed
550
    let blocks = factory.into_blocks()?;
Ryan Olson's avatar
Ryan Olson committed
551

552
553
    Ok((Arc::new(pool), blocks, offload_filter))
}