tensorlogic-adapters 0.1.0

Symbol tables, axis metadata, and domain masks for TensorLogic
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
//! Multi-user schema management with locking.
//!
//! This module provides thread-safe concurrent access to symbol tables with
//! read/write locking, transaction support, and lock statistics.
//!
//! # Features
//!
//! - **Read/Write Locks**: Multiple concurrent readers or single writer
//! - **Transactions**: Atomic operations with commit/rollback support
//! - **Lock Statistics**: Monitor lock contention and usage patterns
//! - **Timeout Support**: Prevent indefinite blocking on lock acquisition
//! - **Deadlock Detection**: Basic deadlock prevention through timeouts
//!
//! # Example
//!
//! ```rust
//! use tensorlogic_adapters::{LockedSymbolTable, DomainInfo};
//! use std::sync::Arc;
//! use std::thread;
//!
//! let table = Arc::new(LockedSymbolTable::new());
//!
//! // Spawn multiple readers
//! let mut handles = vec![];
//! for i in 0..3 {
//!     let table_clone = Arc::clone(&table);
//!     handles.push(thread::spawn(move || {
//!         let guard = table_clone.read();
//!         println!("Reader {} sees {} domains", i, guard.domains.len());
//!     }));
//! }
//!
//! // Wait for readers
//! for handle in handles {
//!     handle.join().expect("unwrap");
//! }
//!
//! // Single writer
//! {
//!     let mut guard = table.write();
//!     guard.add_domain(DomainInfo::new("User", 100)).expect("unwrap");
//! }
//! ```

use crate::{AdapterError, SymbolTable};
use std::sync::{RwLock, RwLockReadGuard, RwLockWriteGuard, TryLockError};
use std::time::{Duration, Instant};

/// Statistics about lock usage and contention.
#[derive(Debug, Clone, Default)]
pub struct LockStats {
    /// Total number of successful read lock acquisitions
    pub read_locks: usize,
    /// Total number of successful write lock acquisitions
    pub write_locks: usize,
    /// Total number of failed read lock attempts (would block)
    pub read_contentions: usize,
    /// Total number of failed write lock attempts (would block)
    pub write_contentions: usize,
    /// Total time spent waiting for read locks (milliseconds)
    pub read_wait_ms: u128,
    /// Total time spent waiting for write locks (milliseconds)
    pub write_wait_ms: u128,
    /// Number of transactions started
    pub transactions_started: usize,
    /// Number of transactions committed
    pub transactions_committed: usize,
    /// Number of transactions rolled back
    pub transactions_rolled_back: usize,
}

impl LockStats {
    /// Create new empty lock statistics.
    pub fn new() -> Self {
        Self::default()
    }

    /// Calculate average read wait time in milliseconds.
    pub fn avg_read_wait_ms(&self) -> f64 {
        if self.read_locks == 0 {
            0.0
        } else {
            self.read_wait_ms as f64 / self.read_locks as f64
        }
    }

    /// Calculate average write wait time in milliseconds.
    pub fn avg_write_wait_ms(&self) -> f64 {
        if self.write_locks == 0 {
            0.0
        } else {
            self.write_wait_ms as f64 / self.write_locks as f64
        }
    }

    /// Calculate read contention rate (0.0 to 1.0).
    pub fn read_contention_rate(&self) -> f64 {
        let total = self.read_locks + self.read_contentions;
        if total == 0 {
            0.0
        } else {
            self.read_contentions as f64 / total as f64
        }
    }

    /// Calculate write contention rate (0.0 to 1.0).
    pub fn write_contention_rate(&self) -> f64 {
        let total = self.write_locks + self.write_contentions;
        if total == 0 {
            0.0
        } else {
            self.write_contentions as f64 / total as f64
        }
    }

    /// Calculate transaction commit rate (0.0 to 1.0).
    pub fn commit_rate(&self) -> f64 {
        if self.transactions_started == 0 {
            0.0
        } else {
            self.transactions_committed as f64 / self.transactions_started as f64
        }
    }
}

/// A thread-safe symbol table with read/write locking.
///
/// This wrapper provides concurrent access to a symbol table with read/write
/// locks, transaction support, and lock statistics tracking.
pub struct LockedSymbolTable {
    table: RwLock<SymbolTable>,
    stats: RwLock<LockStats>,
}

impl LockedSymbolTable {
    /// Create a new locked symbol table.
    pub fn new() -> Self {
        Self {
            table: RwLock::new(SymbolTable::new()),
            stats: RwLock::new(LockStats::new()),
        }
    }

    /// Create a locked symbol table from an existing symbol table.
    pub fn from_table(table: SymbolTable) -> Self {
        Self {
            table: RwLock::new(table),
            stats: RwLock::new(LockStats::new()),
        }
    }

    /// Acquire a read lock on the symbol table.
    ///
    /// This will block until a read lock can be acquired. Multiple readers
    /// can hold locks simultaneously.
    pub fn read(&self) -> RwLockReadGuard<'_, SymbolTable> {
        let start = Instant::now();
        let guard = self.table.read().expect("lock should not be poisoned");
        let elapsed = start.elapsed().as_millis();

        if let Ok(mut stats) = self.stats.write() {
            stats.read_locks += 1;
            stats.read_wait_ms += elapsed;
        }

        guard
    }

    /// Try to acquire a read lock without blocking.
    ///
    /// Returns `Some(guard)` if successful, `None` if would block.
    pub fn try_read(&self) -> Option<RwLockReadGuard<'_, SymbolTable>> {
        match self.table.try_read() {
            Ok(guard) => {
                if let Ok(mut stats) = self.stats.write() {
                    stats.read_locks += 1;
                }
                Some(guard)
            }
            Err(TryLockError::WouldBlock) => {
                if let Ok(mut stats) = self.stats.write() {
                    stats.read_contentions += 1;
                }
                None
            }
            Err(TryLockError::Poisoned(_)) => None,
        }
    }

    /// Acquire a write lock on the symbol table.
    ///
    /// This will block until a write lock can be acquired. Only one writer
    /// can hold a lock at a time, and no readers can be active.
    pub fn write(&self) -> RwLockWriteGuard<'_, SymbolTable> {
        let start = Instant::now();
        let guard = self.table.write().expect("lock should not be poisoned");
        let elapsed = start.elapsed().as_millis();

        if let Ok(mut stats) = self.stats.write() {
            stats.write_locks += 1;
            stats.write_wait_ms += elapsed;
        }

        guard
    }

    /// Try to acquire a write lock without blocking.
    ///
    /// Returns `Some(guard)` if successful, `None` if would block.
    pub fn try_write(&self) -> Option<RwLockWriteGuard<'_, SymbolTable>> {
        match self.table.try_write() {
            Ok(guard) => {
                if let Ok(mut stats) = self.stats.write() {
                    stats.write_locks += 1;
                }
                Some(guard)
            }
            Err(TryLockError::WouldBlock) => {
                if let Ok(mut stats) = self.stats.write() {
                    stats.write_contentions += 1;
                }
                None
            }
            Err(TryLockError::Poisoned(_)) => None,
        }
    }

    /// Get current lock statistics.
    pub fn stats(&self) -> LockStats {
        self.stats
            .read()
            .expect("lock should not be poisoned")
            .clone()
    }

    /// Reset lock statistics.
    pub fn reset_stats(&self) {
        *self.stats.write().expect("lock should not be poisoned") = LockStats::new();
    }

    /// Start a new transaction.
    ///
    /// Returns a transaction object that can be committed or rolled back.
    pub fn begin_transaction(&self) -> Transaction<'_> {
        if let Ok(mut stats) = self.stats.write() {
            stats.transactions_started += 1;
        }
        Transaction::new(self)
    }
}

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

/// A transaction for atomic operations on a symbol table.
///
/// Transactions capture the state of the symbol table at the start and
/// allow rolling back to that state if needed.
pub struct Transaction<'a> {
    locked_table: &'a LockedSymbolTable,
    snapshot: Option<SymbolTable>,
    committed: bool,
}

impl<'a> Transaction<'a> {
    fn new(locked_table: &'a LockedSymbolTable) -> Self {
        // Take snapshot
        let snapshot = locked_table.read().clone();
        Self {
            locked_table,
            snapshot: Some(snapshot),
            committed: false,
        }
    }

    /// Execute operations within this transaction.
    ///
    /// The closure receives a mutable reference to the symbol table.
    pub fn execute<F, R>(&mut self, f: F) -> Result<R, AdapterError>
    where
        F: FnOnce(&mut SymbolTable) -> Result<R, AdapterError>,
    {
        let mut guard = self.locked_table.write();
        f(&mut guard)
    }

    /// Commit the transaction, making all changes permanent.
    pub fn commit(mut self) {
        self.committed = true;
        if let Ok(mut stats) = self.locked_table.stats.write() {
            stats.transactions_committed += 1;
        }
        // Drop snapshot
        self.snapshot = None;
    }

    /// Rollback the transaction, reverting all changes.
    pub fn rollback(mut self) {
        if let Some(snapshot) = self.snapshot.take() {
            *self.locked_table.write() = snapshot;
        }
        if let Ok(mut stats) = self.locked_table.stats.write() {
            stats.transactions_rolled_back += 1;
        }
    }
}

impl<'a> Drop for Transaction<'a> {
    fn drop(&mut self) {
        // Auto-rollback if not committed
        if !self.committed {
            if let Some(snapshot) = self.snapshot.take() {
                if let Ok(mut guard) = self.locked_table.table.write() {
                    *guard = snapshot;
                }
                if let Ok(mut stats) = self.locked_table.stats.write() {
                    stats.transactions_rolled_back += 1;
                }
            }
        }
    }
}

/// Extension trait for timeout-based lock acquisition.
pub trait LockWithTimeout {
    /// Try to acquire a read lock with a timeout.
    ///
    /// Returns `Some(guard)` if successful within timeout, `None` otherwise.
    fn read_timeout(&self, timeout: Duration) -> Option<RwLockReadGuard<'_, SymbolTable>>;

    /// Try to acquire a write lock with a timeout.
    ///
    /// Returns `Some(guard)` if successful within timeout, `None` otherwise.
    fn write_timeout(&self, timeout: Duration) -> Option<RwLockWriteGuard<'_, SymbolTable>>;
}

impl LockWithTimeout for LockedSymbolTable {
    fn read_timeout(&self, timeout: Duration) -> Option<RwLockReadGuard<'_, SymbolTable>> {
        let start = Instant::now();
        loop {
            if let Some(guard) = self.try_read() {
                return Some(guard);
            }
            if start.elapsed() >= timeout {
                if let Ok(mut stats) = self.stats.write() {
                    stats.read_contentions += 1;
                }
                return None;
            }
            std::thread::sleep(Duration::from_millis(1));
        }
    }

    fn write_timeout(&self, timeout: Duration) -> Option<RwLockWriteGuard<'_, SymbolTable>> {
        let start = Instant::now();
        loop {
            if let Some(guard) = self.try_write() {
                return Some(guard);
            }
            if start.elapsed() >= timeout {
                if let Ok(mut stats) = self.stats.write() {
                    stats.write_contentions += 1;
                }
                return None;
            }
            std::thread::sleep(Duration::from_millis(1));
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::DomainInfo;
    use std::sync::Arc;
    use std::thread;

    #[test]
    fn test_basic_read_write() {
        let table = LockedSymbolTable::new();

        // Write
        {
            let mut guard = table.write();
            guard
                .add_domain(DomainInfo::new("User", 100))
                .expect("unwrap");
        }

        // Read
        {
            let guard = table.read();
            assert_eq!(guard.domains.len(), 1);
            assert!(guard.get_domain("User").is_some());
        }
    }

    #[test]
    fn test_multiple_readers() {
        let table = Arc::new(LockedSymbolTable::new());

        // Add some data
        {
            let mut guard = table.write();
            guard
                .add_domain(DomainInfo::new("User", 100))
                .expect("unwrap");
        }

        // Spawn multiple readers
        let mut handles = vec![];
        for _ in 0..5 {
            let table_clone = Arc::clone(&table);
            handles.push(thread::spawn(move || {
                let guard = table_clone.read();
                assert_eq!(guard.domains.len(), 1);
            }));
        }

        for handle in handles {
            handle.join().expect("unwrap");
        }
    }

    #[test]
    fn test_try_read_write() {
        let table = LockedSymbolTable::new();

        // Try read (should succeed)
        {
            let guard = table.try_read();
            assert!(guard.is_some());
        }

        // Try write (should succeed)
        {
            let guard = table.try_write();
            assert!(guard.is_some());
        }
    }

    #[test]
    fn test_try_write_contention() {
        let table = Arc::new(LockedSymbolTable::new());

        // Hold read lock
        let _read_guard = table.read();

        // Try write (should fail due to active reader)
        let table_clone = Arc::clone(&table);
        let handle = thread::spawn(move || {
            let guard = table_clone.try_write();
            assert!(guard.is_none());
        });

        handle.join().expect("unwrap");

        // Check contention stats
        let stats = table.stats();
        assert!(stats.write_contentions > 0);
    }

    #[test]
    fn test_transaction_commit() {
        let table = LockedSymbolTable::new();

        {
            let mut txn = table.begin_transaction();
            txn.execute(|t| {
                t.add_domain(DomainInfo::new("User", 100)).expect("unwrap");
                t.add_domain(DomainInfo::new("Post", 1000)).expect("unwrap");
                Ok(())
            })
            .expect("unwrap");
            txn.commit();
        }

        let guard = table.read();
        assert_eq!(guard.domains.len(), 2);

        let stats = table.stats();
        assert_eq!(stats.transactions_committed, 1);
    }

    #[test]
    fn test_transaction_rollback() {
        let table = LockedSymbolTable::new();

        // Add initial domain
        {
            let mut guard = table.write();
            guard
                .add_domain(DomainInfo::new("User", 100))
                .expect("unwrap");
        }

        {
            let mut txn = table.begin_transaction();
            txn.execute(|t| {
                t.add_domain(DomainInfo::new("Post", 1000)).expect("unwrap");
                Ok(())
            })
            .expect("unwrap");
            txn.rollback();
        }

        let guard = table.read();
        assert_eq!(guard.domains.len(), 1);
        assert!(guard.get_domain("Post").is_none());

        let stats = table.stats();
        assert_eq!(stats.transactions_rolled_back, 1);
    }

    #[test]
    fn test_transaction_auto_rollback() {
        let table = LockedSymbolTable::new();

        {
            let mut txn = table.begin_transaction();
            txn.execute(|t| {
                t.add_domain(DomainInfo::new("User", 100)).expect("unwrap");
                Ok(())
            })
            .expect("unwrap");
            // Drop without commit (auto-rollback)
        }

        let guard = table.read();
        assert_eq!(guard.domains.len(), 0);

        let stats = table.stats();
        assert_eq!(stats.transactions_rolled_back, 1);
    }

    #[test]
    fn test_lock_stats() {
        let table = LockedSymbolTable::new();

        // Read operations
        for _ in 0..3 {
            let _guard = table.read();
        }

        // Write operations
        for _ in 0..2 {
            let _guard = table.write();
        }

        let stats = table.stats();
        assert_eq!(stats.read_locks, 3);
        assert_eq!(stats.write_locks, 2);
    }

    #[test]
    fn test_reset_stats() {
        let table = LockedSymbolTable::new();

        let _guard = table.read();
        assert_eq!(table.stats().read_locks, 1);

        table.reset_stats();
        assert_eq!(table.stats().read_locks, 0);
    }

    #[test]
    fn test_timeout_success() {
        let table = LockedSymbolTable::new();

        let guard = table.read_timeout(Duration::from_millis(100));
        assert!(guard.is_some());
    }

    #[test]
    fn test_timeout_failure() {
        let table = Arc::new(LockedSymbolTable::new());

        // Hold write lock
        let _write_guard = table.write();

        // Try to acquire write lock with timeout in another thread
        let table_clone = Arc::clone(&table);
        let handle = thread::spawn(move || {
            let guard = table_clone.write_timeout(Duration::from_millis(50));
            assert!(guard.is_none());
        });

        handle.join().expect("unwrap");
    }

    #[test]
    fn test_concurrent_read_write() {
        let table = Arc::new(LockedSymbolTable::new());

        // Initialize with data
        {
            let mut guard = table.write();
            guard
                .add_domain(DomainInfo::new("User", 100))
                .expect("unwrap");
        }

        let mut handles = vec![];

        // Readers
        for _ in 0..3 {
            let table_clone = Arc::clone(&table);
            handles.push(thread::spawn(move || {
                for _ in 0..10 {
                    let guard = table_clone.read();
                    assert!(!guard.domains.is_empty());
                    thread::sleep(Duration::from_millis(1));
                }
            }));
        }

        // Writers
        for i in 0..2 {
            let table_clone = Arc::clone(&table);
            handles.push(thread::spawn(move || {
                for j in 0..5 {
                    let mut guard = table_clone.write();
                    let domain_name = format!("Domain_{}_{}", i, j);
                    guard
                        .add_domain(DomainInfo::new(&domain_name, 100))
                        .expect("unwrap");
                    thread::sleep(Duration::from_millis(2));
                }
            }));
        }

        for handle in handles {
            handle.join().expect("unwrap");
        }

        // Verify final state
        let guard = table.read();
        assert!(guard.domains.len() >= 11); // 1 initial + 10 from writers

        // Check stats
        let stats = table.stats();
        assert!(stats.read_locks > 0);
        assert!(stats.write_locks > 0);
    }

    #[test]
    fn test_stats_calculations() {
        let mut stats = LockStats::new();
        stats.read_locks = 10;
        stats.write_locks = 5;
        stats.read_wait_ms = 100;
        stats.write_wait_ms = 200;
        stats.read_contentions = 2;
        stats.write_contentions = 3;
        stats.transactions_started = 10;
        stats.transactions_committed = 8;

        assert_eq!(stats.avg_read_wait_ms(), 10.0);
        assert_eq!(stats.avg_write_wait_ms(), 40.0);
        assert!((stats.read_contention_rate() - 0.1667).abs() < 0.001);
        assert_eq!(stats.write_contention_rate(), 0.375);
        assert_eq!(stats.commit_rate(), 0.8);
    }

    #[test]
    fn test_transaction_error_handling() {
        let table = LockedSymbolTable::new();

        let result: Result<(), AdapterError> = {
            let mut txn = table.begin_transaction();
            txn.execute(|t| {
                t.add_domain(DomainInfo::new("User", 100)).expect("unwrap");
                // Simulate error
                Err(AdapterError::DuplicateDomain("User".to_string()))
            })
        };

        assert!(result.is_err());

        // Transaction should auto-rollback
        let guard = table.read();
        assert_eq!(guard.domains.len(), 0);
    }

    #[test]
    fn test_from_table() {
        let mut original = SymbolTable::new();
        original
            .add_domain(DomainInfo::new("User", 100))
            .expect("unwrap");

        let locked = LockedSymbolTable::from_table(original);

        let guard = locked.read();
        assert_eq!(guard.domains.len(), 1);
        assert!(guard.get_domain("User").is_some());
    }
}