"vscode:/vscode.git/clone" did not exist on "717fc00e98c18d183f9141393b4185ddfb6606b3"
object_flow.rs 21.1 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
// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

//! End-to-end test for G2->G4 (object storage) offload flow with distributed locking.
//!
//! This test demonstrates:
//! - Using the locking mechanism (.lock/.meta files) for distributed coordination
//! - Verifying lock acquisition and release
//! - Verifying meta file creation marks blocks as offloaded
//! - Verifying re-offload is skipped for blocks that already have meta files
//!
//! Note: Uses a mock in-memory object storage implementation for testing without
//! requiring a real S3/MinIO backend.

#[cfg(test)]
mod tests {
    use std::collections::HashMap;
    use std::sync::{Arc, RwLock};
    use std::time::{SystemTime, UNIX_EPOCH};

    use anyhow::Result;
    use bytes::Bytes;
    use futures::future::BoxFuture;

    use crate::LogicalLayoutHandle;
    use crate::object::{LockFileContent, ObjectBlockOps, ObjectLockManager};
    use crate::offload::{
        BoxFuture as PolicyBoxFuture, EvalContext, ObjectLockPresenceFilter, OffloadPolicy,
        PendingTracker,
    };
    use crate::{BlockId, G2, SequenceHash};

    /// Create a test sequence hash from a simple integer.
    fn test_hash(n: u64) -> SequenceHash {
        SequenceHash::new(n, None, 0)
    }

    /// Get current time as seconds since epoch
    fn now_secs() -> u64 {
        SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap()
            .as_secs()
    }

    /// Format timestamp as RFC3339-like string
    fn timestamp_to_string(secs: u64) -> String {
        format!("{}", secs)
    }

    /// Parse timestamp from string
    fn parse_timestamp(s: &str) -> Option<u64> {
        s.parse().ok()
    }

    /// Check if deadline timestamp is expired
    fn is_expired_timestamp(deadline_str: &str) -> bool {
        if let Some(deadline) = parse_timestamp(deadline_str) {
            now_secs() > deadline
        } else {
            true // Can't parse = treat as expired
        }
    }

    // =========================================================================
    // Mock Object Storage Implementation
    // =========================================================================

    /// In-memory mock object storage for testing.
    #[derive(Debug, Default)]
    struct MockObjectStorage {
        objects: RwLock<HashMap<String, Bytes>>,
    }

    impl MockObjectStorage {
        fn new() -> Self {
            Self {
                objects: RwLock::new(HashMap::new()),
            }
        }

        fn has_object(&self, key: &str) -> bool {
            self.objects.read().unwrap().contains_key(key)
        }

        fn get_object(&self, key: &str) -> Option<Bytes> {
            self.objects.read().unwrap().get(key).cloned()
        }

        fn put_object(&self, key: &str, data: Bytes) {
            self.objects.write().unwrap().insert(key.to_string(), data);
        }

        fn delete_object(&self, key: &str) -> bool {
            self.objects.write().unwrap().remove(key).is_some()
        }

        fn put_if_not_exists(&self, key: &str, data: Bytes) -> bool {
            let mut objects = self.objects.write().unwrap();
            if objects.contains_key(key) {
                false
            } else {
                objects.insert(key.to_string(), data);
                true
            }
        }

        #[allow(dead_code)]
        fn list_keys(&self) -> Vec<String> {
            self.objects.read().unwrap().keys().cloned().collect()
        }
    }

    /// Mock ObjectBlockOps implementation using in-memory storage.
    #[allow(dead_code)]
    struct MockObjectBlockClient {
        storage: Arc<MockObjectStorage>,
    }

    #[allow(dead_code)]
    impl MockObjectBlockClient {
        fn new(storage: Arc<MockObjectStorage>) -> Self {
            Self { storage }
        }
    }

    impl ObjectBlockOps for MockObjectBlockClient {
        fn has_blocks(
            &self,
            keys: Vec<SequenceHash>,
        ) -> BoxFuture<'static, Vec<(SequenceHash, Option<usize>)>> {
            let storage = self.storage.clone();
            Box::pin(async move {
                keys.into_iter()
                    .map(|hash| {
                        let key = format!("{:?}", hash);
                        let size = storage.get_object(&key).map(|b| b.len());
                        (hash, size)
                    })
                    .collect()
            })
        }

        fn put_blocks(
            &self,
            keys: Vec<SequenceHash>,
            _layout: LogicalLayoutHandle,
            _block_ids: Vec<BlockId>,
        ) -> BoxFuture<'static, Vec<Result<SequenceHash, SequenceHash>>> {
            let storage = self.storage.clone();
            Box::pin(async move {
                keys.into_iter()
                    .map(|hash| {
                        let key = format!("{:?}", hash);
                        storage.put_object(&key, Bytes::from("mock_block_data"));
                        Ok(hash)
                    })
                    .collect()
            })
        }

        fn get_blocks(
            &self,
            keys: Vec<SequenceHash>,
            _layout: LogicalLayoutHandle,
            _block_ids: Vec<BlockId>,
        ) -> BoxFuture<'static, Vec<Result<SequenceHash, SequenceHash>>> {
            let storage = self.storage.clone();
            Box::pin(async move {
                keys.into_iter()
                    .map(|hash| {
                        let key = format!("{:?}", hash);
                        if storage.has_object(&key) {
                            Ok(hash)
                        } else {
                            Err(hash)
                        }
                    })
                    .collect()
            })
        }
    }

    /// Mock ObjectLockManager implementation using in-memory storage.
    struct MockLockManager {
        storage: Arc<MockObjectStorage>,
        instance_id: String,
        lock_timeout_secs: u64,
    }

    impl MockLockManager {
        fn new(storage: Arc<MockObjectStorage>, instance_id: String) -> Self {
            Self {
                storage,
                instance_id,
                lock_timeout_secs: 300,
            }
        }

        fn lock_key(hash: &SequenceHash) -> String {
            format!("{:?}.lock", hash)
        }

        fn meta_key(hash: &SequenceHash) -> String {
            format!("{:?}.meta", hash)
        }

        fn create_lock_content(&self) -> LockFileContent {
            LockFileContent {
                instance_id: self.instance_id.clone(),
                acquired_at: timestamp_to_string(now_secs()),
                deadline: timestamp_to_string(now_secs() + self.lock_timeout_secs),
            }
        }
    }

    impl ObjectLockManager for MockLockManager {
        fn has_meta(&self, hash: SequenceHash) -> PolicyBoxFuture<'static, Result<bool>> {
            let storage = self.storage.clone();
            Box::pin(async move {
                let meta_key = Self::meta_key(&hash);
                Ok(storage.has_object(&meta_key))
            })
        }

        fn try_acquire_lock(&self, hash: SequenceHash) -> PolicyBoxFuture<'static, Result<bool>> {
            let storage = self.storage.clone();
            let lock_content = self.create_lock_content();
            let our_instance_id = self.instance_id.clone();

            Box::pin(async move {
                let lock_key = Self::lock_key(&hash);
                let lock_data =
                    serde_json::to_vec(&lock_content).expect("Failed to serialize lock content");

                // Try conditional put
                if storage.put_if_not_exists(&lock_key, Bytes::from(lock_data.clone())) {
                    return Ok(true); // Acquired lock
                }

                // Lock exists, check if we own it or if it's expired
                if let Some(existing_data) = storage.get_object(&lock_key)
                    && let Ok(existing_lock) =
                        serde_json::from_slice::<LockFileContent>(&existing_data)
                {
                    // Check if we own the lock
                    if existing_lock.instance_id == our_instance_id {
                        return Ok(true);
                    }

                    // Check if expired
                    if is_expired_timestamp(&existing_lock.deadline) {
                        // Expired, overwrite
                        storage.put_object(&lock_key, Bytes::from(lock_data));
                        return Ok(true);
                    }
                }

                Ok(false) // Lock held by another instance
            })
        }

        fn create_meta(&self, hash: SequenceHash) -> PolicyBoxFuture<'static, Result<()>> {
            let storage = self.storage.clone();
            Box::pin(async move {
                let meta_key = Self::meta_key(&hash);
                storage.put_object(&meta_key, Bytes::new());
                Ok(())
            })
        }

        fn release_lock(&self, hash: SequenceHash) -> PolicyBoxFuture<'static, Result<()>> {
            let storage = self.storage.clone();
            Box::pin(async move {
                let lock_key = Self::lock_key(&hash);
                storage.delete_object(&lock_key);
                Ok(())
            })
        }
    }

    // =========================================================================
    // Lock Manager Tests
    // =========================================================================

    /// Test basic lock acquisition and release.
    #[tokio::test]
    async fn test_lock_manager_acquire_and_release() -> Result<()> {
        let storage = Arc::new(MockObjectStorage::new());
        let lock_manager = MockLockManager::new(storage.clone(), "test-instance".to_string());

        let hash = test_hash(12345);

        // Initially no lock or meta
        assert!(!storage.has_object(&MockLockManager::lock_key(&hash)));
        assert!(!storage.has_object(&MockLockManager::meta_key(&hash)));

        // Acquire lock
        let acquired = lock_manager.try_acquire_lock(hash).await?;
        assert!(acquired, "Should acquire lock");
        assert!(storage.has_object(&MockLockManager::lock_key(&hash)));

        // Verify lock content
        let lock_data = storage
            .get_object(&MockLockManager::lock_key(&hash))
            .unwrap();
        let lock_content: LockFileContent = serde_json::from_slice(&lock_data)?;
        assert_eq!(lock_content.instance_id, "test-instance");

        // Create meta
        lock_manager.create_meta(hash).await?;
        assert!(storage.has_object(&MockLockManager::meta_key(&hash)));

        // Release lock
        lock_manager.release_lock(hash).await?;
        assert!(!storage.has_object(&MockLockManager::lock_key(&hash)));

        // Meta should still exist
        assert!(storage.has_object(&MockLockManager::meta_key(&hash)));

        eprintln!("✓ Lock acquisition and release test passed");
        Ok(())
    }

    /// Test that same instance can re-acquire its own lock.
    #[tokio::test]
    async fn test_lock_manager_reacquire_own_lock() -> Result<()> {
        let storage = Arc::new(MockObjectStorage::new());
        let lock_manager = MockLockManager::new(storage.clone(), "test-instance".to_string());

        let hash = test_hash(12345);

        // Acquire lock
        let acquired1 = lock_manager.try_acquire_lock(hash).await?;
        assert!(acquired1, "Should acquire lock first time");

        // Re-acquire same lock (same instance)
        let acquired2 = lock_manager.try_acquire_lock(hash).await?;
        assert!(
            acquired2,
            "Same instance should be able to re-acquire its lock"
        );

        eprintln!("✓ Lock re-acquisition test passed");
        Ok(())
    }

    /// Test that different instance cannot acquire a valid lock.
    #[tokio::test]
    async fn test_lock_manager_contention() -> Result<()> {
        let storage = Arc::new(MockObjectStorage::new());
        let lock_manager1 = MockLockManager::new(storage.clone(), "instance-1".to_string());
        let lock_manager2 = MockLockManager::new(storage.clone(), "instance-2".to_string());

        let hash = test_hash(12345);

        // Instance 1 acquires lock
        let acquired1 = lock_manager1.try_acquire_lock(hash).await?;
        assert!(acquired1, "Instance 1 should acquire lock");

        // Instance 2 tries to acquire same lock
        let acquired2 = lock_manager2.try_acquire_lock(hash).await?;
        assert!(
            !acquired2,
            "Instance 2 should NOT acquire lock held by instance 1"
        );

        // Instance 1 can still re-acquire its own lock
        let acquired1_again = lock_manager1.try_acquire_lock(hash).await?;
        assert!(acquired1_again, "Instance 1 should re-acquire its own lock");

        eprintln!("✓ Lock contention test passed");
        Ok(())
    }

    /// Test that expired locks can be overwritten.
    #[tokio::test]
    async fn test_lock_manager_expired_lock_overwrite() -> Result<()> {
        let storage = Arc::new(MockObjectStorage::new());
        let lock_manager = MockLockManager::new(storage.clone(), "new-instance".to_string());

        let hash = test_hash(12345);

        // Pre-populate an expired lock from another instance
        let expired_lock = LockFileContent {
            instance_id: "old-instance".to_string(),
            acquired_at: timestamp_to_string(0), // Ancient time
            deadline: timestamp_to_string(1),    // Long expired
        };
        let lock_key = MockLockManager::lock_key(&hash);
        storage.put_object(&lock_key, Bytes::from(serde_json::to_vec(&expired_lock)?));

        // New instance should be able to overwrite expired lock
        let acquired = lock_manager.try_acquire_lock(hash).await?;
        assert!(acquired, "Should acquire expired lock");

        // Verify new instance owns the lock
        let lock_data = storage.get_object(&lock_key).unwrap();
        let lock_content: LockFileContent = serde_json::from_slice(&lock_data)?;
        assert_eq!(lock_content.instance_id, "new-instance");

        eprintln!("✓ Expired lock overwrite test passed");
        Ok(())
    }

    /// Test has_meta checks correctly.
    #[tokio::test]
    async fn test_lock_manager_has_meta() -> Result<()> {
        let storage = Arc::new(MockObjectStorage::new());
        let lock_manager = MockLockManager::new(storage.clone(), "test-instance".to_string());

        let hash = test_hash(12345);

        // Initially no meta
        let has_meta_before = lock_manager.has_meta(hash).await?;
        assert!(!has_meta_before, "Should not have meta initially");

        // Create meta
        lock_manager.create_meta(hash).await?;

        // Now has meta
        let has_meta_after = lock_manager.has_meta(hash).await?;
        assert!(has_meta_after, "Should have meta after creation");

        eprintln!("✓ Has meta test passed");
        Ok(())
    }

    // =========================================================================
    // Policy Tests
    // =========================================================================

    /// Test ObjectLockPresenceFilter passes blocks without meta/lock.
    #[tokio::test]
    async fn test_policy_passes_new_blocks() -> Result<()> {
        let storage = Arc::new(MockObjectStorage::new());
        let lock_manager: Arc<dyn ObjectLockManager> = Arc::new(MockLockManager::new(
            storage.clone(),
            "test-instance".to_string(),
        ));
        let filter = ObjectLockPresenceFilter::<G2>::new(lock_manager);

        let hash = test_hash(12345);
        let ctx = EvalContext::<G2>::from_weak(BlockId::default(), hash);

        // Evaluate policy
        let result = match filter.evaluate(&ctx) {
            futures::future::Either::Left(ready) => ready.await,
            futures::future::Either::Right(boxed) => boxed.await,
        };

        assert!(result?, "Policy should pass for new block");

        // Lock should be acquired during evaluation
        assert!(storage.has_object(&MockLockManager::lock_key(&hash)));

        eprintln!("✓ Policy passes new blocks test passed");
        Ok(())
    }

    /// Test ObjectLockPresenceFilter filters blocks with existing meta.
    #[tokio::test]
    async fn test_policy_filters_blocks_with_meta() -> Result<()> {
        let storage = Arc::new(MockObjectStorage::new());

        // Pre-populate meta file
        let hash = test_hash(12345);
        let meta_key = MockLockManager::meta_key(&hash);
        storage.put_object(&meta_key, Bytes::new());

        let lock_manager: Arc<dyn ObjectLockManager> = Arc::new(MockLockManager::new(
            storage.clone(),
            "test-instance".to_string(),
        ));
        let filter = ObjectLockPresenceFilter::<G2>::new(lock_manager);

        let ctx = EvalContext::<G2>::from_weak(BlockId::default(), hash);

        // Evaluate policy
        let result = match filter.evaluate(&ctx) {
            futures::future::Either::Left(ready) => ready.await,
            futures::future::Either::Right(boxed) => boxed.await,
        };

        assert!(!result?, "Policy should filter block with existing meta");

        eprintln!("✓ Policy filters blocks with meta test passed");
        Ok(())
    }

    /// Test ObjectLockPresenceFilter filters blocks with valid lock from another instance.
    #[tokio::test]
    async fn test_policy_filters_locked_blocks() -> Result<()> {
        let storage = Arc::new(MockObjectStorage::new());

        // Pre-populate lock from another instance
        let hash = test_hash(12345);
        let lock_content = LockFileContent {
            instance_id: "other-instance".to_string(),
            acquired_at: timestamp_to_string(now_secs()),
            deadline: timestamp_to_string(now_secs() + 300), // 5 min in future
        };
        let lock_key = MockLockManager::lock_key(&hash);
        storage.put_object(&lock_key, Bytes::from(serde_json::to_vec(&lock_content)?));

        let lock_manager: Arc<dyn ObjectLockManager> = Arc::new(MockLockManager::new(
            storage.clone(),
            "test-instance".to_string(),
        ));
        let filter = ObjectLockPresenceFilter::<G2>::new(lock_manager);

        let ctx = EvalContext::<G2>::from_weak(BlockId::default(), hash);

        // Evaluate policy
        let result = match filter.evaluate(&ctx) {
            futures::future::Either::Left(ready) => ready.await,
            futures::future::Either::Right(boxed) => boxed.await,
        };

        assert!(
            !result?,
            "Policy should filter block locked by another instance"
        );

        eprintln!("✓ Policy filters locked blocks test passed");
        Ok(())
    }

    /// Test ObjectLockPresenceFilter with pending tracker.
    #[tokio::test]
    async fn test_policy_filters_pending_blocks() -> Result<()> {
        let storage = Arc::new(MockObjectStorage::new());
        let lock_manager: Arc<dyn ObjectLockManager> = Arc::new(MockLockManager::new(
            storage.clone(),
            "test-instance".to_string(),
        ));

        let pending_tracker = Arc::new(PendingTracker::new());
        let filter = ObjectLockPresenceFilter::<G2>::new(lock_manager)
            .with_pending_tracker(pending_tracker.clone());

        let hash = test_hash(12345);

        // Mark as pending
        let _guard = pending_tracker.guard(hash);

        let ctx = EvalContext::<G2>::from_weak(BlockId::default(), hash);

        // Evaluate policy
        let result = match filter.evaluate(&ctx) {
            futures::future::Either::Left(ready) => ready.await,
            futures::future::Either::Right(boxed) => boxed.await,
        };

        assert!(!result?, "Policy should filter pending block");

        eprintln!("✓ Policy filters pending blocks test passed");
        Ok(())
    }

    /// Test batch evaluation filters correctly.
    #[tokio::test]
    async fn test_policy_batch_evaluation() -> Result<()> {
        let storage = Arc::new(MockObjectStorage::new());

        // Pre-populate meta for some blocks
        let hash1 = test_hash(1);
        let hash2 = test_hash(2);
        let hash3 = test_hash(3);

        storage.put_object(&MockLockManager::meta_key(&hash1), Bytes::new()); // Has meta

        let lock_manager: Arc<dyn ObjectLockManager> = Arc::new(MockLockManager::new(
            storage.clone(),
            "test-instance".to_string(),
        ));
        let filter = ObjectLockPresenceFilter::<G2>::new(lock_manager);

        let contexts = vec![
            EvalContext::<G2>::from_weak(0, hash1), // Has meta - should filter
            EvalContext::<G2>::from_weak(1, hash2), // New - should pass
            EvalContext::<G2>::from_weak(2, hash3), // New - should pass
        ];

        // Evaluate batch
        let result = match filter.evaluate_batch(&contexts) {
            futures::future::Either::Left(ready) => ready.await,
            futures::future::Either::Right(boxed) => boxed.await,
        };

        let results = result?;
        assert_eq!(results.len(), 3);
        assert!(!results[0], "Block with meta should be filtered");
        assert!(results[1], "New block should pass");
        assert!(results[2], "New block should pass");

        eprintln!("✓ Policy batch evaluation test passed");
        Ok(())
    }
}