handle.rs 20.4 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
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

//! SessionHandle: Unified handle for controlling a remote session.
//!
//! This is the unified replacement for `RemoteSessionHandle` that uses the
//! new session model types (`SessionPhase`, `ControlRole`, `SessionStateSnapshot`).
//!
//! Key improvements over RemoteSessionHandle:
//! - Uses unified `SessionPhase` and `ControlRole` enums
//! - Supports bidirectional control transfer (yield/acquire)
//! - Uses `SessionStateSnapshot` for state observation
//! - Same RDMA support via `ParallelWorker`

use anyhow::Result;
use std::sync::Arc;
use tokio::sync::watch;

use crate::worker::group::ParallelWorkers;
use crate::{BlockId, InstanceId, SequenceHash};
use kvbm_common::LogicalLayoutHandle;
use kvbm_physical::transfer::{TransferCompleteNotification, TransferOptions};

use super::{
    BlockInfo, ControlRole, SessionId, SessionMessage, SessionPhase, SessionStateSnapshot,
    transport::MessageTransport,
};

/// Handle for controlling a remote session.
///
/// Created by attaching to a remote session. Provides methods to:
/// - Query and observe session state
/// - Issue control commands (trigger staging, release blocks)
/// - Transfer control bidirectionally (yield/acquire)
/// - Pull blocks via RDMA
///
/// ## Usage
///
/// ```ignore
/// // Attach to remote session
/// let mut handle = leader.attach_session(remote_id, session_id).await?;
///
/// // Wait for initial state
/// let state = handle.wait_for_ready().await?;
///
/// // Trigger staging if needed
/// if state.g3_pending > 0 {
///     handle.trigger_staging().await?;
///     handle.wait_for_ready().await?;
/// }
///
/// // Pull blocks via RDMA
/// let notification = handle.pull_blocks_rdma(&state.g2_blocks, &local_block_ids).await?;
/// notification.await?;
///
/// // Notify remote and detach
/// handle.mark_blocks_pulled(hashes).await?;
/// handle.detach().await?;
/// ```
pub struct SessionHandle {
    session_id: SessionId,
    remote_instance: InstanceId,
    local_instance: InstanceId,
    transport: Arc<MessageTransport>,

    // State observation
    state_rx: watch::Receiver<SessionStateSnapshot>,

    // RDMA transfer support
    parallel_worker: Option<Arc<dyn ParallelWorkers>>,
}

impl SessionHandle {
    /// Create a new session handle.
    ///
    /// Note: Currently unused during incremental migration. Will be used once
    /// existing session implementations are fully migrated to the new model.
    #[allow(dead_code)]
    pub(crate) fn new(
        session_id: SessionId,
        remote_instance: InstanceId,
        local_instance: InstanceId,
        transport: Arc<MessageTransport>,
        state_rx: watch::Receiver<SessionStateSnapshot>,
    ) -> Self {
        Self {
            session_id,
            remote_instance,
            local_instance,
            transport,
            state_rx,
            parallel_worker: None,
        }
    }

    /// Add RDMA support to this handle.
    pub fn with_rdma_support(mut self, parallel_worker: Arc<dyn ParallelWorkers>) -> Self {
        self.parallel_worker = Some(parallel_worker);
        self
    }

    // =========================================================================
    // Identity
    // =========================================================================

    /// Get the session ID.
    pub fn session_id(&self) -> SessionId {
        self.session_id
    }

    /// Get the remote instance ID.
    pub fn remote_instance(&self) -> InstanceId {
        self.remote_instance
    }

    /// Get the local instance ID.
    pub fn local_instance(&self) -> InstanceId {
        self.local_instance
    }

    // =========================================================================
    // State Observation
    // =========================================================================

    /// Get the current state snapshot (non-blocking).
    pub fn current_state(&self) -> SessionStateSnapshot {
        self.state_rx.borrow().clone()
    }

    /// Get the current phase.
    pub fn phase(&self) -> SessionPhase {
        self.state_rx.borrow().phase
    }

    /// Get the current control role of the remote session.
    pub fn remote_control_role(&self) -> ControlRole {
        self.state_rx.borrow().control_role
    }

    /// Check if state has changed since last read.
    pub fn has_changed(&self) -> bool {
        self.state_rx.has_changed().unwrap_or(false)
    }

    /// Wait for state to change.
    pub async fn wait_for_change(&mut self) -> Result<SessionStateSnapshot> {
        self.state_rx
            .changed()
            .await
            .map_err(|e| anyhow::anyhow!("State channel closed: {}", e))?;
        Ok(self.state_rx.borrow().clone())
    }

    /// Wait for the session to reach Ready phase (all blocks in G2).
    pub async fn wait_for_ready(&mut self) -> Result<SessionStateSnapshot> {
        self.state_rx
            .wait_for(|s| s.phase == SessionPhase::Ready || s.phase.is_terminal())
            .await
            .map_err(|e| anyhow::anyhow!("Failed waiting for ready: {}", e))?;

        let state = self.state_rx.borrow().clone();
        if state.phase == SessionPhase::Failed {
            anyhow::bail!("Session failed while waiting for ready");
        }
        Ok(state)
    }

    /// Wait for the session to complete.
    pub async fn wait_for_complete(&mut self) -> Result<SessionStateSnapshot> {
        self.state_rx
            .wait_for(|s| s.phase.is_terminal())
            .await
            .map_err(|e| anyhow::anyhow!("Failed waiting for complete: {}", e))?;
        Ok(self.state_rx.borrow().clone())
    }

    /// Check if the session is complete.
    pub fn is_complete(&self) -> bool {
        self.state_rx.borrow().phase.is_terminal()
    }

    /// Check if the session is ready (all blocks in G2).
    pub fn is_ready(&self) -> bool {
        self.state_rx.borrow().phase == SessionPhase::Ready
    }

    /// Get G2 blocks from current state.
    pub fn get_g2_blocks(&self) -> Vec<BlockInfo> {
        self.state_rx.borrow().g2_blocks.clone()
    }

    /// Get count of G3 blocks pending staging.
    pub fn g3_pending_count(&self) -> usize {
        self.state_rx.borrow().g3_pending
    }

    /// Get the layer range that is ready for transfer.
    ///
    /// Returns `None` if all layers are ready or layerwise tracking is not active.
    /// Returns `Some(range)` if only specific layers are ready.
    pub fn ready_layer_range(&self) -> Option<std::ops::Range<usize>> {
        self.state_rx.borrow().ready_layer_range.clone()
    }

    // =========================================================================
    // Control Commands
    // =========================================================================

    /// Trigger G3→G2 staging on the remote session.
    ///
    /// Idempotent - no-op if already staging or staged.
    pub async fn trigger_staging(&self) -> Result<()> {
        let msg = SessionMessage::TriggerStaging {
            session_id: self.session_id,
        };
        self.transport.send_session(self.remote_instance, msg).await
    }

    /// Notify remote that blocks have been pulled.
    ///
    /// Call after successfully pulling blocks via RDMA.
    pub async fn mark_blocks_pulled(&self, pulled_hashes: Vec<SequenceHash>) -> Result<()> {
        let msg = SessionMessage::BlocksPulled {
            session_id: self.session_id,
            pulled_hashes,
        };
        self.transport.send_session(self.remote_instance, msg).await
    }

    /// Detach from the session.
    ///
    /// Consumes the handle. The remote session will release remaining blocks.
    pub async fn detach(self) -> Result<()> {
        let msg = SessionMessage::Detach {
            peer: self.local_instance,
            session_id: self.session_id,
        };
        self.transport.send_session(self.remote_instance, msg).await
    }

    // =========================================================================
    // Control Transfer (Bidirectional)
    // =========================================================================

    /// Yield control to the remote peer.
    ///
    /// After yielding, this handle transitions to Neutral and the remote
    /// can acquire control if desired.
    pub async fn yield_control(&self) -> Result<()> {
        let msg = SessionMessage::YieldControl {
            peer: self.local_instance,
            session_id: self.session_id,
        };
        self.transport.send_session(self.remote_instance, msg).await
    }

    /// Attempt to acquire control from the remote peer.
    ///
    /// Valid when remote is in Neutral state.
    pub async fn acquire_control(&self) -> Result<()> {
        let msg = SessionMessage::AcquireControl {
            peer: self.local_instance,
            session_id: self.session_id,
        };
        self.transport.send_session(self.remote_instance, msg).await
    }

    // =========================================================================
    // RDMA Transfer Methods
    // =========================================================================

    /// Check if remote metadata has been imported.
    pub fn has_remote_metadata(&self) -> bool {
        self.parallel_worker
            .as_ref()
            .map(|pw| pw.has_remote_metadata(self.remote_instance))
            .unwrap_or(false)
    }

    /// Ensure remote metadata is imported (lazy loading).
    pub async fn ensure_metadata_imported(&mut self) -> Result<()> {
        let parallel_worker = self
            .parallel_worker
            .as_ref()
            .ok_or_else(|| anyhow::anyhow!("RDMA support not configured"))?;

        if parallel_worker.has_remote_metadata(self.remote_instance) {
            return Ok(());
        }

        let remote_metadata = self
            .transport
            .request_metadata(self.remote_instance)
            .await?;

        parallel_worker
            .connect_remote(self.remote_instance, remote_metadata)?
            .await?;

        Ok(())
    }

    /// Pull blocks from remote G2 to local G2 via RDMA.
    ///
    /// This method:
    /// 1. Ensures remote metadata is imported
    /// 2. Executes SPMD-aware transfer (worker N pulls from remote worker N)
    /// 3. Returns notification that completes when all transfers done
    pub async fn pull_blocks_rdma(
        &mut self,
        blocks: &[BlockInfo],
        local_dst_block_ids: &[BlockId],
    ) -> Result<TransferCompleteNotification> {
        self.ensure_metadata_imported().await?;
        self.pull_blocks_rdma_explicit(blocks, local_dst_block_ids)
    }

    /// Pull blocks with explicit metadata pre-import.
    ///
    /// Caller must have already ensured metadata is imported.
    pub fn pull_blocks_rdma_explicit(
        &self,
        blocks: &[BlockInfo],
        local_dst_block_ids: &[BlockId],
    ) -> Result<TransferCompleteNotification> {
        let parallel_worker = self
            .parallel_worker
            .as_ref()
            .ok_or_else(|| anyhow::anyhow!("RDMA support not configured"))?;

        if !parallel_worker.has_remote_metadata(self.remote_instance) {
            anyhow::bail!(
                "Remote metadata not imported for instance {}",
                self.remote_instance
            );
        }

        if blocks.len() != local_dst_block_ids.len() {
            anyhow::bail!(
                "Block count mismatch: source={}, destination={}",
                blocks.len(),
                local_dst_block_ids.len()
            );
        }

        let src_block_ids: Vec<BlockId> = blocks.iter().map(|b| b.block_id).collect();

        parallel_worker.execute_remote_onboard_for_instance(
            self.remote_instance,
            LogicalLayoutHandle::G2,
            src_block_ids,
            LogicalLayoutHandle::G2,
            local_dst_block_ids.to_vec().into(),
            Default::default(),
        )
    }

    /// Pull blocks from remote G2 to local G2 via RDMA with transfer options.
    ///
    /// This method allows specifying transfer options like layer range for
    /// layerwise transfer. Use this when you only want to pull specific layers.
    ///
    /// # Example
    /// ```ignore
    /// // Pull only layer 0
    /// let notification = handle.pull_blocks_rdma_with_options(
    ///     &state.g2_blocks,
    ///     &local_block_ids,
    ///     TransferOptions::builder().layer_range(0..1).build(),
    /// ).await?;
    /// notification.await?;
    /// ```
    pub async fn pull_blocks_rdma_with_options(
        &mut self,
        blocks: &[BlockInfo],
        local_dst_block_ids: &[BlockId],
        options: TransferOptions,
    ) -> Result<TransferCompleteNotification> {
        self.ensure_metadata_imported().await?;
        self.pull_blocks_rdma_with_options_explicit(blocks, local_dst_block_ids, options)
    }

    /// Pull blocks with options and explicit metadata pre-import.
    ///
    /// Caller must have already ensured metadata is imported.
    pub fn pull_blocks_rdma_with_options_explicit(
        &self,
        blocks: &[BlockInfo],
        local_dst_block_ids: &[BlockId],
        options: TransferOptions,
    ) -> Result<TransferCompleteNotification> {
        let parallel_worker = self
            .parallel_worker
            .as_ref()
            .ok_or_else(|| anyhow::anyhow!("RDMA support not configured"))?;

        if !parallel_worker.has_remote_metadata(self.remote_instance) {
            anyhow::bail!(
                "Remote metadata not imported for instance {}",
                self.remote_instance
            );
        }

        if blocks.len() != local_dst_block_ids.len() {
            anyhow::bail!(
                "Block count mismatch: source={}, destination={}",
                blocks.len(),
                local_dst_block_ids.len()
            );
        }

        let src_block_ids: Vec<BlockId> = blocks.iter().map(|b| b.block_id).collect();

        parallel_worker.execute_remote_onboard_for_instance(
            self.remote_instance,
            LogicalLayoutHandle::G2,
            src_block_ids,
            LogicalLayoutHandle::G2,
            local_dst_block_ids.to_vec().into(),
            options,
        )
    }
}

/// Sender for state updates to SessionHandle.
pub struct SessionHandleStateTx {
    tx: watch::Sender<SessionStateSnapshot>,
}

impl SessionHandleStateTx {
    /// Create a new state sender.
    pub fn new(tx: watch::Sender<SessionStateSnapshot>) -> Self {
        Self { tx }
    }

    /// Update state from a full snapshot.
    pub fn update(&self, state: SessionStateSnapshot) {
        let _ = self.tx.send(state);
    }

    /// Update phase only.
    pub fn set_phase(&self, phase: SessionPhase) {
        self.tx.send_modify(|state| {
            state.phase = phase;
        });
    }

    /// Update G2 blocks.
    pub fn set_g2_blocks(&self, blocks: Vec<BlockInfo>) {
        self.tx.send_modify(|state| {
            state.g2_blocks = blocks;
        });
    }

    /// Add newly staged blocks.
    ///
    /// # Arguments
    /// * `staged` - Blocks that have been staged
    /// * `g3_remaining` - Count of G3 blocks still pending
    /// * `layer_range` - Optional layer range that is ready for transfer
    pub fn add_staged_blocks(
        &self,
        staged: Vec<BlockInfo>,
        g3_remaining: usize,
        layer_range: Option<std::ops::Range<usize>>,
    ) {
        self.tx.send_modify(|state| {
            state.g2_blocks.extend(staged);
            state.g3_pending = g3_remaining;
            state.ready_layer_range = layer_range;
            if g3_remaining == 0 && state.ready_layer_range.is_none() {
                // All blocks staged and no layer tracking = fully ready
                state.phase = SessionPhase::Ready;
            }
        });
    }

    /// Set error/failed state.
    pub fn set_failed(&self) {
        self.tx.send_modify(|state| {
            state.phase = SessionPhase::Failed;
        });
    }
}

/// Create a new session handle state channel.
pub fn session_handle_state_channel()
-> (SessionHandleStateTx, watch::Receiver<SessionStateSnapshot>) {
    let initial = SessionStateSnapshot {
        phase: SessionPhase::Searching,
        control_role: ControlRole::Controllee,
        g2_blocks: Vec::new(),
        g3_pending: 0,
        ready_layer_range: None,
    };
    let (tx, rx) = watch::channel(initial);
    (SessionHandleStateTx::new(tx), rx)
}

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

    fn create_test_transport() -> Arc<MessageTransport> {
        Arc::new(MessageTransport::local(
            Arc::new(DashMap::new()),
            Arc::new(DashMap::new()),
        ))
    }

    #[test]
    fn test_session_handle_state_channel() {
        let (tx, rx) = session_handle_state_channel();

        // Initial state
        let state = rx.borrow().clone();
        assert_eq!(state.phase, SessionPhase::Searching);
        assert_eq!(state.control_role, ControlRole::Controllee);
        assert!(state.g2_blocks.is_empty());

        // Update state
        tx.set_phase(SessionPhase::Ready);
        let state = rx.borrow().clone();
        assert_eq!(state.phase, SessionPhase::Ready);
    }

    #[test]
    fn test_session_handle_creation() {
        let (_, rx) = session_handle_state_channel();
        let transport = create_test_transport();
        let session_id = SessionId::new_v4();
        let remote_id = InstanceId::new_v4();
        let local_id = InstanceId::new_v4();

        let handle = SessionHandle::new(session_id, remote_id, local_id, transport, rx);

        assert_eq!(handle.session_id(), session_id);
        assert_eq!(handle.remote_instance(), remote_id);
        assert_eq!(handle.local_instance(), local_id);
        assert_eq!(handle.phase(), SessionPhase::Searching);
        assert!(!handle.is_ready());
        assert!(!handle.is_complete());
        assert!(!handle.has_remote_metadata());
    }

    #[tokio::test]
    async fn test_wait_for_ready() {
        let (tx, rx) = session_handle_state_channel();
        let transport = create_test_transport();
        let session_id = SessionId::new_v4();

        let mut handle = SessionHandle::new(
            session_id,
            InstanceId::new_v4(),
            InstanceId::new_v4(),
            transport,
            rx,
        );

        // Spawn task to update state
        tokio::spawn(async move {
            tokio::time::sleep(tokio::time::Duration::from_millis(10)).await;
            tx.set_phase(SessionPhase::Ready);
        });

        let state = handle.wait_for_ready().await.unwrap();
        assert_eq!(state.phase, SessionPhase::Ready);
    }

    #[test]
    fn test_add_staged_blocks() {
        let (tx, rx) = session_handle_state_channel();

        // Set initial g3 pending
        tx.update(SessionStateSnapshot {
            phase: SessionPhase::Staging,
            control_role: ControlRole::Controllee,
            g2_blocks: Vec::new(),
            g3_pending: 5,
            ready_layer_range: None,
        });

        let state = rx.borrow().clone();
        assert_eq!(state.g3_pending, 5);
        assert!(state.g2_blocks.is_empty());

        // Add staged blocks with remaining = 0
        let block = BlockInfo {
            block_id: 42,
            sequence_hash: crate::SequenceHash::new(1, None, 100),
            layout_handle: kvbm_physical::manager::LayoutHandle::new(0, 1),
        };
        tx.add_staged_blocks(vec![block], 0, None);

        let state = rx.borrow().clone();
        assert_eq!(state.g2_blocks.len(), 1);
        assert_eq!(state.g3_pending, 0);
        // No layer range + g3_remaining == 0 → Ready
        assert_eq!(state.phase, SessionPhase::Ready);
    }

    #[test]
    fn test_set_failed() {
        let (tx, rx) = session_handle_state_channel();

        // Initially Searching
        assert_eq!(rx.borrow().phase, SessionPhase::Searching);

        tx.set_failed();

        assert_eq!(rx.borrow().phase, SessionPhase::Failed);
    }

    #[tokio::test]
    async fn test_wait_for_complete() {
        let (tx, rx) = session_handle_state_channel();
        let transport = create_test_transport();
        let session_id = SessionId::new_v4();

        let mut handle = SessionHandle::new(
            session_id,
            InstanceId::new_v4(),
            InstanceId::new_v4(),
            transport,
            rx,
        );

        tokio::spawn(async move {
            tokio::time::sleep(tokio::time::Duration::from_millis(10)).await;
            tx.set_phase(SessionPhase::Complete);
        });

        let state = handle.wait_for_complete().await.unwrap();
        assert_eq!(state.phase, SessionPhase::Complete);
        assert!(handle.is_complete());
    }
}