ryo-analysis 0.1.0

Code graph and discovery engine for the RYO project
Documentation
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
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
664
665
666
667
668
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
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
//! LockTrackerV2 - VarId-based lock tracking for DataFlowGraphV2.
//!
//! Key improvements over V1:
//! - Uses VarId instead of petgraph::NodeIndex
//! - Integrates seamlessly with DataFlowGraphV2
//! - Same lock tracking semantics

use super::var_id::VarId;
use crate::symbol::SymbolId;
use std::collections::HashMap;

// ============================================================================
// Lock Types (shared vocabulary)
// ============================================================================

/// Type of lock primitive.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum LockType {
    /// std::sync::Mutex
    Mutex,
    /// std::sync::RwLock (read guard)
    RwLockRead,
    /// std::sync::RwLock (write guard)
    RwLockWrite,
    /// std::cell::RefCell (single-threaded)
    RefCell,
    /// std::cell::RefCell (mutable borrow)
    RefCellMut,
    /// parking_lot::Mutex
    ParkingLotMutex,
    /// parking_lot::RwLock
    ParkingLotRwLock,
    /// tokio::sync::Mutex
    TokioMutex,
    /// tokio::sync::RwLock
    TokioRwLock,
}

impl LockType {
    /// Check if this is a read-only lock.
    pub fn is_read_only(&self) -> bool {
        matches!(self, LockType::RwLockRead | LockType::RefCell)
    }

    /// Check if this is a write/exclusive lock.
    pub fn is_exclusive(&self) -> bool {
        !self.is_read_only()
    }
}

/// Kind of field access.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum AccessKind {
    /// Read-only access
    Read,
    /// Write-only access
    Write,
    /// Both read and write access
    ReadWrite,
}

impl AccessKind {
    /// Merge two access kinds.
    pub fn merge(self, other: Self) -> Self {
        match (self, other) {
            (AccessKind::Read, AccessKind::Read) => AccessKind::Read,
            (AccessKind::Write, AccessKind::Write) => AccessKind::Write,
            _ => AccessKind::ReadWrite,
        }
    }
}

/// Suggestion for lock optimization.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum LockSuggestion {
    /// Field can be extracted to atomic type.
    UseAtomic {
        /// Field name.
        field: String,
        /// Current type (if known).
        current_type: Option<String>,
        /// Suggested atomic type.
        suggested_type: String,
        /// Line reference.
        line: u32,
    },

    /// Lock can be split into multiple finer locks.
    SplitLock {
        /// Original lock variable.
        lock_name: String,
        /// Fields that can be split.
        /// (field_name, suggested_wrapper)
        suggested_splits: Vec<(String, String)>,
        /// Line reference.
        line: u32,
    },

    /// Critical section scope can be reduced.
    ReduceScope {
        /// Guard variable name.
        guard_name: String,
        /// Current critical section lines.
        current_span: (u32, u32),
        /// Suggested narrower span.
        suggested_span: (u32, u32),
        /// Reason for suggestion.
        reason: String,
    },

    /// Mutex can be replaced with RwLock.
    UseRwLock {
        /// Lock variable name.
        lock_name: String,
        /// Number of read accesses.
        read_count: usize,
        /// Number of write accesses.
        write_count: usize,
        /// Line reference.
        line: u32,
    },

    /// Lock is held across await point.
    LockAcrossAwait {
        /// Guard variable name.
        guard_name: String,
        /// Lock acquisition line.
        lock_line: u32,
        /// Await point line.
        await_line: u32,
    },

    /// Lock can be removed (data is thread-local).
    RemoveLock {
        /// Lock variable name.
        lock_name: String,
        /// Reason.
        reason: String,
        /// Line reference.
        line: u32,
    },
}

impl LockSuggestion {
    /// Get the severity/priority of this suggestion (higher = more important).
    pub fn severity(&self) -> u8 {
        match self {
            LockSuggestion::LockAcrossAwait { .. } => 10, // Critical for async
            LockSuggestion::UseAtomic { .. } => 8,        // Simple, high impact
            LockSuggestion::SplitLock { .. } => 6,        // Moderate complexity
            LockSuggestion::ReduceScope { .. } => 5,      // Good practice
            LockSuggestion::UseRwLock { .. } => 4,        // Read-heavy optimization
            LockSuggestion::RemoveLock { .. } => 3,       // Rare case
        }
    }

    /// Get a human-readable description.
    pub fn description(&self) -> String {
        match self {
            LockSuggestion::UseAtomic {
                field,
                suggested_type,
                ..
            } => {
                format!("Consider using {} for field '{}'", suggested_type, field)
            }
            LockSuggestion::SplitLock {
                lock_name,
                suggested_splits,
                ..
            } => {
                let fields: Vec<_> = suggested_splits.iter().map(|(f, _)| f.as_str()).collect();
                format!(
                    "Consider splitting lock '{}' for fields: {:?}",
                    lock_name, fields
                )
            }
            LockSuggestion::ReduceScope {
                guard_name, reason, ..
            } => {
                format!("Reduce scope of guard '{}': {}", guard_name, reason)
            }
            LockSuggestion::UseRwLock {
                lock_name,
                read_count,
                write_count,
                ..
            } => {
                format!(
                    "Consider RwLock for '{}' ({} reads, {} writes)",
                    lock_name, read_count, write_count
                )
            }
            LockSuggestion::LockAcrossAwait { guard_name, .. } => {
                format!("Lock '{}' is held across await point", guard_name)
            }
            LockSuggestion::RemoveLock {
                lock_name, reason, ..
            } => {
                format!("Lock '{}' may be unnecessary: {}", lock_name, reason)
            }
        }
    }

    /// Get a short description for the suggestion.
    pub fn short_description(&self) -> String {
        match self {
            LockSuggestion::UseAtomic {
                field,
                suggested_type,
                ..
            } => {
                format!("Use {} for field '{}'", suggested_type, field)
            }
            LockSuggestion::SplitLock {
                lock_name,
                suggested_splits,
                ..
            } => {
                format!(
                    "Split '{}' into {} separate locks",
                    lock_name,
                    suggested_splits.len()
                )
            }
            LockSuggestion::ReduceScope {
                guard_name, reason, ..
            } => {
                format!("Reduce scope of '{}': {}", guard_name, reason)
            }
            LockSuggestion::UseRwLock {
                lock_name,
                read_count,
                write_count,
                ..
            } => {
                format!(
                    "Use RwLock for '{}' ({} reads, {} writes)",
                    lock_name, read_count, write_count
                )
            }
            LockSuggestion::LockAcrossAwait {
                guard_name,
                lock_line,
                await_line,
                ..
            } => {
                format!(
                    "Lock '{}' held across await (lines {}-{})",
                    guard_name, lock_line, await_line
                )
            }
            LockSuggestion::RemoveLock {
                lock_name, reason, ..
            } => {
                format!("Remove unnecessary '{}': {}", lock_name, reason)
            }
        }
    }
}

// ============================================================================
// Lock Acquisition V2
// ============================================================================

/// Represents a lock acquisition point (V2 - uses VarId).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct LockAcquisitionV2 {
    /// The variable representing the lock (e.g., `self.mutex`).
    pub lock_var: VarId,
    /// The variable representing the guard.
    pub guard_var: VarId,
    /// The type of lock.
    pub lock_type: LockType,
    /// Line where the lock is acquired.
    pub line: u32,
    /// Whether this is a try_lock (non-blocking).
    pub is_try: bool,
    /// The name of the lock variable.
    pub lock_name: String,
    /// The name of the guard variable.
    pub guard_name: String,
    /// The function that owns this lock acquisition.
    pub owner_fn: Option<SymbolId>,
}

impl LockAcquisitionV2 {
    /// Create a new lock acquisition.
    pub fn new(
        lock_var: VarId,
        guard_var: VarId,
        lock_type: LockType,
        line: u32,
        lock_name: impl Into<String>,
        guard_name: impl Into<String>,
    ) -> Self {
        Self {
            lock_var,
            guard_var,
            lock_type,
            line,
            is_try: false,
            lock_name: lock_name.into(),
            guard_name: guard_name.into(),
            owner_fn: None,
        }
    }

    /// Set the owning function.
    pub fn with_owner_fn(mut self, owner: SymbolId) -> Self {
        self.owner_fn = Some(owner);
        self
    }

    /// Mark as try_lock.
    pub fn with_try(mut self) -> Self {
        self.is_try = true;
        self
    }
}

// ============================================================================
// Field Access V2
// ============================================================================

/// A field access within a critical section (V2).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FieldAccessV2 {
    /// The name of the field being accessed.
    pub field_name: String,
    /// The kind of access (read/write).
    pub access_kind: AccessKind,
    /// Line where the access occurs.
    pub line: u32,
}

impl FieldAccessV2 {
    /// Create a new field access.
    pub fn new(field_name: impl Into<String>, access_kind: AccessKind, line: u32) -> Self {
        Self {
            field_name: field_name.into(),
            access_kind,
            line,
        }
    }
}

// ============================================================================
// Critical Section V2
// ============================================================================

/// A critical section (V2 - uses VarId).
#[derive(Debug, Clone)]
pub struct CriticalSectionV2 {
    /// The lock acquisition that starts this critical section.
    pub acquisition: LockAcquisitionV2,
    /// Line where the critical section starts.
    pub start_line: u32,
    /// Line where the critical section ends (guard dropped).
    pub end_line: Option<u32>,
    /// Fields accessed within this critical section.
    pub field_accesses: Vec<FieldAccessV2>,
    /// Whether the CS contains expensive operations.
    pub contains_expensive_ops: bool,
    /// Whether the CS contains await points (async issue).
    pub contains_await: bool,
}

impl CriticalSectionV2 {
    /// Create a new critical section.
    pub fn new(acquisition: LockAcquisitionV2) -> Self {
        let start_line = acquisition.line;
        Self {
            acquisition,
            start_line,
            end_line: None,
            field_accesses: Vec::new(),
            contains_expensive_ops: false,
            contains_await: false,
        }
    }

    /// End the critical section at the given line.
    pub fn end_at(&mut self, line: u32) {
        self.end_line = Some(line);
    }

    /// Add a field access.
    pub fn add_field_access(&mut self, access: FieldAccessV2) {
        self.field_accesses.push(access);
    }

    /// Mark as containing expensive operations.
    pub fn mark_expensive(&mut self) {
        self.contains_expensive_ops = true;
    }

    /// Mark as containing await point.
    pub fn mark_await(&mut self) {
        self.contains_await = true;
    }

    /// Get unique fields accessed.
    pub fn unique_fields(&self) -> Vec<&str> {
        let mut fields: Vec<&str> = self
            .field_accesses
            .iter()
            .map(|a| a.field_name.as_str())
            .collect();
        fields.sort();
        fields.dedup();
        fields
    }

    /// Get the merged access kind for a field.
    pub fn field_access_kind(&self, field: &str) -> Option<AccessKind> {
        self.field_accesses
            .iter()
            .filter(|a| a.field_name == field)
            .map(|a| a.access_kind)
            .reduce(|a, b| a.merge(b))
    }

    /// Check if only read accesses occurred.
    pub fn is_read_only(&self) -> bool {
        self.field_accesses
            .iter()
            .all(|a| a.access_kind == AccessKind::Read)
    }

    /// Get the span (number of lines) of this critical section.
    pub fn span(&self) -> Option<u32> {
        self.end_line.map(|end| end.saturating_sub(self.start_line))
    }
}

// ============================================================================
// Lock Tracker V2
// ============================================================================

/// Tracks lock acquisitions and critical sections (V2 - uses VarId).
#[derive(Debug, Clone, Default)]
pub struct LockTrackerV2 {
    /// All lock acquisitions.
    acquisitions: Vec<LockAcquisitionV2>,
    /// Active critical sections (guard_var -> CriticalSection).
    active_sections: HashMap<VarId, CriticalSectionV2>,
    /// Completed critical sections.
    completed_sections: Vec<CriticalSectionV2>,
}

impl LockTrackerV2 {
    /// Create a new lock tracker.
    pub fn new() -> Self {
        Self::default()
    }

    /// Record a lock acquisition.
    pub fn acquire(&mut self, acquisition: LockAcquisitionV2) {
        let guard_var = acquisition.guard_var;
        self.acquisitions.push(acquisition.clone());
        self.active_sections
            .insert(guard_var, CriticalSectionV2::new(acquisition));
    }

    /// Record a field access within a critical section.
    pub fn record_field_access(
        &mut self,
        guard_var: VarId,
        field_name: &str,
        access_kind: AccessKind,
        line: u32,
    ) {
        if let Some(cs) = self.active_sections.get_mut(&guard_var) {
            cs.add_field_access(FieldAccessV2::new(field_name, access_kind, line));
        }
    }

    /// Mark a critical section as containing expensive operations.
    pub fn mark_expensive(&mut self, guard_var: VarId) {
        if let Some(cs) = self.active_sections.get_mut(&guard_var) {
            cs.mark_expensive();
        }
    }

    /// Mark a critical section as containing await point.
    pub fn mark_await(&mut self, guard_var: VarId, _await_line: u32) {
        if let Some(cs) = self.active_sections.get_mut(&guard_var) {
            cs.mark_await();
        }
    }

    /// End a critical section (guard dropped).
    pub fn release(&mut self, guard_var: VarId, line: u32) {
        if let Some(mut cs) = self.active_sections.remove(&guard_var) {
            cs.end_at(line);
            self.completed_sections.push(cs);
        }
    }

    /// Get all completed critical sections.
    pub fn critical_sections(&self) -> &[CriticalSectionV2] {
        &self.completed_sections
    }

    /// Get all lock acquisitions.
    pub fn acquisitions(&self) -> &[LockAcquisitionV2] {
        &self.acquisitions
    }

    /// Get lock acquisitions owned by a specific function.
    pub fn acquisitions_by_owner(&self, owner: SymbolId) -> Vec<&LockAcquisitionV2> {
        self.acquisitions
            .iter()
            .filter(|a| a.owner_fn == Some(owner))
            .collect()
    }

    /// Get active critical sections.
    pub fn active_sections(&self) -> impl Iterator<Item = &CriticalSectionV2> {
        self.active_sections.values()
    }

    /// Check if a guard is currently active.
    pub fn is_active(&self, guard_var: VarId) -> bool {
        self.active_sections.contains_key(&guard_var)
    }

    /// Clear all tracking state.
    pub fn clear(&mut self) {
        self.acquisitions.clear();
        self.active_sections.clear();
        self.completed_sections.clear();
    }

    /// Get the number of completed critical sections.
    pub fn completed_count(&self) -> usize {
        self.completed_sections.len()
    }

    /// Get the number of active critical sections.
    pub fn active_count(&self) -> usize {
        self.active_sections.len()
    }

    /// Flush all active sections to completed sections.
    ///
    /// Called at function/scope boundaries where guards are implicitly dropped.
    /// Since PureAST has no span info, end_line is left as None.
    pub fn flush_active_sections(&mut self) {
        let active = std::mem::take(&mut self.active_sections);
        for (_, cs) in active {
            self.completed_sections.push(cs);
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::symbol::SymbolId;
    use slotmap::SlotMap;

    /// Test helper to create VarIds from a shared mapping.
    struct TestVars {
        symbols: SlotMap<SymbolId, &'static str>,
        mapping: super::super::var_id::VarSymbolMapping,
    }

    impl TestVars {
        fn new() -> Self {
            Self {
                symbols: SlotMap::with_key(),
                mapping: super::super::var_id::VarSymbolMapping::new(),
            }
        }

        fn var(&mut self, name: &'static str) -> VarId {
            let sym = self.symbols.insert(name);
            self.mapping.register(sym)
        }
    }

    #[test]
    fn test_lock_acquisition_v2() {
        let mut vars = TestVars::new();
        let lock = vars.var("lock");
        let guard = vars.var("guard");
        let acq = LockAcquisitionV2::new(lock, guard, LockType::Mutex, 10, "mutex", "guard");

        assert_eq!(acq.lock_var, lock);
        assert_eq!(acq.guard_var, guard);
        assert_eq!(acq.lock_type, LockType::Mutex);
        assert_eq!(acq.line, 10);
        assert!(!acq.is_try);

        let try_acq = acq.with_try();
        assert!(try_acq.is_try);
    }

    #[test]
    fn test_critical_section_field_tracking() {
        let mut vars = TestVars::new();
        let lock = vars.var("lock");
        let guard = vars.var("guard");
        let acq = LockAcquisitionV2::new(lock, guard, LockType::Mutex, 10, "mutex", "guard");
        let mut cs = CriticalSectionV2::new(acq);

        cs.add_field_access(FieldAccessV2::new("counter", AccessKind::Read, 11));
        cs.add_field_access(FieldAccessV2::new("counter", AccessKind::Write, 12));
        cs.add_field_access(FieldAccessV2::new("name", AccessKind::Read, 13));

        let fields = cs.unique_fields();
        assert_eq!(fields.len(), 2);

        assert_eq!(cs.field_access_kind("counter"), Some(AccessKind::ReadWrite));
        assert_eq!(cs.field_access_kind("name"), Some(AccessKind::Read));
    }

    #[test]
    fn test_critical_section_is_read_only() {
        let mut vars = TestVars::new();
        let lock = vars.var("lock");
        let guard = vars.var("guard");
        let acq = LockAcquisitionV2::new(lock, guard, LockType::Mutex, 10, "mutex", "guard");
        let mut cs = CriticalSectionV2::new(acq);

        cs.add_field_access(FieldAccessV2::new("a", AccessKind::Read, 11));
        cs.add_field_access(FieldAccessV2::new("b", AccessKind::Read, 12));
        assert!(cs.is_read_only());

        cs.add_field_access(FieldAccessV2::new("c", AccessKind::Write, 13));
        assert!(!cs.is_read_only());
    }

    #[test]
    fn test_lock_tracker_lifecycle() {
        let mut tracker = LockTrackerV2::new();
        let mut vars = TestVars::new();
        let lock = vars.var("lock");
        let guard = vars.var("guard");

        let acq = LockAcquisitionV2::new(lock, guard, LockType::Mutex, 10, "mutex", "guard");
        tracker.acquire(acq);

        assert!(tracker.is_active(guard));
        assert_eq!(tracker.acquisitions().len(), 1);
        assert_eq!(tracker.active_count(), 1);

        tracker.record_field_access(guard, "counter", AccessKind::Write, 11);
        tracker.release(guard, 15);

        assert!(!tracker.is_active(guard));
        assert_eq!(tracker.critical_sections().len(), 1);
        assert_eq!(tracker.completed_count(), 1);
        assert_eq!(tracker.active_count(), 0);

        let cs = &tracker.critical_sections()[0];
        assert_eq!(cs.start_line, 10);
        assert_eq!(cs.end_line, Some(15));
        assert_eq!(cs.field_accesses.len(), 1);
    }

    #[test]
    fn test_lock_tracker_mark_expensive_await() {
        let mut tracker = LockTrackerV2::new();
        let mut vars = TestVars::new();
        let lock = vars.var("lock");
        let guard = vars.var("guard");

        let acq = LockAcquisitionV2::new(lock, guard, LockType::TokioMutex, 10, "mutex", "guard");
        tracker.acquire(acq);

        tracker.mark_expensive(guard);
        tracker.mark_await(guard, 12);
        tracker.release(guard, 15);

        let cs = &tracker.critical_sections()[0];
        assert!(cs.contains_expensive_ops);
        assert!(cs.contains_await);
    }

    #[test]
    fn test_lock_tracker_clear() {
        let mut tracker = LockTrackerV2::new();
        let mut vars = TestVars::new();
        let lock = vars.var("lock");
        let guard = vars.var("guard");

        let acq = LockAcquisitionV2::new(lock, guard, LockType::Mutex, 10, "mutex", "guard");
        tracker.acquire(acq);
        tracker.release(guard, 15);

        assert_eq!(tracker.completed_count(), 1);

        tracker.clear();

        assert_eq!(tracker.completed_count(), 0);
        assert_eq!(tracker.acquisitions().len(), 0);
    }

    #[test]
    fn test_flush_active_sections() {
        let mut tracker = LockTrackerV2::new();
        let mut vars = TestVars::new();
        let lock1 = vars.var("lock1");
        let guard1 = vars.var("guard1");
        let lock2 = vars.var("lock2");
        let guard2 = vars.var("guard2");

        let acq1 = LockAcquisitionV2::new(lock1, guard1, LockType::Mutex, 0, "m1", "g1");
        let acq2 = LockAcquisitionV2::new(lock2, guard2, LockType::RwLockRead, 0, "r1", "g2");
        tracker.acquire(acq1);
        tracker.acquire(acq2);

        assert_eq!(tracker.active_count(), 2);
        assert_eq!(tracker.completed_count(), 0);

        tracker.flush_active_sections();

        assert_eq!(tracker.active_count(), 0);
        assert_eq!(tracker.completed_count(), 2);
        // end_line is None since no explicit release
        assert!(tracker.critical_sections()[0].end_line.is_none());
        assert!(tracker.critical_sections()[1].end_line.is_none());
    }

    #[test]
    fn test_flush_preserves_acquisitions() {
        let mut tracker = LockTrackerV2::new();
        let mut vars = TestVars::new();
        let lock = vars.var("lock");
        let guard = vars.var("guard");

        let acq = LockAcquisitionV2::new(lock, guard, LockType::Mutex, 0, "mutex", "guard");
        tracker.acquire(acq);
        tracker.flush_active_sections();

        // acquisitions count remains
        assert_eq!(tracker.acquisitions().len(), 1);
        // completed_sections populated
        assert_eq!(tracker.completed_count(), 1);
    }
}