state.rs 19.4 KB
Newer Older
Ryan Olson's avatar
Ryan Olson committed
1
2
3
// SPDX-FileCopyrightText: Copyright (c) 2024-2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// 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

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

Ryan Olson's avatar
Ryan Olson committed
34
35
36
37
    // 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
38

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

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

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

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

Ryan Olson's avatar
Ryan Olson committed
53
54
55
    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
56

Ryan Olson's avatar
Ryan Olson committed
57
58
59
60
    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
61

Ryan Olson's avatar
Ryan Olson committed
62
63
64
65
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
66

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

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

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

Ryan Olson's avatar
Ryan Olson committed
79
80
81
82
83
84
    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
85

Ryan Olson's avatar
Ryan Olson committed
86
87
        Ok(())
    }
88

Ryan Olson's avatar
Ryan Olson committed
89
90
91
92
93
94
95
96
    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)
    }
}
97

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

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

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

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

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

145
146
147
        // 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();

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

154
155
156
157
158
        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,
159
            kvbm_metrics: resources.config.kvbm_metrics.clone(),
160
            bypass_cpu_mem,
161
162
        };

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

        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>> {
222
        let model_config = config.model.clone();
223
        let mut resources = Resources::new(config).await?;
Ryan Olson's avatar
Ryan Olson committed
224
225
226
227
228
        let block_data_factories = local::LocalBlockDataFactories::new(&mut resources)?;

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

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

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

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

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

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

277
278
279
        // 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();

280
281
282
283
284
        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,
285
            kvbm_metrics: resources.config.kvbm_metrics.clone(),
286
            bypass_cpu_mem,
287
288
        };

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

Ryan Olson's avatar
Ryan Olson committed
297
298
        let resources = Arc::new(resources);

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

309
310
311
312
313
        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
314
            state.disk_pool.as_ref().unwrap().add_blocks(blocks).await?;
315
316
        }

Ryan Olson's avatar
Ryan Olson committed
317
318
319
320
321
        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
322
            state.host_pool.as_ref().unwrap().add_blocks(blocks).await?;
Ryan Olson's avatar
Ryan Olson committed
323
324
325
326
327
328
329
330
331
332
333
        }

        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
334
335
                .add_blocks(blocks)
                .await?;
Ryan Olson's avatar
Ryan Olson committed
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
        }

        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
371
            worker_id, self.resources.worker_id,
Ryan Olson's avatar
Ryan Olson committed
372
373
374
375
            "Cannot import blockset from self"
        );

        let agent = self
Ryan Olson's avatar
Ryan Olson committed
376
            .resources
Ryan Olson's avatar
Ryan Olson committed
377
378
            .nixl_agent
            .as_ref()
379
            .as_ref()
Ryan Olson's avatar
Ryan Olson committed
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
            .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
495
496
497
impl<Locality: LocalityProvider, Metadata: BlockMetadata> std::fmt::Debug
    for KvBlockManagerState<Locality, Metadata>
{
Ryan Olson's avatar
Ryan Olson committed
498
499
500
501
502
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "KvBlockManagerState")
    }
}

Ryan Olson's avatar
Ryan Olson committed
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
//     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,
526
    _pool_name: &str,
527
528
529
530
531
) -> Result<(
    Arc<dyn BlockPool<S, L, M>>,
    Vec<Block<S, L, M>>,
    Option<Arc<dyn OffloadFilter>>,
)> {
Ryan Olson's avatar
Ryan Olson committed
532
533
534
535
536
537
    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())
        .build()?;
Ryan Olson's avatar
Ryan Olson committed
538

539
    let offload_filter = factory.offload_filter();
Ryan Olson's avatar
Ryan Olson committed
540
    let blocks = factory.into_blocks()?;
Ryan Olson's avatar
Ryan Olson committed
541

542
543
    Ok((Arc::new(pool), blocks, offload_filter))
}