"vscode:/vscode.git/clone" did not exist on "c0f34b15a060e04af5193aa4b0c66b4d37daeb8f"
offload.rs 59.5 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// SPDX-FileCopyrightText: Copyright (c) 2024-2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

16
17
18
19
20
//! # Offload Manager
//! The offload manager is responsible for handling all block transfers between different cache levels.
//!
//! ## Offloading
//! Offloading is the process of moving blocks to a cache level further away from the device.
Ryan Olson's avatar
Ryan Olson committed
21
//! When blocks are registered (via [`ManagedBlockPool::register_blocks`]), they are automatically sent to the offload manager.
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
//! Due to limited bandwidth, the offload manager must prioritize which offloads to perform.
//! This is indicated by the `priority` parameter to [`OffloadManager::offload`].
//! When a offload request is received, the offload manager will enqueue it into a priority queue.
//! This priority queue is keyed by the `priority` parameter, where blocks with lower priority values are processed first.
//! Within the same priority, blocks that were sent to the offload manager earlier are processed first.
//!
//! ## Onboarding
//! Onboarding is the process of moving blocks to a cache level closer to the device.
//! All onboardings are manually triggered through the [`OffloadManager::onboard`] method.
//!
//! ## Transfer Managers
//! The offload manager uses two transfer managers to handle the offloading and onboarding of blocks.
//!
//! The [`CudaTransferManager`] is responsible for transfers between the device and host.
//! The [`DiskTransferManager`] is responsible for transfers from host to disk and disk to device.
//!
//! ## Worker Threads
//! The offload manager uses two kinds of worker threads to handle the offloading and onboarding of blocks.
//!
//! The [`OffloadManager::offload_worker`] is responsible for offloading blocks.
//! The [`OffloadManager::onboard_worker`] is responsible for onboarding blocks.
//!
//! The kind of offloads/onboards they perform is dictated by the source and target arguments
45
//! of the [`OffloadManager::offload_worker`] and [`OffloadManager::onboard_worker`] methods.
46

Ryan Olson's avatar
Ryan Olson committed
47
48
49
50
use super::block::{
    locality::LocalityProvider, transfer::TransferContext, BlockError, BlockMetadata, BlockState,
    ImmutableBlock, MutableBlock,
};
51
use super::metrics::{BlockManagerMetrics, PoolMetrics};
Ryan Olson's avatar
Ryan Olson committed
52
use super::pool::{BlockPool, BlockPoolError};
53
use super::storage::{Cuda, Storage};
Ryan Olson's avatar
Ryan Olson committed
54
use super::{DeviceStorage, DiskStorage, PinnedStorage};
55
56
57
58
59
use nixl_sys::Agent as NixlAgent;
use std::sync::Arc;
use tokio::runtime::Handle;
use tokio::sync::{
    mpsc::{self, error::TryRecvError},
Ryan Olson's avatar
Ryan Olson committed
60
    oneshot, Mutex,
61
};
62
use tokio_util::sync::CancellationToken;
63
64
65
66
67
68
69

use anyhow::Result;
use std::any::Any;

use std::collections::BTreeSet;

mod pending;
70
pub mod request;
71

Ryan Olson's avatar
Ryan Olson committed
72
use pending::{LocalTransferManager, PendingTransfer, TransferBatcher, TransferManager};
73
use request::{BlockResult, OffloadRequest, OffloadRequestKey, OnboardRequest};
74

75
76
use dynamo_runtime::utils::task::CriticalTaskExecutionHandle;

77
78
const MAX_CONCURRENT_TRANSFERS: usize = 4;
const MAX_TRANSFER_BATCH_SIZE: usize = 16;
79
80

/// The offload manager handles all block transfers between different cache levels.
Ryan Olson's avatar
Ryan Olson committed
81
pub struct OffloadManager<Locality: LocalityProvider, Metadata: BlockMetadata> {
82
    // Handles to the device, host, and disk pools.
Ryan Olson's avatar
Ryan Olson committed
83
84
85
    disk: Option<Arc<dyn BlockPool<DiskStorage, Locality, Metadata>>>,
    host: Option<Arc<dyn BlockPool<PinnedStorage, Locality, Metadata>>>,
    device: Option<Arc<dyn BlockPool<DeviceStorage, Locality, Metadata>>>,
86

87
    /// Queue of offloading requests.
Ryan Olson's avatar
Ryan Olson committed
88
89
    device_offload_tx: mpsc::UnboundedSender<OffloadRequest<DeviceStorage, Locality, Metadata>>,
    host_offload_tx: mpsc::UnboundedSender<OffloadRequest<PinnedStorage, Locality, Metadata>>,
90
91

    /// Queue of pending onboarding requests.
Ryan Olson's avatar
Ryan Olson committed
92
93
94
95
    host_onboard_tx:
        mpsc::UnboundedSender<OnboardRequest<PinnedStorage, DeviceStorage, Locality, Metadata>>,
    disk_onboard_tx:
        mpsc::UnboundedSender<OnboardRequest<DiskStorage, DeviceStorage, Locality, Metadata>>,
96
97
98

    /// An incrementing counter for offloaded blocks. Within the same priority, blocks with lower tick values are processed first.
    tick: Arc<Mutex<u64>>,
99
100
}

Ryan Olson's avatar
Ryan Olson committed
101
102
103
impl<Locality: LocalityProvider + 'static, Metadata: BlockMetadata>
    OffloadManager<Locality, Metadata>
{
104
    pub fn new(
Ryan Olson's avatar
Ryan Olson committed
105
106
107
        disk: Option<Arc<dyn BlockPool<DiskStorage, Locality, Metadata>>>,
        host: Option<Arc<dyn BlockPool<PinnedStorage, Locality, Metadata>>>,
        device: Option<Arc<dyn BlockPool<DeviceStorage, Locality, Metadata>>>,
108
109
        nixl_agent: Arc<Option<NixlAgent>>,
        async_rt_handle: Handle,
110
        metrics: Arc<BlockManagerMetrics>,
111
        cancellation_token: CancellationToken,
112
    ) -> Result<Arc<Self>> {
113
114
115
116
117
        let (device_offload_tx, device_offload_rx) = mpsc::unbounded_channel();
        let (host_offload_tx, host_offload_rx) = mpsc::unbounded_channel();

        let (host_onboard_tx, host_onboard_rx) = mpsc::unbounded_channel();
        let (disk_onboard_tx, disk_onboard_rx) = mpsc::unbounded_channel();
118
119

        let this = Arc::new(Self {
120
            disk,
121
            host,
122
123
124
125
126
            device,
            device_offload_tx,
            host_offload_tx,
            host_onboard_tx,
            disk_onboard_tx,
127
128
129
            tick: Arc::new(Mutex::new(0)),
        });

130
        let cuda_ctx = Cuda::device_or_create(0)?;
131

132
133
134
135
        // We want cuda offloads to happen in parallel with host onboards, so we need to use a different stream.
        let device_offload_transfer_ctx = Arc::new(TransferContext::new(
            nixl_agent.clone(),
            cuda_ctx.new_stream()?,
136
            async_rt_handle.clone(),
137
        ));
138

Ryan Olson's avatar
Ryan Olson committed
139
140
141
142
        let device_metrics = metrics.pool("device");
        let host_metrics = metrics.pool("host");
        let disk_metrics = metrics.pool("disk");

143
        // Device -> Host offload
144
145
146
147
148
        let device_to_host_task = OffloadManager::offload_worker(
            this.device.clone(),
            this.host.clone(),
            device_offload_rx,
            Arc::new(TransferBatcher::new(
Ryan Olson's avatar
Ryan Olson committed
149
                LocalTransferManager::new(
150
151
                    device_offload_transfer_ctx,
                    MAX_CONCURRENT_TRANSFERS,
152
                    &async_rt_handle,
153
                    cancellation_token.clone(),
Ryan Olson's avatar
Ryan Olson committed
154
155
                    device_metrics.clone(),
                    "offload_bw".to_string(),
156
                )?,
157
158
159
160
                MAX_TRANSFER_BATCH_SIZE,
                &async_rt_handle,
                cancellation_token.clone(),
            )),
Ryan Olson's avatar
Ryan Olson committed
161
            device_metrics.clone(),
162
163
164
165
166
167
168
169
170
            cancellation_token.clone(),
        );
        CriticalTaskExecutionHandle::new_with_runtime(
            |_| device_to_host_task,
            cancellation_token.clone(),
            "Device -> Host offload worker",
            &async_rt_handle,
        )?
        .detach();
171

172
173
174
        let transfer_ctx = Arc::new(TransferContext::new(
            nixl_agent.clone(),
            cuda_ctx.new_stream()?,
175
            async_rt_handle.clone(),
176
        ));
177

178
        // Host -> Disk offload
179
180
181
182
183
        let host_to_disk_task = OffloadManager::offload_worker(
            this.host.clone(),
            this.disk.clone(),
            host_offload_rx,
            Arc::new(TransferBatcher::new(
Ryan Olson's avatar
Ryan Olson committed
184
                LocalTransferManager::new(
185
186
187
188
                    transfer_ctx.clone(),
                    MAX_CONCURRENT_TRANSFERS,
                    &async_rt_handle,
                    cancellation_token.clone(),
Ryan Olson's avatar
Ryan Olson committed
189
190
                    host_metrics.clone(),
                    "offload_bw".to_string(),
191
                )?,
192
193
194
195
                MAX_TRANSFER_BATCH_SIZE,
                &async_rt_handle,
                cancellation_token.clone(),
            )),
Ryan Olson's avatar
Ryan Olson committed
196
            host_metrics.clone(),
197
198
199
200
201
202
203
204
205
            cancellation_token.clone(),
        );
        CriticalTaskExecutionHandle::new_with_runtime(
            |_| host_to_disk_task,
            cancellation_token.clone(),
            "Host -> Disk offload worker",
            &async_rt_handle,
        )?
        .detach();
206

207
        // Host -> Device onboarding
208
209
210
211
212
        let host_to_device_task = OffloadManager::onboard_worker(
            this.host.clone(),
            this.device.clone(),
            host_onboard_rx,
            Arc::new(TransferBatcher::new(
Ryan Olson's avatar
Ryan Olson committed
213
                LocalTransferManager::new(
214
215
                    transfer_ctx.clone(),
                    MAX_CONCURRENT_TRANSFERS,
216
                    &async_rt_handle,
217
                    cancellation_token.clone(),
Ryan Olson's avatar
Ryan Olson committed
218
219
                    host_metrics.clone(),
                    "onboard_bw".to_string(),
220
                )?,
221
222
223
224
                MAX_TRANSFER_BATCH_SIZE,
                &async_rt_handle,
                cancellation_token.clone(),
            )),
Ryan Olson's avatar
Ryan Olson committed
225
            host_metrics.clone(),
226
227
228
229
230
231
232
233
234
            cancellation_token.clone(),
        );
        CriticalTaskExecutionHandle::new_with_runtime(
            |_| host_to_device_task,
            cancellation_token.clone(),
            "Host -> Device onboarding worker",
            &async_rt_handle,
        )?
        .detach();
235

236
        // Disk -> Device onboarding
237
238
239
240
241
        let disk_to_device_task = OffloadManager::onboard_worker(
            this.disk.clone(),
            this.device.clone(),
            disk_onboard_rx,
            Arc::new(TransferBatcher::new(
Ryan Olson's avatar
Ryan Olson committed
242
                LocalTransferManager::new(
243
244
245
246
                    transfer_ctx.clone(),
                    MAX_CONCURRENT_TRANSFERS,
                    &async_rt_handle,
                    cancellation_token.clone(),
Ryan Olson's avatar
Ryan Olson committed
247
248
                    disk_metrics.clone(),
                    "onboard_bw".to_string(),
249
                )?,
250
251
252
253
                MAX_TRANSFER_BATCH_SIZE,
                &async_rt_handle,
                cancellation_token.clone(),
            )),
Ryan Olson's avatar
Ryan Olson committed
254
            disk_metrics.clone(),
255
256
257
258
259
260
261
262
263
            cancellation_token.clone(),
        );
        CriticalTaskExecutionHandle::new_with_runtime(
            |_| disk_to_device_task,
            cancellation_token.clone(),
            "Disk -> Device onboarding worker",
            &async_rt_handle,
        )?
        .detach();
264

265
        Ok(this)
266
    }
267

268
    async fn offload_worker<Source: Storage, Target: Storage>(
Ryan Olson's avatar
Ryan Olson committed
269
270
271
272
        source_pool: Option<Arc<dyn BlockPool<Source, Locality, Metadata>>>,
        target_pool: Option<Arc<dyn BlockPool<Target, Locality, Metadata>>>,
        mut offload_rx: mpsc::UnboundedReceiver<OffloadRequest<Source, Locality, Metadata>>,
        transfer_manager: Arc<dyn TransferManager<Source, Target, Locality, Metadata>>,
273
        pool_metrics: Arc<PoolMetrics>,
274
        cancellation_token: CancellationToken,
275
    ) -> Result<()> {
276
        if source_pool.is_none() || target_pool.is_none() {
277
278
279
            return Ok(());
        }

280
281
        let source_pool = source_pool.as_ref().unwrap();
        let target_pool = target_pool.as_ref().unwrap();
282

283
        let mut queue = BTreeSet::new();
284
285

        loop {
286
287
288
289
            if cancellation_token.is_cancelled() {
                return Ok(());
            }

290
            // Try to check the offload queue.
291
292
293
294
            loop {
                match offload_rx.try_recv() {
                    Ok(request) => {
                        queue.insert(request);
295
                        pool_metrics.gauge("offload_queue_size").inc();
296
297
298
299
                    }
                    Err(TryRecvError::Empty) => {
                        break;
                    }
300
                    Err(e) => return Err(e.into()),
301
302
                }
            }
303
304

            // If there is a request, process it.
305
            if let Some(request) = queue.pop_first() {
306
                pool_metrics.gauge("offload_queue_size").dec();
307
308
                // Try to upgrade the block to a strong reference.
                let block = match request.block.upgrade() {
Ryan Olson's avatar
Ryan Olson committed
309
                    Some(block) => Some(ImmutableBlock::new(block)),
310
                    // If unable to upgrade, the block may have been moved to the inactive pool.
311
                    None => source_pool
312
313
                        .match_sequence_hashes(vec![request.sequence_hash].as_slice())
                        .await?
Ryan Olson's avatar
Ryan Olson committed
314
                        .pop(),
315
316
                };

317
                // If we've found the block, offload it.
318
                if let Some(block) = block {
319
320
                    // If the block is already in the target, don't offload it.
                    if let Ok(blocks) = target_pool
Ryan Olson's avatar
Ryan Olson committed
321
322
                        .match_sequence_hashes(vec![request.sequence_hash].as_slice())
                        .await
323
324
325
326
327
328
                    {
                        if !blocks.is_empty() {
                            continue;
                        }
                    }

329
330
331
332
333
                    let target_block = 'target_block: {
                        if let Ok(blocks) = target_pool.allocate_blocks(1).await {
                            if let Some(block) = blocks.into_iter().next() {
                                break 'target_block Some(block);
                            }
334
                        }
335
336
337

                        tracing::warn!("Target pool full. Skipping offload. This should only ever happen with very small pool sizes.");
                        None
338
339
                    };

340
                    if let Some(target_block) = target_block {
341
                        pool_metrics.counter("offload_processed").inc();
Ryan Olson's avatar
Ryan Olson committed
342
343
344
345
                        tracing::debug!(
                            "Offloading block with sequence hash {} to target pool.",
                            request.sequence_hash
                        );
346
                        transfer_manager
347
                            .enqueue_transfer(PendingTransfer::new(
348
                                vec![block],
349
                                vec![target_block],
350
                                None,
351
                                target_pool.clone(),
352
353
354
355
356
                            ))
                            .await?;
                    }
                }
            } else {
357
                // Await the next request.
358
359
360
361
                tokio::select! {
                    _ = cancellation_token.cancelled() => return Ok(()),
                    Some(request) = offload_rx.recv() => {
                        queue.insert(request);
362
                        pool_metrics.gauge("offload_queue_size").inc();
363
                    }
364
                }
365
366
367
368
            }
        }
    }

369
    async fn onboard_worker<Source: Storage, Target: Storage>(
Ryan Olson's avatar
Ryan Olson committed
370
371
372
373
        source_pool: Option<Arc<dyn BlockPool<Source, Locality, Metadata>>>,
        target_pool: Option<Arc<dyn BlockPool<Target, Locality, Metadata>>>,
        mut onboard_rx: mpsc::UnboundedReceiver<OnboardRequest<Source, Target, Locality, Metadata>>,
        transfer_manager: Arc<dyn TransferManager<Source, Target, Locality, Metadata>>,
374
        pool_metrics: Arc<PoolMetrics>,
375
        cancellation_token: CancellationToken,
376
    ) -> Result<()> {
377
        if source_pool.is_none() || target_pool.is_none() {
378
379
380
            return Ok(());
        }

381
        let target_pool = target_pool.as_ref().unwrap();
382
383
384
385
        loop {
            tokio::select! {
                _ = cancellation_token.cancelled() => return Ok::<(), anyhow::Error>(()),
                Some(request) = onboard_rx.recv() => {
386
387
388
389
390

                    pool_metrics
                        .gauge("onboard_queue_size")
                        .set(onboard_rx.len() as i64);

391
                    // Try to allocate blocks on the device.
Ryan Olson's avatar
Ryan Olson committed
392
393
394
395
396
397
398
399
400
                    let target_blocks = if let Some(targets) = request.targets {
                        targets
                    } else {
                            match target_pool.allocate_blocks(request.blocks.len()).await {
                            Ok(blocks) => blocks,
                            Err(err) => {
                                let _ = request.response_tx.send(Err(err));
                                continue;
                            }
401
402
                        }
                    };
403

404
405
406
407
                    pool_metrics
                        .counter("onboard_processed")
                        .inc_by(request.blocks.len() as u64);

Ryan Olson's avatar
Ryan Olson committed
408
                    tracing::debug!("Onboarding {} blocks to target pool.", request.blocks.len());
409
410
411

                    transfer_manager
                        .enqueue_transfer(PendingTransfer::new(
Ryan Olson's avatar
Ryan Olson committed
412
                            request.blocks,
413
414
415
416
417
418
419
                            target_blocks,
                            Some(request.response_tx),
                            target_pool.clone(),
                        ))
                        .await?;

                    Ok::<(), anyhow::Error>(())
420
                }
421
            }?;
422
423
424
425
426
        }
    }

    pub async fn offload<S: Storage>(
        &self,
Ryan Olson's avatar
Ryan Olson committed
427
        block: &ImmutableBlock<S, Locality, Metadata>,
428
429
430
        priority: u64,
    ) -> core::result::Result<(), BlockPoolError> {
        match block.state() {
431
            BlockState::Registered(_, _) => {}
432
433
434
435
436
437
            _ => {
                return Err(BlockPoolError::BlockError(BlockError::InvalidState(
                    "Block is not registered.".to_string(),
                )));
            }
        }
438
439
440
441
442
443
444
445
446
447

        let mut tick = self.tick.lock().await;
        let key = OffloadRequestKey {
            priority,
            timestamp: *tick,
        };
        // Increment a counter for each block. Within the same priority, blocks with lower counter values are processed first.
        *tick += 1;
        drop(tick);

448
449
450
451
452
453
        // This can get called by all pools, regardless of whether or not they have a place to offload to.
        // Because of this, we need to check the block type here.
        let any_block = block as &dyn Any;

        // TODO: What's the performance penalty of this runtime type-checking?
        if let Some(device_block) =
Ryan Olson's avatar
Ryan Olson committed
454
            any_block.downcast_ref::<ImmutableBlock<DeviceStorage, Locality, Metadata>>()
455
        {
456
457
458
459
            // The host pool doesn't exist, so we can't offload to it.
            if self.device_offload_tx.is_closed() {
                return Ok(());
            }
460
461
462

            let request = OffloadRequest {
                block: Arc::downgrade(device_block.mutable_block()),
Ryan Olson's avatar
Ryan Olson committed
463
                sequence_hash: device_block.sequence_hash(),
464
465
466
                key,
            };

467
468
            self.device_offload_tx.send(request).unwrap();
        } else if let Some(host_block) =
Ryan Olson's avatar
Ryan Olson committed
469
            any_block.downcast_ref::<ImmutableBlock<PinnedStorage, Locality, Metadata>>()
470
471
472
473
474
475
476
477
        {
            // The disk pool doesn't exist, so we can't offload to it.
            if self.host_offload_tx.is_closed() {
                return Ok(());
            }

            let request = OffloadRequest {
                block: Arc::downgrade(host_block.mutable_block()),
Ryan Olson's avatar
Ryan Olson committed
478
                sequence_hash: host_block.sequence_hash(),
479
480
481
482
                key,
            };

            self.host_offload_tx.send(request).unwrap();
483
484
485
486
487
        }

        Ok(())
    }

Ryan Olson's avatar
Ryan Olson committed
488
    pub fn onboard<S: Storage>(
489
        &self,
Ryan Olson's avatar
Ryan Olson committed
490
491
492
493
        blocks: Vec<ImmutableBlock<S, Locality, Metadata>>,
        targets: Option<Vec<MutableBlock<DeviceStorage, Locality, Metadata>>>,
    ) -> oneshot::Receiver<BlockResult<DeviceStorage, Locality, Metadata>> {
        let (tx, rx) = oneshot::channel();
494
495
        for block in &blocks {
            match block.state() {
496
                BlockState::Registered(_, _) => {}
497
                _ => {
Ryan Olson's avatar
Ryan Olson committed
498
                    tx.send(Err(BlockPoolError::BlockError(BlockError::InvalidState(
499
                        "Block is not registered.".to_string(),
Ryan Olson's avatar
Ryan Olson committed
500
501
502
                    ))))
                    .unwrap();
                    return rx;
503
504
505
506
                }
            }
        }

Ryan Olson's avatar
Ryan Olson committed
507
508
509
510
511
512
513
514
        if let Some(targets) = targets.as_ref() {
            if targets.len() != blocks.len() {
                tx.send(Err(BlockPoolError::BlockError(BlockError::Other(
                    anyhow::anyhow!("Number of targets does not match number of blocks."),
                ))))
                .unwrap();
                return rx;
            }
515
516
        }

Ryan Olson's avatar
Ryan Olson committed
517
518
519
520
        if blocks.is_empty() {
            tx.send(Ok(vec![])).unwrap();
            return rx;
        }
521

522
523
524
525
        let any_block = blocks.first().unwrap() as &dyn Any;

        // TODO: This is really ugly.
        if any_block
Ryan Olson's avatar
Ryan Olson committed
526
            .downcast_ref::<ImmutableBlock<PinnedStorage, Locality, Metadata>>()
527
528
529
530
531
532
            .is_some()
        {
            let host_blocks = blocks
                .iter()
                .map(|b| {
                    (b as &dyn Any)
Ryan Olson's avatar
Ryan Olson committed
533
                        .downcast_ref::<ImmutableBlock<PinnedStorage, Locality, Metadata>>()
534
535
536
537
538
                        .unwrap()
                        .clone()
                })
                .collect();

Ryan Olson's avatar
Ryan Olson committed
539
540
541
542
543
544
545
546
            if let Err(e) = self
                .host_onboard_tx
                .send(OnboardRequest::new(host_blocks, tx, targets))
            {
                e.0.response_tx
                    .send(Err(BlockPoolError::ProgressEngineShutdown))
                    .unwrap();
            }
547
        } else if any_block
Ryan Olson's avatar
Ryan Olson committed
548
            .downcast_ref::<ImmutableBlock<DiskStorage, Locality, Metadata>>()
549
550
551
552
553
554
            .is_some()
        {
            let disk_blocks = blocks
                .iter()
                .map(|b| {
                    (b as &dyn Any)
Ryan Olson's avatar
Ryan Olson committed
555
                        .downcast_ref::<ImmutableBlock<DiskStorage, Locality, Metadata>>()
556
557
558
559
560
                        .unwrap()
                        .clone()
                })
                .collect();

Ryan Olson's avatar
Ryan Olson committed
561
562
563
564
565
566
567
568
            if let Err(e) = self
                .disk_onboard_tx
                .send(OnboardRequest::new(disk_blocks, tx, targets))
            {
                e.0.response_tx
                    .send(Err(BlockPoolError::ProgressEngineShutdown))
                    .unwrap();
            }
569
        } else {
Ryan Olson's avatar
Ryan Olson committed
570
            tx.send(Err(BlockPoolError::BlockError(BlockError::Other(
571
                anyhow::anyhow!("Block type not supported for onboarding."),
Ryan Olson's avatar
Ryan Olson committed
572
573
            ))))
            .unwrap();
574
575
        }

Ryan Olson's avatar
Ryan Olson committed
576
        rx
577
578
579
580
    }
}

#[cfg(all(test, feature = "testing-cuda"))]
Ryan Olson's avatar
Ryan Olson committed
581
mod tests {
582
583
584
    use super::*;

    use crate::block_manager::{
585
        block::{
Ryan Olson's avatar
Ryan Olson committed
586
            locality::Local, BasicMetadata, BlockDataExt, BlockDataProvider, Blocks, MutableBlock,
587
        },
Ryan Olson's avatar
Ryan Olson committed
588
589
        layout::{nixl::NixlLayout, FullyContiguous, LayerSeparate, LayoutType},
        pool::{BlockRegistrationDuplicationSetting, ManagedBlockPool},
590
        storage::{
591
            DeviceAllocator, DeviceStorage, DiskAllocator, DiskStorage, PinnedAllocator,
Ryan Olson's avatar
Ryan Olson committed
592
            PinnedStorage, StorageAllocator, StorageType,
593
        },
Ryan Olson's avatar
Ryan Olson committed
594
        LayoutConfig, NixlRegisterableStorage,
595
    };
596
    use crate::tokens::{TokenBlockSequence, Tokens};
597
    use nixl_sys::{MemoryRegion, NixlDescriptor};
598

599
    use aligned_vec::avec;
600
    use cudarc::runtime::sys::{cudaMemcpy, cudaMemcpyKind, cudaMemset};
601
    use prometheus::Registry;
Ryan Olson's avatar
Ryan Olson committed
602
    use rstest::*;
603
    use std::fs::File;
604
    use std::io::{Read, Seek, SeekFrom, Write};
605
606
    use std::mem::ManuallyDrop;
    use std::os::unix::io::FromRawFd;
607
608

    const BLOCK_SIZE: usize = 4;
609
    const NUM_LAYERS: usize = 8;
610

Ryan Olson's avatar
Ryan Olson committed
611
612
613
    type DevicePool = Option<Arc<dyn BlockPool<DeviceStorage, Local, BasicMetadata>>>;
    type HostPool = Option<Arc<dyn BlockPool<PinnedStorage, Local, BasicMetadata>>>;
    type DiskPool = Option<Arc<dyn BlockPool<DiskStorage, Local, BasicMetadata>>>;
614
615
616
617
618

    lazy_static::lazy_static! {
        static ref NIXL_AGENT: Arc<Option<NixlAgent>> = {
            let agent = NixlAgent::new("offload-manager").unwrap();
            let (_, ucx_params) = agent.get_plugin_params("UCX").unwrap();
Ryan Olson's avatar
Ryan Olson committed
619
            let (_, gds_mt_params) = agent.get_plugin_params("GDS_MT").unwrap();
620
            let (_, posix_params) = agent.get_plugin_params("POSIX").unwrap();
621
            agent.create_backend("UCX", &ucx_params).unwrap();
Ryan Olson's avatar
Ryan Olson committed
622
            agent.create_backend("GDS_MT", &gds_mt_params).unwrap();
623
            agent.create_backend("POSIX", &posix_params).unwrap();
624
625
626
            Arc::new(Some(agent))
        };
    }
627

Ryan Olson's avatar
Ryan Olson committed
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
    fn build_layout<S: Storage + NixlRegisterableStorage>(
        config: LayoutConfig,
        layout_type: LayoutType,
        agent: &NixlAgent,
        allocator: &dyn StorageAllocator<S>,
        duplication_setting: BlockRegistrationDuplicationSetting,
    ) -> Result<Arc<dyn BlockPool<S, Local, BasicMetadata>>> {
        match layout_type {
            LayoutType::FullyContiguous => {
                let mut pool_layout = FullyContiguous::allocate(config.clone(), allocator)?;
                pool_layout.nixl_register(agent, None)?;
                let blocks = Blocks::new(pool_layout, 42, 0)?.into_blocks()?;
                Ok(Arc::new(
                    ManagedBlockPool::builder()
                        .blocks(blocks)
                        .default_duplication_setting(duplication_setting)
                        .build()?,
                ))
            }
            LayoutType::LayerSeparate { outer_contiguous } => {
                let mut pool_layout =
                    LayerSeparate::allocate(config.clone(), allocator, outer_contiguous)?;
                pool_layout.nixl_register(agent, None)?;
                let blocks = Blocks::new(pool_layout, 42, 0)?.into_blocks()?;
                Ok(Arc::new(
                    ManagedBlockPool::builder()
                        .blocks(blocks)
                        .default_duplication_setting(duplication_setting)
                        .build()?,
                ))
            }
        }
    }

    #[allow(clippy::type_complexity)]
    fn build_pools(
664
665
        device_blocks: usize,
        host_blocks: Option<usize>,
666
        disk_blocks: Option<usize>,
667
        inner_dim: Option<usize>,
668
    ) -> Result<(
Ryan Olson's avatar
Ryan Olson committed
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
        Arc<OffloadManager<Local, BasicMetadata>>,
        DevicePool,
        HostPool,
        DiskPool,
    )> {
        build_pools_with_layout(
            device_blocks,
            host_blocks,
            disk_blocks,
            inner_dim,
            LayoutType::FullyContiguous,
            BlockRegistrationDuplicationSetting::Disabled,
        )
    }

    #[allow(clippy::type_complexity)]
    pub fn build_pools_with_layout(
        device_blocks: usize,
        host_blocks: Option<usize>,
        disk_blocks: Option<usize>,
        inner_dim: Option<usize>,
        layout_type: LayoutType,
        duplication_setting: BlockRegistrationDuplicationSetting,
    ) -> Result<(
        Arc<OffloadManager<Local, BasicMetadata>>,
694
695
696
697
        DevicePool,
        HostPool,
        DiskPool,
    )> {
698
699
        let mut config = LayoutConfig {
            num_blocks: device_blocks,
700
            num_layers: NUM_LAYERS,
701
            outer_dim: 1,
702
            page_size: BLOCK_SIZE,
703
            inner_dim: inner_dim.unwrap_or(1024),
704
            alignment: 1,
Ryan Olson's avatar
Ryan Olson committed
705
            dtype_width_bytes: 2,
706
707
        };

708
709
710
        let agent_arc = NIXL_AGENT.clone();
        let agent = agent_arc.as_ref().as_ref().unwrap();

Ryan Olson's avatar
Ryan Olson committed
711
712
713
714
715
716
717
        let device_pool = Some(build_layout(
            config.clone(),
            layout_type,
            agent,
            &DeviceAllocator::default(),
            duplication_setting,
        )?);
718
719
720

        let host_pool = if let Some(host_blocks) = host_blocks {
            config.num_blocks = host_blocks;
Ryan Olson's avatar
Ryan Olson committed
721
722
723
724
725
726
727
            Some(build_layout(
                config.clone(),
                layout_type,
                agent,
                &PinnedAllocator::default(),
                duplication_setting,
            )?)
728
        } else {
729
            None
730
731
        };

732
733
        let disk_pool = if let Some(disk_blocks) = disk_blocks {
            config.num_blocks = disk_blocks;
Ryan Olson's avatar
Ryan Olson committed
734
735
736
737
738
739
740
            Some(build_layout(
                config,
                layout_type,
                agent,
                &DiskAllocator,
                duplication_setting,
            )?)
741
        } else {
742
            None
743
        };
744

745
746
747
748
749
750
751
752
        let async_rt_handle = Handle::current();

        let manager = OffloadManager::new(
            disk_pool.clone(),
            host_pool.clone(),
            device_pool.clone(),
            agent_arc,
            async_rt_handle,
753
            BlockManagerMetrics::new(&Arc::new(Registry::new()))?,
754
            CancellationToken::new(),
755
756
757
        )?;

        Ok((manager, device_pool, host_pool, disk_pool))
758
759
760
    }

    /// Create a block in the 'RESET' state.
Ryan Olson's avatar
Ryan Olson committed
761
    #[expect(dead_code)]
762
    async fn get_block<S: Storage, Metadata: BlockMetadata>(
Ryan Olson's avatar
Ryan Olson committed
763
764
765
766
        pool: &Arc<dyn BlockPool<S, Local, Metadata>>,
    ) -> Result<MutableBlock<S, Local, Metadata>> {
        let mut blocks = pool.allocate_blocks(1).await?;
        Ok(blocks.pop().unwrap())
767
768
769
770
    }

    /// Create a block in the 'COMPLETED' state.
    async fn completed_block<S: Storage, Metadata: BlockMetadata>(
Ryan Olson's avatar
Ryan Olson committed
771
        pool: &Arc<dyn BlockPool<S, Local, Metadata>>,
772
        tokens: [u32; BLOCK_SIZE],
Ryan Olson's avatar
Ryan Olson committed
773
774
775
776
777
778
779
780
    ) -> Result<MutableBlock<S, Local, Metadata>> {
        let mut block = pool
            .allocate_blocks(1)
            .await?
            .into_iter()
            .next()
            .ok_or(anyhow::anyhow!("Failed to allocate block"))?;

781
782
783
784
785
786
787
788
        block.init_sequence(42)?;
        for token in tokens {
            block.add_token(token)?;
        }
        block.commit()?;
        Ok(block)
    }

789
    fn populate_block<S: Storage + NixlDescriptor>(
790
        block: &impl BlockDataProvider<StorageType = S>,
Ryan Olson's avatar
Ryan Olson committed
791
        start_value: u8,
792
    ) -> Result<()> {
Ryan Olson's avatar
Ryan Olson committed
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
        let block_data = block.block_data();

        let mut value = start_value;

        for layer_idx in 0..block_data.num_layers() {
            for outer_idx in 0..block_data.num_outer_dims() {
                let layer_view = block_data.layer_view(layer_idx, outer_idx)?;
                match block_data.storage_type() {
                    StorageType::Device(_) | StorageType::Pinned => unsafe {
                        cudaMemset(
                            layer_view.as_ptr() as *mut std::ffi::c_void,
                            value as i32,
                            layer_view.size(),
                        )
                        .result()?;
                    },
                    StorageType::Disk(_) => {
                        let nixl_desc = layer_view.as_nixl_descriptor();
                        let mut file: ManuallyDrop<File>;
                        let data = avec![[4096] | value; layer_view.size()];

                        unsafe {
                            file =
                                ManuallyDrop::new(File::from_raw_fd(nixl_desc.device_id() as i32));
                            file.seek(SeekFrom::Start(nixl_desc.as_ptr() as u64))?;
                        }
                        file.write_all(&data)?;
                        file.sync_all()?;
                        file.flush()?;
                    }
                    _ => panic!(),
824
825
                }
            }
Ryan Olson's avatar
Ryan Olson committed
826
827

            value += 1;
828
        }
829

830
831
832
        Ok(())
    }

833
834
    fn get_block_contents<S: Storage + NixlDescriptor>(
        block: &impl BlockDataProvider<StorageType = S>,
Ryan Olson's avatar
Ryan Olson committed
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
865
866
867
868
869
870
871
872
873
874
875
876
    ) -> Result<Vec<Vec<u8>>> {
        let block_data = block.block_data();

        let mut contents: Vec<Vec<u8>> = Vec::new();

        for layer_idx in 0..block_data.num_layers() {
            for outer_idx in 0..block_data.num_outer_dims() {
                let layer_view = block_data.layer_view(layer_idx, outer_idx)?;
                match block_data.storage_type() {
                    StorageType::Device(_) => unsafe {
                        let mut buffer = vec![0_u8; layer_view.size()];

                        cudaMemcpy(
                            buffer.as_mut_ptr() as *mut std::ffi::c_void,
                            layer_view.as_ptr() as *const std::ffi::c_void,
                            layer_view.size(),
                            cudaMemcpyKind::cudaMemcpyDeviceToHost,
                        )
                        .result()?;

                        contents.push(buffer);
                    },
                    StorageType::Pinned => unsafe {
                        contents.push(
                            std::slice::from_raw_parts(layer_view.as_ptr(), layer_view.size())
                                .to_vec(),
                        );
                    },
                    StorageType::Disk(_) => {
                        let nixl_desc = layer_view.as_nixl_descriptor();
                        let mut file: ManuallyDrop<File>;
                        let mut aligned = avec![[4096] | 0; layer_view.size()];

                        unsafe {
                            file =
                                ManuallyDrop::new(File::from_raw_fd(nixl_desc.device_id() as i32));
                            file.seek(SeekFrom::Start(nixl_desc.as_ptr() as u64))?;
                        }
                        file.read_exact(&mut aligned)?;
                        contents.push(aligned.to_vec());
                    }
                    _ => anyhow::bail!("Unsupported storage type."),
877
878
                }
            }
879
880
        }

Ryan Olson's avatar
Ryan Olson committed
881
        Ok(contents)
882
883
    }

884
    fn check_block_contents(
885
886
        block1: &impl BlockDataProvider<StorageType = impl Storage + NixlDescriptor>,
        block2: &impl BlockDataProvider<StorageType = impl Storage + NixlDescriptor>,
Ryan Olson's avatar
Ryan Olson committed
887
        start_value: u8,
888
    ) -> Result<()> {
889
890
        let contents1 = get_block_contents(block1)?;
        let contents2 = get_block_contents(block2)?;
891

Ryan Olson's avatar
Ryan Olson committed
892
893
894
895
896
897
898
899
900
        assert_eq!(contents1.len(), contents2.len());

        let mut value = start_value;

        for (layer1_vec, layer2_vec) in contents1.iter().zip(contents2.iter()) {
            for (c1_value, c2_value) in layer1_vec.iter().zip(layer2_vec.iter()) {
                if c1_value != c2_value || c1_value != &value {
                    panic!("{} != {} != {}", c1_value, c2_value, value);
                }
901
            }
Ryan Olson's avatar
Ryan Olson committed
902
            value += 1;
903
        }
904
905
906
907
908
        Ok(())
    }

    #[tokio::test]
    async fn test_offload_invalid_blocks() -> Result<()> {
909
        let (offload_manager, device_pool, _, _) = build_pools(4, Some(4), None, None)?;
910

911
        let device_pool = device_pool.as_ref().unwrap();
912
913
914
915
916
917
918
919
920
921
922
923
924
925

        // Check blocks in the 'COMPLETED' state.
        let immutable_block = ImmutableBlock::new(Arc::new(
            completed_block(device_pool, [0; BLOCK_SIZE]).await?,
        ));
        assert!(matches!(
            offload_manager.offload(&immutable_block, 0).await,
            Err(BlockPoolError::BlockError(BlockError::InvalidState(_)))
        ));

        Ok(())
    }

    #[tokio::test]
Ryan Olson's avatar
Ryan Olson committed
926
927
928
929
930
931
932
933
934
935
936
937
938
    #[rstest]
    #[case(LayoutType::FullyContiguous)]
    #[case(LayoutType::LayerSeparate { outer_contiguous: true })]
    #[case(LayoutType::LayerSeparate { outer_contiguous: false })]
    async fn test_offload_registered_blocks(#[case] layout_type: LayoutType) -> Result<()> {
        let (offload_manager, device_pool, host_pool, _) = build_pools_with_layout(
            4,
            Some(4),
            None,
            None,
            layout_type,
            BlockRegistrationDuplicationSetting::Disabled,
        )?;
939

940
941
        let device_pool = device_pool.as_ref().unwrap();
        let host_pool = host_pool.as_ref().unwrap();
942
943
944
945
946
947
948
949
950
951
952

        // Create a block and register it with the offload manager
        let block = completed_block(device_pool, [0, 1, 2, 3]).await?;

        let immutable_device_block = device_pool
            .register_blocks(vec![block])
            .await?
            .into_iter()
            .next()
            .ok_or(anyhow::anyhow!("Failed to register block"))?;

953
        populate_block(&immutable_device_block, 42)?;
954
955
956
957
958
959
960
961
962
963
964

        // Offloads should only go to G2 (for now)
        offload_manager.offload(&immutable_device_block, 0).await?;

        // Wait for it to be processed.
        // TODO: This is a bit of a hack, and may lead to non-deterministic behavior.
        // In theory, the offload + memcpy should take much less time than this.
        tokio::time::sleep(std::time::Duration::from_millis(100)).await;

        // Check that the block exists in the host pool
        let host_blocks = host_pool
Ryan Olson's avatar
Ryan Olson committed
965
            .match_sequence_hashes(vec![immutable_device_block.sequence_hash()].as_slice())
966
967
968
969
            .await?;

        assert_eq!(host_blocks.len(), 1);
        assert_eq!(
Ryan Olson's avatar
Ryan Olson committed
970
971
            host_blocks[0].sequence_hash(),
            immutable_device_block.sequence_hash()
972
973
        );

974
        check_block_contents(&immutable_device_block, &host_blocks[0], 42)?;
975
976
977
978
979
980

        Ok(())
    }

    #[tokio::test]
    async fn test_no_host_blocks_available() -> Result<()> {
981
        let (offload_manager, device_pool, host_pool, _) = build_pools(4, Some(4), None, None)?;
982

983
984
        let device_pool = device_pool.as_ref().unwrap();
        let host_pool = host_pool.as_ref().unwrap();
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003

        let host_blocks = host_pool.allocate_blocks(4).await?;
        assert_eq!(host_blocks.len(), 4);

        let device_block = completed_block(device_pool, [0, 1, 2, 3]).await?;
        let immutable_device_block = device_pool
            .register_blocks(vec![device_block])
            .await?
            .into_iter()
            .next()
            .unwrap();

        offload_manager.offload(&immutable_device_block, 0).await?;

        // Wait for offload to be processed.
        tokio::time::sleep(std::time::Duration::from_millis(100)).await;

        // The offload should fail gracefuly due to a lack of host blocks
        let matched_host_blocks = host_pool
Ryan Olson's avatar
Ryan Olson committed
1004
            .match_sequence_hashes(vec![immutable_device_block.sequence_hash()].as_slice())
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
            .await?;
        assert_eq!(matched_host_blocks.len(), 0);

        // Wait for blocks to be returned to the pool.
        drop(host_blocks);
        tokio::time::sleep(std::time::Duration::from_millis(100)).await;

        // Try the offload again.
        offload_manager.offload(&immutable_device_block, 0).await?;

        // Wait for offload to be processed.
        tokio::time::sleep(std::time::Duration::from_millis(100)).await;

        // This time, the offload should succeed.
        let matched_host_blocks = host_pool
Ryan Olson's avatar
Ryan Olson committed
1020
            .match_sequence_hashes(vec![immutable_device_block.sequence_hash()].as_slice())
1021
1022
1023
1024
1025
1026
1027
            .await?;
        assert_eq!(matched_host_blocks.len(), 1);

        Ok(())
    }

    #[tokio::test]
Ryan Olson's avatar
Ryan Olson committed
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
    #[rstest]
    #[case(LayoutType::FullyContiguous)]
    #[case(LayoutType::LayerSeparate { outer_contiguous: true })]
    #[case(LayoutType::LayerSeparate { outer_contiguous: false })]
    async fn test_onboard(#[case] layout_type: LayoutType) -> Result<()> {
        let (offload_manager, device_pool, host_pool, _) = build_pools_with_layout(
            4,
            Some(4),
            None,
            None,
            layout_type,
            BlockRegistrationDuplicationSetting::Disabled,
        )?;
1041

1042
1043
        let device_pool = device_pool.as_ref().unwrap();
        let host_pool = host_pool.as_ref().unwrap();
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053

        // Allocate and fill a block on the host.
        let host_block = completed_block(host_pool, [0, 1, 2, 3]).await?;
        let immutable_host_block = host_pool
            .register_blocks(vec![host_block])
            .await?
            .into_iter()
            .next()
            .unwrap();

1054
        populate_block(&immutable_host_block, 42)?;
1055
1056
1057

        // Onboard the block.
        let onboarded_blocks = offload_manager
Ryan Olson's avatar
Ryan Olson committed
1058
1059
            .onboard(vec![immutable_host_block.clone()], None)
            .await??;
1060
1061
1062
1063

        assert_eq!(onboarded_blocks.len(), 1);
        // Check that the sequence hash is the same.
        assert_eq!(
Ryan Olson's avatar
Ryan Olson committed
1064
1065
            onboarded_blocks[0].sequence_hash(),
            immutable_host_block.sequence_hash()
1066
1067
1068
1069
        );
        // Check that the block is registered.
        assert!(matches!(
            onboarded_blocks[0].state(),
1070
            BlockState::Registered(_, _)
1071
1072
        ));

1073
        check_block_contents(&immutable_host_block, &onboarded_blocks[0], 42)?;
1074
1075
1076
1077

        // Wait for the new value to show up in the device pool.
        tokio::time::sleep(std::time::Duration::from_millis(100)).await;
        let device_blocks = device_pool
Ryan Olson's avatar
Ryan Olson committed
1078
            .match_sequence_hashes(vec![onboarded_blocks[0].sequence_hash()].as_slice())
1079
1080
1081
            .await?;
        assert_eq!(device_blocks.len(), 1);
        assert_eq!(
Ryan Olson's avatar
Ryan Olson committed
1082
1083
            device_blocks[0].sequence_hash(),
            onboarded_blocks[0].sequence_hash()
1084
1085
1086
        );

        // Check that this is the same block.
1087
        check_block_contents(&immutable_host_block, &device_blocks[0], 42)?;
1088
1089
1090
1091
1092

        Ok(())
    }

    #[tokio::test]
Ryan Olson's avatar
Ryan Olson committed
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
    #[rstest]
    #[case(LayoutType::FullyContiguous)]
    #[case(LayoutType::LayerSeparate { outer_contiguous: true })]
    #[case(LayoutType::LayerSeparate { outer_contiguous: false })]
    async fn test_offload_onboard(#[case] layout_type: LayoutType) -> Result<()> {
        let (offload_manager, device_pool, host_pool, _) = build_pools_with_layout(
            4,
            Some(4),
            None,
            None,
            layout_type,
            BlockRegistrationDuplicationSetting::Disabled,
        )?;
1106

1107
1108
        let device_pool = device_pool.as_ref().unwrap();
        let host_pool = host_pool.as_ref().unwrap();
1109
1110
1111
1112
1113
1114
1115
1116
1117

        let device_block = completed_block(device_pool, [0, 1, 2, 3]).await?;
        let immutable_device_block = device_pool
            .register_blocks(vec![device_block])
            .await?
            .into_iter()
            .next()
            .unwrap();

1118
        populate_block(&immutable_device_block, 42)?;
1119
1120
1121
1122
1123
1124
1125
1126
        // Offload the block to the host.
        offload_manager.offload(&immutable_device_block, 0).await?;

        // Wait for the offload to be processed.
        tokio::time::sleep(std::time::Duration::from_millis(100)).await;

        // Check that the block exists in the host pool.
        let immutable_host_block = host_pool
Ryan Olson's avatar
Ryan Olson committed
1127
            .match_sequence_hashes(vec![immutable_device_block.sequence_hash()].as_slice())
1128
1129
1130
1131
1132
            .await?
            .into_iter()
            .next()
            .unwrap();

1133
        check_block_contents(&immutable_device_block, &immutable_host_block, 42)?;
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148

        // Remove the device block from the pool by dropping it and allocating more blocks.
        drop(immutable_device_block);

        // Wait for the block to be returned to the pool.
        tokio::time::sleep(std::time::Duration::from_millis(100)).await;

        let device_blocks = device_pool.allocate_blocks(4).await?;
        assert_eq!(device_blocks.len(), 4);

        drop(device_blocks);
        tokio::time::sleep(std::time::Duration::from_millis(100)).await;

        // Check that the block is not in the device pool.
        let device_blocks = device_pool
Ryan Olson's avatar
Ryan Olson committed
1149
            .match_sequence_hashes(vec![immutable_host_block.sequence_hash()].as_slice())
1150
1151
1152
1153
1154
            .await?;
        assert_eq!(device_blocks.len(), 0);

        // Onboard the block back to the device pool.
        let onboarded_blocks = offload_manager
Ryan Olson's avatar
Ryan Olson committed
1155
1156
            .onboard(vec![immutable_host_block.clone()], None)
            .await??;
1157
1158
        assert_eq!(onboarded_blocks.len(), 1);
        assert_eq!(
Ryan Olson's avatar
Ryan Olson committed
1159
1160
            onboarded_blocks[0].sequence_hash(),
            immutable_host_block.sequence_hash()
1161
1162
1163
        );
        assert!(matches!(
            onboarded_blocks[0].state(),
1164
            BlockState::Registered(_, _)
1165
1166
        ));

1167
        check_block_contents(&immutable_host_block, &onboarded_blocks[0], 42)?;
1168
1169
1170
1171
1172
1173

        Ok(())
    }

    #[tokio::test]
    async fn test_onboard_err_handling() -> Result<()> {
1174
        let (offload_manager, device_pool, host_pool, _) = build_pools(4, Some(4), None, None)?;
1175

1176
1177
        let device_pool = device_pool.as_ref().unwrap();
        let host_pool = host_pool.as_ref().unwrap();
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190

        let host_block = completed_block(host_pool, [0, 1, 2, 3]).await?;
        let immutable_host_block = host_pool
            .register_blocks(vec![host_block])
            .await?
            .into_iter()
            .next()
            .unwrap();

        let device_blocks = device_pool.allocate_blocks(4).await?;
        assert_eq!(device_blocks.len(), 4);

        let res = offload_manager
Ryan Olson's avatar
Ryan Olson committed
1191
1192
            .onboard(vec![immutable_host_block.clone()], None)
            .await?;
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
        assert!(matches!(
            res.err().unwrap(),
            BlockPoolError::NotEnoughBlocksAvailable(_, _)
        ));

        Ok(())
    }

    #[tokio::test]
    async fn test_offload_onboard_no_host_blocks() -> Result<()> {
1203
        let (offload_manager, device_pool, _, _) = build_pools(4, None, None, None)?;
1204

1205
        let device_pool = device_pool.as_ref().unwrap();
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218

        let device_block = completed_block(device_pool, [0, 1, 2, 3]).await?;
        let immutable_device_block = device_pool
            .register_blocks(vec![device_block])
            .await?
            .into_iter()
            .next()
            .unwrap();

        offload_manager.offload(&immutable_device_block, 0).await?;

        Ok(())
    }
1219
1220

    #[tokio::test]
Ryan Olson's avatar
Ryan Olson committed
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
    #[rstest]
    #[case(LayoutType::FullyContiguous)]
    #[case(LayoutType::LayerSeparate { outer_contiguous: true })]
    #[case(LayoutType::LayerSeparate { outer_contiguous: false })]
    async fn test_offload_disk(#[case] layout_type: LayoutType) -> Result<()> {
        let (offload_manager, _, host_pool, disk_pool) = build_pools_with_layout(
            4,
            Some(4),
            Some(4),
            None,
            layout_type,
            BlockRegistrationDuplicationSetting::Disabled,
        )?;
1234

1235
1236
        let host_pool = host_pool.as_ref().unwrap();
        let disk_pool = disk_pool.as_ref().unwrap();
1237
1238
1239
1240
1241
1242
1243
1244
1245

        let host_block = completed_block(host_pool, [0, 1, 2, 3]).await?;
        let immutable_host_block = host_pool
            .register_blocks(vec![host_block])
            .await?
            .into_iter()
            .next()
            .unwrap();

1246
        populate_block(&immutable_host_block, 42)?;
1247
1248
1249
1250
1251
1252

        offload_manager.offload(&immutable_host_block, 0).await?;

        tokio::time::sleep(std::time::Duration::from_millis(500)).await;

        let disk_blocks = disk_pool
Ryan Olson's avatar
Ryan Olson committed
1253
            .match_sequence_hashes(vec![immutable_host_block.sequence_hash()].as_slice())
1254
1255
1256
            .await?;
        assert_eq!(disk_blocks.len(), 1);
        assert_eq!(
Ryan Olson's avatar
Ryan Olson committed
1257
1258
            disk_blocks[0].sequence_hash(),
            immutable_host_block.sequence_hash()
1259
1260
        );

1261
        check_block_contents(&immutable_host_block, &disk_blocks[0], 42)?;
1262
1263
1264
1265
1266

        Ok(())
    }

    #[tokio::test]
Ryan Olson's avatar
Ryan Olson committed
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
    #[rstest]
    #[case(LayoutType::FullyContiguous)]
    #[case(LayoutType::LayerSeparate { outer_contiguous: true })]
    #[case(LayoutType::LayerSeparate { outer_contiguous: false })]
    async fn test_onboard_disk(#[case] layout_type: LayoutType) -> Result<()> {
        let (offload_manager, device_pool, _, disk_pool) = build_pools_with_layout(
            4,
            None,
            Some(4),
            None,
            layout_type,
            BlockRegistrationDuplicationSetting::Disabled,
        )?;
1280

1281
1282
        let device_pool = device_pool.as_ref().unwrap();
        let disk_pool = disk_pool.as_ref().unwrap();
1283
1284
1285
1286
1287
1288
1289
1290
1291

        let disk_block = completed_block(disk_pool, [0, 1, 2, 3]).await?;
        let immutable_disk_block = disk_pool
            .register_blocks(vec![disk_block])
            .await?
            .into_iter()
            .next()
            .unwrap();

1292
1293
        populate_block(&immutable_disk_block, 42)?;

1294
        let device_block = offload_manager
Ryan Olson's avatar
Ryan Olson committed
1295
1296
            .onboard(vec![immutable_disk_block.clone()], None)
            .await??;
1297

1298
1299
        check_block_contents(&immutable_disk_block, &device_block[0], 42)?;

1300
1301
        assert_eq!(device_block.len(), 1);
        assert_eq!(
Ryan Olson's avatar
Ryan Olson committed
1302
1303
            device_block[0].sequence_hash(),
            immutable_disk_block.sequence_hash()
1304
1305
1306
        );
        assert_eq!(
            device_pool
Ryan Olson's avatar
Ryan Olson committed
1307
                .match_sequence_hashes(vec![immutable_disk_block.sequence_hash()].as_slice())
1308
1309
1310
1311
1312
1313
1314
1315
1316
                .await?
                .len(),
            1
        );

        Ok(())
    }

    #[tokio::test]
Ryan Olson's avatar
Ryan Olson committed
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
    #[rstest]
    #[case(LayoutType::FullyContiguous)]
    #[case(LayoutType::LayerSeparate { outer_contiguous: true })]
    #[case(LayoutType::LayerSeparate { outer_contiguous: false })]
    async fn test_bulk_transfer_disk(#[case] layout_type: LayoutType) -> Result<()> {
        let (offload_manager, device_pool, host_pool, disk_pool) = build_pools_with_layout(
            8,
            Some(8),
            Some(8),
            None,
            layout_type,
            BlockRegistrationDuplicationSetting::Disabled,
        )?;
1330

1331
1332
1333
        let disk_pool = disk_pool.as_ref().unwrap();
        let host_pool = host_pool.as_ref().unwrap();
        let device_pool = device_pool.as_ref().unwrap();
1334
1335
1336
1337
1338

        let mut host_blocks = Vec::new();

        for i in 0..8 {
            let block = completed_block(host_pool, [i; 4]).await?;
1339
            populate_block(&block, i as u8)?;
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
            host_blocks.push(block);
        }

        let immutable_host_blocks = host_pool.register_blocks(host_blocks).await?;

        for block in &immutable_host_blocks {
            offload_manager.offload(block, 0).await?;
        }

        tokio::time::sleep(std::time::Duration::from_millis(500)).await;

        let mut disk_blocks = Vec::new();

1353
        for (i, host_block) in immutable_host_blocks.iter().enumerate() {
1354
            let blocks = disk_pool
Ryan Olson's avatar
Ryan Olson committed
1355
                .match_sequence_hashes(vec![host_block.sequence_hash()].as_slice())
1356
1357
                .await?;
            assert_eq!(blocks.len(), 1);
1358
            check_block_contents(host_block, &blocks[0], i as u8)?;
1359
1360
1361
            disk_blocks.push(blocks[0].clone());
        }

Ryan Olson's avatar
Ryan Olson committed
1362
        let device_blocks = offload_manager.onboard(disk_blocks.clone(), None).await??;
1363
1364
        assert_eq!(device_blocks.len(), disk_blocks.len());

1365
        for (i, disk_block) in disk_blocks.iter().enumerate() {
1366
            let blocks = device_pool
Ryan Olson's avatar
Ryan Olson committed
1367
                .match_sequence_hashes(vec![disk_block.sequence_hash()].as_slice())
1368
1369
                .await?;
            assert_eq!(blocks.len(), 1);
1370
            check_block_contents(disk_block, &blocks[0], i as u8)?;
1371
1372
1373
1374
        }

        Ok(())
    }
1375
1376
1377
1378
1379
1380
1381

    #[tokio::test]
    async fn test_transfer_batcher() -> Result<()> {
        let (offload_manager, device_pool, _, disk_pool) = build_pools(
            2 * MAX_TRANSFER_BATCH_SIZE + 1,
            None,
            Some(2 * MAX_TRANSFER_BATCH_SIZE + 1),
1382
            None,
1383
1384
1385
1386
1387
1388
1389
1390
        )?;

        let device_pool = device_pool.as_ref().unwrap();
        let disk_pool = disk_pool.as_ref().unwrap();

        let mut disk_blocks = Vec::new();

        for i in 0..2 * MAX_TRANSFER_BATCH_SIZE + 1 {
1391
1392
1393
            let disk_block = completed_block(disk_pool, [i as u32; 4]).await?;
            populate_block(&disk_block, i as u8)?;
            disk_blocks.push(disk_block);
1394
1395
1396
1397
1398
        }

        let immutable_disk_blocks = disk_pool.register_blocks(disk_blocks).await?;

        let device_blocks = offload_manager
Ryan Olson's avatar
Ryan Olson committed
1399
1400
            .onboard(immutable_disk_blocks.clone(), None)
            .await??;
1401
1402
        assert_eq!(device_blocks.len(), 2 * MAX_TRANSFER_BATCH_SIZE + 1);

1403
        for (i, device_block) in device_blocks.iter().enumerate() {
1404
            let blocks = device_pool
Ryan Olson's avatar
Ryan Olson committed
1405
                .match_sequence_hashes(vec![device_block.sequence_hash()].as_slice())
1406
                .await?;
1407
            check_block_contents(device_block, &blocks[0], i as u8)?;
1408
1409
1410
1411
1412
            assert_eq!(blocks.len(), 1);
        }

        Ok(())
    }
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428

    #[tokio::test]
    async fn test_onboard_unsupported_block_type() -> Result<()> {
        let (offload_manager, device_pool, _, _) = build_pools(1, None, None, None)?;

        let device_pool = device_pool.as_ref().unwrap();

        let block = completed_block(device_pool, [0; 4]).await?;

        let registered_block = device_pool
            .register_blocks(vec![block])
            .await?
            .into_iter()
            .next()
            .unwrap();

Ryan Olson's avatar
Ryan Olson committed
1429
1430
1431
        let onboarded_blocks = offload_manager
            .onboard(vec![registered_block], None)
            .await?;
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
        assert!(matches!(
            onboarded_blocks,
            Err(BlockPoolError::BlockError(BlockError::Other(_)))
        ));

        Ok(())
    }

    #[tokio::test]
    async fn test_offload_transfer_metadata() -> Result<()> {
        let (offload_manager, device_pool, host_pool, _) = build_pools(4, Some(4), None, None)?;

        let device_pool = device_pool.as_ref().unwrap();
        let host_pool = host_pool.as_ref().unwrap();

        let mut device_block = completed_block(device_pool, [0; 4]).await?;

        populate_block(&device_block, 42)?;

        let new_metadata = device_block.metadata().update_priority(1);
        device_block.update_metadata(new_metadata);

        let immutable_device_block = device_pool
            .register_blocks(vec![device_block])
            .await?
            .into_iter()
            .next()
            .unwrap();
        offload_manager.offload(&immutable_device_block, 0).await?;

        tokio::time::sleep(std::time::Duration::from_millis(100)).await;

        let host_blocks = host_pool
Ryan Olson's avatar
Ryan Olson committed
1465
            .match_sequence_hashes(vec![immutable_device_block.sequence_hash()].as_slice())
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
            .await?;
        assert_eq!(host_blocks.len(), 1);
        check_block_contents(&immutable_device_block, &host_blocks[0], 42)?;
        assert_eq!(host_blocks[0].metadata().priority(), 1);

        Ok(())
    }

    #[tokio::test]
    async fn test_onboard_duplicate() -> Result<()> {
        let (offload_manager, device_pool, host_pool, _) = build_pools(4, Some(4), None, None)?;

        let device_pool = device_pool.as_ref().unwrap();
        let host_pool = host_pool.as_ref().unwrap();

        let device_block = completed_block(device_pool, [0; 4]).await?;

        let immutable_device_block = device_pool
            .register_blocks(vec![device_block])
            .await?
            .into_iter()
            .next()
            .unwrap();

        populate_block(&immutable_device_block, 42)?;

        offload_manager.offload(&immutable_device_block, 0).await?;

        tokio::time::sleep(std::time::Duration::from_millis(100)).await;

        let host_blocks = host_pool
Ryan Olson's avatar
Ryan Olson committed
1497
            .match_sequence_hashes(vec![immutable_device_block.sequence_hash()].as_slice())
1498
1499
1500
1501
            .await?;
        assert_eq!(host_blocks.len(), 1);

        let onboarded_blocks = offload_manager
Ryan Olson's avatar
Ryan Olson committed
1502
1503
            .onboard(vec![host_blocks[0].clone()], None)
            .await??;
1504
1505
1506
1507
1508
1509
        assert_eq!(onboarded_blocks.len(), 1);
        check_block_contents(&host_blocks[0], &onboarded_blocks[0], 42)?;

        // This should be the same block that we put on the device.
        // The block that was copied should be discarded by the block pool.
        assert_eq!(
Ryan Olson's avatar
Ryan Olson committed
1510
1511
            onboarded_blocks[0].block_id(),
            immutable_device_block.block_id()
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
        );

        Ok(())
    }

    #[tokio::test]
    async fn test_transfer_big_blocks() -> Result<()> {
        // Try a block size of 32 MB.
        let inner_dim = 2_usize.pow(20) * 32 / NUM_LAYERS / BLOCK_SIZE;
        let (offload_manager, device_pool, host_pool, disk_pool) =
            build_pools(2, Some(2), Some(2), Some(inner_dim))?;

        let device_pool = device_pool.as_ref().unwrap();
        let host_pool = host_pool.as_ref().unwrap();
        let disk_pool = disk_pool.as_ref().unwrap();

        let device_block = completed_block(device_pool, [0; 4]).await?;

        populate_block(&device_block, 42)?;

        let immutable_device_block = device_pool
            .register_blocks(vec![device_block])
            .await?
            .into_iter()
            .next()
            .unwrap();

        // Offload to host.
        offload_manager.offload(&immutable_device_block, 0).await?;

        // Wait for the offload to be processed.
        tokio::time::sleep(std::time::Duration::from_millis(100)).await;

        let host_blocks = host_pool
Ryan Olson's avatar
Ryan Olson committed
1546
            .match_sequence_hashes(vec![immutable_device_block.sequence_hash()].as_slice())
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
            .await?;
        assert_eq!(host_blocks.len(), 1);
        check_block_contents(&immutable_device_block, &host_blocks[0], 42)?;

        // Offload to disk
        offload_manager.offload(&host_blocks[0], 0).await?;

        // Wait for the offload to be processed.
        tokio::time::sleep(std::time::Duration::from_millis(500)).await;

        let disk_blocks = disk_pool
Ryan Olson's avatar
Ryan Olson committed
1558
            .match_sequence_hashes(vec![immutable_device_block.sequence_hash()].as_slice())
1559
1560
1561
1562
1563
            .await?;
        assert_eq!(disk_blocks.len(), 1);
        check_block_contents(&host_blocks[0], &disk_blocks[0], 42)?;

        // Onboard to device.
Ryan Olson's avatar
Ryan Olson committed
1564
        let device_blocks = offload_manager.onboard(disk_blocks.clone(), None).await??;
1565
1566
1567
1568
1569
        assert_eq!(device_blocks.len(), 1);
        check_block_contents(&disk_blocks[0], &device_blocks[0], 42)?;

        Ok(())
    }
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606

    #[tokio::test]
    async fn test_offload_evict_order() -> Result<()> {
        let (offload_manager, device_pool, host_pool, _) = build_pools(4, Some(4), None, None)?;

        let device_pool = device_pool.as_ref().unwrap();
        let host_pool = host_pool.as_ref().unwrap();

        let tokens = vec![0_u32; BLOCK_SIZE * 4];
        let token_blocks = TokenBlockSequence::new(Tokens::from(tokens), 4, None);
        assert_eq!(token_blocks.blocks().len(), 4);

        let mut mutable_blocks = Vec::new();
        let mut sequence_hashes = Vec::new();
        for token_block in token_blocks.blocks() {
            let mut mutable_block = device_pool
                .allocate_blocks(1)
                .await?
                .into_iter()
                .next()
                .unwrap();
            mutable_block.apply_token_block(token_block.clone())?;
            sequence_hashes.push(mutable_block.sequence_hash()?);
            mutable_blocks.push(mutable_block);
        }

        let immutable_blocks = device_pool.register_blocks(mutable_blocks).await?;

        for block in &immutable_blocks {
            offload_manager.offload(block, 0).await?;
        }
        // Wait for offloads.
        tokio::time::sleep(std::time::Duration::from_millis(100)).await;

        // Allocate 2 blocks on the host.
        let _host_blocks = host_pool.allocate_blocks(2).await?;

Ryan Olson's avatar
Ryan Olson committed
1607
1608
        // The first two blocks should've been evicted.
        // The last two blocks should still be on the host.
1609
1610
1611
1612
1613
        assert_eq!(
            host_pool
                .match_sequence_hashes(sequence_hashes.as_slice())
                .await?
                .len(),
Ryan Olson's avatar
Ryan Olson committed
1614
            0
1615
1616
1617
1618
        );

        assert_eq!(
            host_pool
Ryan Olson's avatar
Ryan Olson committed
1619
                .match_sequence_hashes(&sequence_hashes[2..])
1620
1621
                .await?
                .len(),
Ryan Olson's avatar
Ryan Olson committed
1622
            2
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
        );

        Ok(())
    }

    #[tokio::test]
    async fn test_onboard_evict_order() -> Result<()> {
        let (offload_manager, device_pool, host_pool, _) = build_pools(4, Some(4), None, None)?;

        let device_pool = device_pool.as_ref().unwrap();
        let host_pool = host_pool.as_ref().unwrap();

        let tokens = vec![0_u32; BLOCK_SIZE * 4];
        let token_blocks = TokenBlockSequence::new(Tokens::from(tokens), 4, None);
        assert_eq!(token_blocks.blocks().len(), 4);

        let mut mutable_blocks = Vec::new();
        let mut sequence_hashes = Vec::new();
        for token_block in token_blocks.blocks() {
            let mut block = host_pool
                .allocate_blocks(1)
                .await?
                .into_iter()
                .next()
                .unwrap();
            block.apply_token_block(token_block.clone())?;

            sequence_hashes.push(block.sequence_hash()?);
            mutable_blocks.push(block);
        }

        let immutable_blocks = host_pool.register_blocks(mutable_blocks).await?;

Ryan Olson's avatar
Ryan Olson committed
1656
        let _ = offload_manager.onboard(immutable_blocks, None).await?;
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683

        tokio::time::sleep(std::time::Duration::from_millis(100)).await;

        let _device_blocks = device_pool.allocate_blocks(2).await?;

        assert_eq!(
            device_pool
                .match_sequence_hashes(sequence_hashes.as_slice())
                .await?
                .len(),
            2
        );

        tokio::time::sleep(std::time::Duration::from_millis(100)).await;

        let _device_blocks2 = device_pool.allocate_blocks(1).await?;

        assert_eq!(
            device_pool
                .match_sequence_hashes(sequence_hashes.as_slice())
                .await?
                .len(),
            1
        );

        Ok(())
    }
1684
}