batch.rs 18.5 KB
Newer Older
Ryan Olson's avatar
Ryan Olson committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

//! Batch collection and accumulation for offload transfers.
//!
//! The batch collector accumulates blocks that pass policy evaluation and
//! groups them into batches for efficient transfer execution.

use std::collections::HashSet;
use std::sync::Arc;
use std::time::{Duration, Instant};

use tokio::sync::{mpsc, watch};
use velo::EventHandle;

use crate::{BlockId, SequenceHash};
use kvbm_logical::blocks::BlockMetadata;

use super::handle::TransferId;
use super::pending::PendingGuard;
use super::queue::CancellableQueue;
use super::source::SourceBlock;

/// Timing trace for tracking block progression through pipeline stages.
///
/// Each block carries a timing trace that records when it passed through
/// each stage. This enables per-container and batch-level timing analysis.
#[derive(Debug, Clone)]
pub struct TimingTrace {
    /// When the block was initially enqueued into the pipeline
    pub enqueued_at: Instant,
    /// When policy evaluation completed for this block
    pub policy_complete_at: Option<Instant>,
    /// When the precondition (e.g., forward pass) completed
    pub precondition_complete_at: Option<Instant>,
    /// When the block was added to a transfer batch
    pub batched_at: Option<Instant>,
    /// When the transfer operation started
    pub transfer_start_at: Option<Instant>,
    /// When the transfer operation completed
    pub transfer_complete_at: Option<Instant>,
}

impl TimingTrace {
    /// Create a new timing trace, recording the current time as enqueue time.
    pub fn new() -> Self {
        Self {
            enqueued_at: Instant::now(),
            policy_complete_at: None,
            precondition_complete_at: None,
            batched_at: None,
            transfer_start_at: None,
            transfer_complete_at: None,
        }
    }

    /// Mark policy evaluation complete.
    pub fn mark_policy_complete(&mut self) {
        self.policy_complete_at = Some(Instant::now());
    }

    /// Mark precondition complete.
    pub fn mark_precondition_complete(&mut self) {
        self.precondition_complete_at = Some(Instant::now());
    }

    /// Mark block as batched.
    pub fn mark_batched(&mut self) {
        self.batched_at = Some(Instant::now());
    }

    /// Mark transfer start.
    pub fn mark_transfer_start(&mut self) {
        self.transfer_start_at = Some(Instant::now());
    }

    /// Mark transfer complete.
    pub fn mark_transfer_complete(&mut self) {
        self.transfer_complete_at = Some(Instant::now());
    }

    /// Get total time from enqueue to transfer complete (if available).
    pub fn total_duration(&self) -> Option<Duration> {
        self.transfer_complete_at
            .map(|end| end.duration_since(self.enqueued_at))
    }

    /// Get policy evaluation duration (if available).
    pub fn policy_duration(&self) -> Option<Duration> {
        self.policy_complete_at
            .map(|end| end.duration_since(self.enqueued_at))
    }

    /// Get precondition wait duration (if available).
    pub fn precondition_duration(&self) -> Option<Duration> {
        match (self.policy_complete_at, self.precondition_complete_at) {
            (Some(start), Some(end)) => Some(end.duration_since(start)),
            _ => None,
        }
    }

    /// Get transfer duration (if available).
    pub fn transfer_duration(&self) -> Option<Duration> {
        match (self.transfer_start_at, self.transfer_complete_at) {
            (Some(start), Some(end)) => Some(end.duration_since(start)),
            _ => None,
        }
    }
}

impl Default for TimingTrace {
    fn default() -> Self {
        Self::new()
    }
}

/// Configuration for batch collection.
#[derive(Debug, Clone)]
pub struct BatchConfig {
    /// Maximum blocks per batch
    pub max_batch_size: usize,
    /// Time to wait before flushing a partial batch
    pub flush_interval: Duration,
    /// Minimum batch size before flush (unless timeout)
    pub min_batch_size: usize,
}

impl Default for BatchConfig {
    fn default() -> Self {
        Self {
            max_batch_size: 1024,
            flush_interval: Duration::from_millis(10),
            min_batch_size: 8,
        }
    }
}

impl BatchConfig {
    /// Create a new batch config with specified max size.
    pub fn with_max_size(mut self, size: usize) -> Self {
        self.max_batch_size = size;
        self
    }

    /// Set the flush interval.
    pub fn with_flush_interval(mut self, interval: Duration) -> Self {
        self.flush_interval = interval;
        self
    }

    /// Set the minimum batch size.
    pub fn with_min_size(mut self, size: usize) -> Self {
        self.min_batch_size = size;
        self
    }
}

/// A block that passed policy evaluation and is queued for transfer.
#[allow(dead_code)]
pub struct QueuedBlock<T: BlockMetadata> {
    /// Transfer ID this block belongs to
    pub transfer_id: TransferId,
    /// Block ID - Some for External/Strong, None for Weak (determined at upgrade)
    pub block_id: Option<BlockId>,
    /// Sequence hash
    pub sequence_hash: SequenceHash,
    /// Source block - Strong/External pass through, Weak upgraded just before transfer
    pub source: SourceBlock<T>,
    /// Transfer state for completion tracking
    pub(crate) state: Arc<std::sync::Mutex<TransferState>>,
    /// RAII guard that removes this block from pending set on drop.
    ///
    /// This ensures duplicate prevention tracking is automatically cleaned up
    /// when the block completes transfer, is cancelled, or errors out.
    pub pending_guard: Option<PendingGuard>,
}

impl<T: BlockMetadata> std::fmt::Debug for QueuedBlock<T> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("QueuedBlock")
            .field("transfer_id", &self.transfer_id)
            .field("block_id", &self.block_id)
            .field("sequence_hash", &self.sequence_hash)
            .finish()
    }
}

/// A batch of blocks ready for transfer execution.
pub struct TransferBatch<T: BlockMetadata> {
    /// Blocks in this batch
    pub blocks: Vec<QueuedBlock<T>>,
    /// Optional precondition event that must be satisfied before processing.
    /// If Some, the pipeline will await this event before executing the transfer.
    pub precondition: Option<EventHandle>,
    /// Timing trace for performance monitoring (batch-level, not per-block).
    pub timing: TimingTrace,
}

impl<T: BlockMetadata> TransferBatch<T> {
    /// Create a new empty batch.
    pub fn new() -> Self {
        Self {
            blocks: Vec::new(),
            precondition: None,
            timing: TimingTrace::new(),
        }
    }

    /// Create with pre-allocated capacity.
    pub fn with_capacity(capacity: usize) -> Self {
        Self {
            blocks: Vec::with_capacity(capacity),
            precondition: None,
            timing: TimingTrace::new(),
        }
    }

    /// Set the precondition event for this batch.
    #[allow(dead_code)]
    pub fn with_precondition(mut self, precondition: EventHandle) -> Self {
        self.precondition = Some(precondition);
        self
    }

    /// Add a block to this batch.
    pub fn push(&mut self, block: QueuedBlock<T>) {
        self.blocks.push(block);
    }

    /// Get the number of blocks in this batch.
    pub fn len(&self) -> usize {
        self.blocks.len()
    }

    /// Check if batch is empty.
    pub fn is_empty(&self) -> bool {
        self.blocks.is_empty()
    }

    /// Get block IDs in this batch (only for blocks with known IDs).
    ///
    /// Weak blocks may have `None` for block_id until upgraded.
    /// The TransferExecutor resolves actual block_ids at transfer time.
    #[allow(dead_code)]
    pub fn block_ids(&self) -> Vec<BlockId> {
        self.blocks.iter().filter_map(|b| b.block_id).collect()
    }

    /// Get sequence hashes in this batch.
    #[allow(dead_code)]
    pub fn sequence_hashes(&self) -> Vec<SequenceHash> {
        self.blocks.iter().map(|b| b.sequence_hash).collect()
    }

    /// Get unique transfer IDs in this batch.
    #[allow(dead_code)]
    pub fn transfer_ids(&self) -> Vec<TransferId> {
        let mut ids: Vec<TransferId> = self.blocks.iter().map(|b| b.transfer_id).collect();
        ids.sort_by_key(|id| id.as_uuid());
        ids.dedup();
        ids
    }

    /// Take all blocks out of this batch.
    #[allow(dead_code)]
    pub fn take(&mut self) -> Vec<QueuedBlock<T>> {
        std::mem::take(&mut self.blocks)
    }

    /// Drain blocks for the given transfer ID (for cancellation).
    #[allow(dead_code)]
    pub fn drain_transfer(&mut self, transfer_id: TransferId) -> Vec<QueuedBlock<T>> {
        let mut kept = Vec::new();
        let mut drained = Vec::new();
        for block in std::mem::take(&mut self.blocks) {
            if block.transfer_id == transfer_id {
                drained.push(block);
            } else {
                kept.push(block);
            }
        }
        self.blocks = kept;
        drained
    }
}

impl<T: BlockMetadata> Default for TransferBatch<T> {
    fn default() -> Self {
        Self::new()
    }
}

use super::handle::TransferState;

/// Result of policy evaluation - blocks ready for batching.
#[allow(dead_code)]
pub struct EvalResult<T: BlockMetadata> {
    /// Transfer ID
    pub transfer_id: TransferId,
    /// Blocks that passed all policies
    pub passed_blocks: Vec<QueuedBlock<T>>,
    /// Block IDs that were filtered out
    pub filtered_ids: Vec<BlockId>,
    /// Transfer state for completion tracking
    pub(crate) state: Arc<std::sync::Mutex<TransferState>>,
}

/// Output from the batch collector to transfer executor.
pub type BatchOutput<T> = mpsc::Sender<TransferBatch<T>>;
/// Receiver side of batch output channel.
pub type BatchOutputRx<T> = mpsc::Receiver<TransferBatch<T>>;

/// Extract the common precondition from a batch of blocks.
///
/// If all blocks share the same precondition, returns it.
/// Otherwise returns `None`.
fn extract_common_precondition<T: BlockMetadata>(blocks: &[QueuedBlock<T>]) -> Option<EventHandle> {
    blocks.first().and_then(|first_block| {
        let first_precondition = first_block.state.lock().unwrap().precondition;
        let all_same = blocks
            .iter()
            .all(|block| block.state.lock().unwrap().precondition == first_precondition);
        if all_same { first_precondition } else { None }
    })
}

/// Batch collector that accumulates blocks and flushes batches.
///
/// The collector accumulates blocks from policy evaluation (via `CancellableQueue`)
/// and groups them into batches based on the configuration. Batches are flushed when:
/// - `max_batch_size` is reached
/// - `flush_interval` expires and `min_batch_size` is met
/// - Shutdown is requested
pub struct BatchCollector<T: BlockMetadata> {
    config: BatchConfig,
    /// Input queue from policy evaluator
    input_queue: Arc<CancellableQueue<EvalResult<T>>>,
    /// Output channel to transfer executor
    output_tx: BatchOutput<T>,
    /// Cancel watch receiver
    cancel_rx: watch::Receiver<HashSet<TransferId>>,
    /// Current batch being built
    current_batch: TransferBatch<T>,
}

impl<T: BlockMetadata> BatchCollector<T> {
    /// Create a new batch collector.
    pub fn new(
        config: BatchConfig,
        input_queue: Arc<CancellableQueue<EvalResult<T>>>,
        output_tx: BatchOutput<T>,
        cancel_rx: watch::Receiver<HashSet<TransferId>>,
    ) -> Self {
        let max_batch_size = config.max_batch_size;
        Self {
            config,
            input_queue,
            output_tx,
            cancel_rx,
            current_batch: TransferBatch::with_capacity(max_batch_size),
        }
    }

    /// Run the batch collector loop.
    pub async fn run(mut self) {
        let mut flush_timer = tokio::time::interval(self.config.flush_interval);
        flush_timer.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);

        let mut poll_interval = tokio::time::interval(Duration::from_micros(100));
        poll_interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);

        loop {
            tokio::select! {
                // Poll queue for items
                _ = poll_interval.tick() => {
                    while let Some(item) = self.input_queue.pop_valid() {
                        self.handle_eval_result(item.data).await;
                    }
                }
                // Periodic flush timer
                _ = flush_timer.tick() => {
                    self.try_flush().await;
                }
                // Check for shutdown
                result = self.cancel_rx.changed() => {
                    if result.is_err() {
                        // Channel closed, flush and exit
                        self.flush_if_not_empty().await;
                        break;
                    }
                }
            }
        }
    }

    /// Handle an evaluation result.
    ///
    /// Adds passed blocks to the current batch and flushes when:
    /// - max_batch_size is reached, OR
    /// - all blocks for a transfer have been processed (per-transfer sentinel flush)
    async fn handle_eval_result(&mut self, result: EvalResult<T>) {
        // Count blocks processed in this eval result (both passed and filtered)
        let blocks_in_eval = result.passed_blocks.len() + result.filtered_ids.len();

        // Add passed blocks to current batch
        for block in result.passed_blocks {
            self.current_batch.push(block);

            // Flush if we've reached max batch size
            if self.current_batch.len() >= self.config.max_batch_size {
                self.flush().await;
            }
        }

        // Update transfer state and check if transfer is complete (sentinel flush)
        let should_flush = {
            let mut state = result.state.lock().unwrap();
            state.blocks_processed += blocks_in_eval;
            // Flush when all blocks for this transfer have been processed
            state.blocks_processed >= state.total_expected_blocks && state.total_expected_blocks > 0
        };

        // Flush immediately when a transfer completes to avoid waiting for min_batch_size
        if should_flush && !self.current_batch.is_empty() {
            tracing::debug!(
                transfer_id = %result.transfer_id,
                batch_size = self.current_batch.len(),
                "Per-transfer sentinel flush"
            );
            self.flush().await;
        }
    }

    /// Try to flush if minimum batch size is reached.
    async fn try_flush(&mut self) {
        if self.current_batch.len() >= self.config.min_batch_size {
            self.flush().await;
        }
    }

    /// Flush current batch if not empty.
    async fn flush_if_not_empty(&mut self) {
        if !self.current_batch.is_empty() {
            self.flush().await;
        }
    }

    /// Flush the current batch to the output channel.
    async fn flush(&mut self) {
        nvtx_range!("offload::batch");
        if self.current_batch.is_empty() {
            return;
        }

        let mut batch = std::mem::replace(
            &mut self.current_batch,
            TransferBatch::with_capacity(self.config.max_batch_size),
        );

        // Mark batch as ready (single O(1) call, not per-block)
        batch.timing.mark_batched();

        batch.precondition = extract_common_precondition(&batch.blocks);

        // Send to transfer executor
        if self.output_tx.send(batch).await.is_err() {
            // Output channel closed, log and continue
            tracing::warn!("Batch output channel closed");
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_batch_config_default() {
        let config = BatchConfig::default();
        assert_eq!(config.max_batch_size, 1024);
        assert_eq!(config.min_batch_size, 8);
    }

    #[test]
    fn test_batch_config_builder() {
        let config = BatchConfig::default()
            .with_max_size(128)
            .with_min_size(16)
            .with_flush_interval(Duration::from_millis(50));

        assert_eq!(config.max_batch_size, 128);
        assert_eq!(config.min_batch_size, 16);
        assert_eq!(config.flush_interval, Duration::from_millis(50));
    }

    #[test]
    fn test_transfer_batch() {
        let batch: TransferBatch<()> = TransferBatch::new();
        assert!(batch.is_empty());
        assert_eq!(batch.len(), 0);
    }

    #[tokio::test]
    async fn test_batch_collector_empty_input() {
        let input_queue = Arc::new(CancellableQueue::<EvalResult<()>>::new());
        let (output_tx, mut output_rx) = mpsc::channel::<TransferBatch<()>>(10);
        let (cancel_tx, cancel_rx) = watch::channel(HashSet::new());

        let collector =
            BatchCollector::new(BatchConfig::default(), input_queue, output_tx, cancel_rx);

        // Drop cancel sender to close channel (triggers shutdown)
        drop(cancel_tx);

        // Run collector
        tokio::spawn(async move {
            collector.run().await;
        });

        // Should receive nothing (empty input)
        let result = tokio::time::timeout(Duration::from_millis(50), output_rx.recv()).await;
        assert!(result.is_err() || result.unwrap().is_none());
    }

    #[test]
    fn test_transfer_batch_with_capacity() {
        let batch: TransferBatch<()> = TransferBatch::with_capacity(128);
        assert!(batch.is_empty());
        assert_eq!(batch.len(), 0);
    }

    #[test]
    fn test_batch_config_with_methods() {
        let config = BatchConfig::default()
            .with_max_size(256)
            .with_min_size(32)
            .with_flush_interval(Duration::from_millis(100));

        assert_eq!(config.max_batch_size, 256);
        assert_eq!(config.min_batch_size, 32);
        assert_eq!(config.flush_interval, Duration::from_millis(100));
    }

    #[test]
    fn test_transfer_batch_methods() {
        let mut batch: TransferBatch<()> = TransferBatch::new();

        // Note: We can't easily create QueuedBlock without the full pipeline setup,
        // so this test just verifies the batch structure methods work on empty batches
        assert!(batch.block_ids().is_empty());
        assert!(batch.sequence_hashes().is_empty());
        assert!(batch.transfer_ids().is_empty());

        // Verify take() works
        let taken = batch.take();
        assert!(taken.is_empty());
        assert!(batch.is_empty());
    }

    #[test]
    fn test_batch_precondition() {
        let batch: TransferBatch<()> = TransferBatch::new();
        assert!(batch.precondition.is_none());

        // Note: with_precondition requires an EventHandle which is complex to create
        // in a unit test, so we just verify the field exists and is None by default
    }
}