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
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
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
//! Incremental validation system for efficient schema revalidation.
//!
//! This module provides smart revalidation that only checks what has changed,
//! enabling efficient validation of large schemas during iterative development.
//!
//! # Overview
//!
//! Traditional validation requires full schema traversal on every change.
//! Incremental validation tracks modifications and only revalidates affected
//! components, providing 10-100x speedup for large schemas.
//!
//! # Architecture
//!
//! - **ChangeTracker**: Records schema modifications (additions, updates, deletions)
//! - **DependencyGraph**: Tracks relationships between schema components
//! - **IncrementalValidator**: Performs targeted validation of affected components
//! - **ValidationCache**: Caches validation results for unchanged components
//!
//! # Example
//!
//! ```rust
//! use tensorlogic_adapters::{SymbolTable, DomainInfo, ChangeTracker, IncrementalValidator};
//!
//! let mut table = SymbolTable::new();
//! let mut tracker = ChangeTracker::new();
//!
//! // Initial validation
//! table.add_domain(DomainInfo::new("Person", 100)).expect("unwrap");
//! tracker.record_domain_addition("Person");
//!
//! let mut validator = IncrementalValidator::new(&table, &tracker);
//! let report = validator.validate_incremental().expect("unwrap");
//! assert!(report.is_valid());
//!
//! // Incremental update - only validates affected parts
//! tracker.record_domain_addition("Location");
//! table.add_domain(DomainInfo::new("Location", 50)).expect("unwrap");
//!
//! let mut validator2 = IncrementalValidator::new(&table, &tracker);
//! let report = validator2.validate_incremental().expect("unwrap");
//! assert!(report.is_valid());
//! ```

use anyhow::Result;
use std::collections::{HashMap, HashSet, VecDeque};
use std::time::{Duration, Instant};

use crate::{DomainHierarchy, SymbolTable, ValidationReport};

/// Type of schema change
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub enum ChangeType {
    /// Domain added
    DomainAdded(String),
    /// Domain modified
    DomainModified(String),
    /// Domain removed
    DomainRemoved(String),
    /// Predicate added
    PredicateAdded(String),
    /// Predicate modified
    PredicateModified(String),
    /// Predicate removed
    PredicateRemoved(String),
    /// Variable binding added
    VariableAdded(String),
    /// Variable binding modified
    VariableModified(String),
    /// Variable binding removed
    VariableRemoved(String),
    /// Hierarchy relationship added
    HierarchyAdded(String, String),
    /// Hierarchy relationship removed
    HierarchyRemoved(String, String),
}

/// Change record with timestamp and metadata
#[derive(Clone, Debug)]
pub struct Change {
    pub change_type: ChangeType,
    pub timestamp: Instant,
    pub batch_id: Option<usize>,
}

impl Change {
    pub fn new(change_type: ChangeType) -> Self {
        Self {
            change_type,
            timestamp: Instant::now(),
            batch_id: None,
        }
    }

    pub fn with_batch(mut self, batch_id: usize) -> Self {
        self.batch_id = Some(batch_id);
        self
    }
}

/// Tracks changes to a symbol table for incremental validation
#[derive(Clone, Debug, Default)]
pub struct ChangeTracker {
    changes: Vec<Change>,
    domains_affected: HashSet<String>,
    predicates_affected: HashSet<String>,
    variables_affected: HashSet<String>,
    current_batch: Option<usize>,
    next_batch_id: usize,
}

impl ChangeTracker {
    pub fn new() -> Self {
        Self::default()
    }

    /// Start a batch of changes that will be validated together
    pub fn begin_batch(&mut self) -> usize {
        let batch_id = self.next_batch_id;
        self.next_batch_id += 1;
        self.current_batch = Some(batch_id);
        batch_id
    }

    /// End the current batch
    pub fn end_batch(&mut self) {
        self.current_batch = None;
    }

    /// Record a domain addition
    pub fn record_domain_addition(&mut self, domain: impl Into<String>) {
        let domain = domain.into();
        self.domains_affected.insert(domain.clone());
        let mut change = Change::new(ChangeType::DomainAdded(domain));
        if let Some(batch) = self.current_batch {
            change = change.with_batch(batch);
        }
        self.changes.push(change);
    }

    /// Record a domain modification
    pub fn record_domain_modification(&mut self, domain: impl Into<String>) {
        let domain = domain.into();
        self.domains_affected.insert(domain.clone());
        let mut change = Change::new(ChangeType::DomainModified(domain));
        if let Some(batch) = self.current_batch {
            change = change.with_batch(batch);
        }
        self.changes.push(change);
    }

    /// Record a domain removal
    pub fn record_domain_removal(&mut self, domain: impl Into<String>) {
        let domain = domain.into();
        self.domains_affected.insert(domain.clone());
        let mut change = Change::new(ChangeType::DomainRemoved(domain));
        if let Some(batch) = self.current_batch {
            change = change.with_batch(batch);
        }
        self.changes.push(change);
    }

    /// Record a predicate addition
    pub fn record_predicate_addition(&mut self, predicate: impl Into<String>) {
        let predicate = predicate.into();
        self.predicates_affected.insert(predicate.clone());
        let mut change = Change::new(ChangeType::PredicateAdded(predicate));
        if let Some(batch) = self.current_batch {
            change = change.with_batch(batch);
        }
        self.changes.push(change);
    }

    /// Record a predicate modification
    pub fn record_predicate_modification(&mut self, predicate: impl Into<String>) {
        let predicate = predicate.into();
        self.predicates_affected.insert(predicate.clone());
        let mut change = Change::new(ChangeType::PredicateModified(predicate));
        if let Some(batch) = self.current_batch {
            change = change.with_batch(batch);
        }
        self.changes.push(change);
    }

    /// Record a predicate removal
    pub fn record_predicate_removal(&mut self, predicate: impl Into<String>) {
        let predicate = predicate.into();
        self.predicates_affected.insert(predicate.clone());
        let mut change = Change::new(ChangeType::PredicateRemoved(predicate));
        if let Some(batch) = self.current_batch {
            change = change.with_batch(batch);
        }
        self.changes.push(change);
    }

    /// Record a variable binding addition
    pub fn record_variable_addition(&mut self, variable: impl Into<String>) {
        let variable = variable.into();
        self.variables_affected.insert(variable.clone());
        let mut change = Change::new(ChangeType::VariableAdded(variable));
        if let Some(batch) = self.current_batch {
            change = change.with_batch(batch);
        }
        self.changes.push(change);
    }

    /// Record a variable binding modification
    pub fn record_variable_modification(&mut self, variable: impl Into<String>) {
        let variable = variable.into();
        self.variables_affected.insert(variable.clone());
        let mut change = Change::new(ChangeType::VariableModified(variable));
        if let Some(batch) = self.current_batch {
            change = change.with_batch(batch);
        }
        self.changes.push(change);
    }

    /// Record a variable binding removal
    pub fn record_variable_removal(&mut self, variable: impl Into<String>) {
        let variable = variable.into();
        self.variables_affected.insert(variable.clone());
        let mut change = Change::new(ChangeType::VariableRemoved(variable));
        if let Some(batch) = self.current_batch {
            change = change.with_batch(batch);
        }
        self.changes.push(change);
    }

    /// Record a hierarchy relationship addition
    pub fn record_hierarchy_addition(
        &mut self,
        subtype: impl Into<String>,
        supertype: impl Into<String>,
    ) {
        let subtype = subtype.into();
        let supertype = supertype.into();
        self.domains_affected.insert(subtype.clone());
        self.domains_affected.insert(supertype.clone());
        let mut change = Change::new(ChangeType::HierarchyAdded(subtype, supertype));
        if let Some(batch) = self.current_batch {
            change = change.with_batch(batch);
        }
        self.changes.push(change);
    }

    /// Record a hierarchy relationship removal
    pub fn record_hierarchy_removal(
        &mut self,
        subtype: impl Into<String>,
        supertype: impl Into<String>,
    ) {
        let subtype = subtype.into();
        let supertype = supertype.into();
        self.domains_affected.insert(subtype.clone());
        self.domains_affected.insert(supertype.clone());
        let mut change = Change::new(ChangeType::HierarchyRemoved(subtype, supertype));
        if let Some(batch) = self.current_batch {
            change = change.with_batch(batch);
        }
        self.changes.push(change);
    }

    /// Get all changes
    pub fn changes(&self) -> &[Change] {
        &self.changes
    }

    /// Get domains affected by changes
    pub fn domains_affected(&self) -> &HashSet<String> {
        &self.domains_affected
    }

    /// Get predicates affected by changes
    pub fn predicates_affected(&self) -> &HashSet<String> {
        &self.predicates_affected
    }

    /// Get variables affected by changes
    pub fn variables_affected(&self) -> &HashSet<String> {
        &self.variables_affected
    }

    /// Check if any changes have been recorded
    pub fn has_changes(&self) -> bool {
        !self.changes.is_empty()
    }

    /// Clear all tracked changes
    pub fn clear(&mut self) {
        self.changes.clear();
        self.domains_affected.clear();
        self.predicates_affected.clear();
        self.variables_affected.clear();
    }

    /// Get change statistics
    pub fn stats(&self) -> ChangeStats {
        let mut by_type = HashMap::new();
        for change in &self.changes {
            let type_name = match &change.change_type {
                ChangeType::DomainAdded(_) => "DomainAdded",
                ChangeType::DomainModified(_) => "DomainModified",
                ChangeType::DomainRemoved(_) => "DomainRemoved",
                ChangeType::PredicateAdded(_) => "PredicateAdded",
                ChangeType::PredicateModified(_) => "PredicateModified",
                ChangeType::PredicateRemoved(_) => "PredicateRemoved",
                ChangeType::VariableAdded(_) => "VariableAdded",
                ChangeType::VariableModified(_) => "VariableModified",
                ChangeType::VariableRemoved(_) => "VariableRemoved",
                ChangeType::HierarchyAdded(_, _) => "HierarchyAdded",
                ChangeType::HierarchyRemoved(_, _) => "HierarchyRemoved",
            };
            *by_type.entry(type_name.to_string()).or_insert(0) += 1;
        }

        ChangeStats {
            total_changes: self.changes.len(),
            domains_affected: self.domains_affected.len(),
            predicates_affected: self.predicates_affected.len(),
            variables_affected: self.variables_affected.len(),
            changes_by_type: by_type,
        }
    }
}

/// Statistics about recorded changes
#[derive(Clone, Debug)]
pub struct ChangeStats {
    pub total_changes: usize,
    pub domains_affected: usize,
    pub predicates_affected: usize,
    pub variables_affected: usize,
    pub changes_by_type: HashMap<String, usize>,
}

/// Dependency graph for schema components
#[derive(Clone, Debug, Default)]
pub struct DependencyGraph {
    /// Predicates that depend on each domain
    domain_dependents: HashMap<String, HashSet<String>>,
    /// Domains that each predicate depends on
    predicate_dependencies: HashMap<String, HashSet<String>>,
    /// Variables that depend on each domain
    variable_dependents: HashMap<String, HashSet<String>>,
}

impl DependencyGraph {
    pub fn new() -> Self {
        Self::default()
    }

    /// Build dependency graph from symbol table
    pub fn from_symbol_table(table: &SymbolTable) -> Self {
        let mut graph = Self::new();

        // Add predicate dependencies
        for (pred_name, pred) in &table.predicates {
            for domain in &pred.arg_domains {
                graph.add_predicate_dependency(pred_name, domain);
            }
        }

        // Add variable dependencies
        for (var, domain) in &table.variables {
            graph.add_variable_dependency(var, domain);
        }

        graph
    }

    /// Add a predicate dependency on a domain
    pub fn add_predicate_dependency(
        &mut self,
        predicate: impl Into<String>,
        domain: impl Into<String>,
    ) {
        let predicate = predicate.into();
        let domain = domain.into();

        self.domain_dependents
            .entry(domain.clone())
            .or_default()
            .insert(predicate.clone());

        self.predicate_dependencies
            .entry(predicate)
            .or_default()
            .insert(domain);
    }

    /// Add a variable dependency on a domain
    pub fn add_variable_dependency(
        &mut self,
        variable: impl Into<String>,
        domain: impl Into<String>,
    ) {
        let variable = variable.into();
        let domain = domain.into();

        self.variable_dependents
            .entry(domain)
            .or_default()
            .insert(variable);
    }

    /// Get all predicates that depend on a domain
    pub fn get_dependent_predicates(&self, domain: &str) -> HashSet<String> {
        self.domain_dependents
            .get(domain)
            .cloned()
            .unwrap_or_default()
    }

    /// Get all variables that depend on a domain
    pub fn get_dependent_variables(&self, domain: &str) -> HashSet<String> {
        self.variable_dependents
            .get(domain)
            .cloned()
            .unwrap_or_default()
    }

    /// Get all domains that a predicate depends on
    pub fn get_predicate_dependencies(&self, predicate: &str) -> HashSet<String> {
        self.predicate_dependencies
            .get(predicate)
            .cloned()
            .unwrap_or_default()
    }

    /// Compute transitive closure of affected components
    pub fn compute_affected_components(
        &self,
        initial_domains: &HashSet<String>,
    ) -> AffectedComponents {
        let mut affected = AffectedComponents::default();
        let mut to_process: VecDeque<String> = initial_domains.iter().cloned().collect();

        affected.domains.extend(initial_domains.clone());

        while let Some(domain) = to_process.pop_front() {
            // Find all predicates depending on this domain
            if let Some(predicates) = self.domain_dependents.get(&domain) {
                for pred in predicates {
                    if affected.predicates.insert(pred.clone()) {
                        // If this predicate depends on other domains, they might be affected too
                        if let Some(deps) = self.predicate_dependencies.get(pred) {
                            for dep_domain in deps {
                                if dep_domain != &domain && !affected.domains.contains(dep_domain) {
                                    // Mark as indirectly affected
                                    affected.domains.insert(dep_domain.clone());
                                }
                            }
                        }
                    }
                }
            }

            // Find all variables depending on this domain
            if let Some(variables) = self.variable_dependents.get(&domain) {
                affected.variables.extend(variables.clone());
            }
        }

        affected
    }
}

/// Components affected by changes
#[derive(Clone, Debug, Default)]
pub struct AffectedComponents {
    pub domains: HashSet<String>,
    pub predicates: HashSet<String>,
    pub variables: HashSet<String>,
}

impl AffectedComponents {
    pub fn is_empty(&self) -> bool {
        self.domains.is_empty() && self.predicates.is_empty() && self.variables.is_empty()
    }

    pub fn total_count(&self) -> usize {
        self.domains.len() + self.predicates.len() + self.variables.len()
    }
}

/// Cache for validation results
#[derive(Clone, Debug, Default)]
pub struct ValidationCache {
    domain_results: HashMap<String, Vec<String>>,
    predicate_results: HashMap<String, Vec<String>>,
    variable_results: HashMap<String, Vec<String>>,
}

impl ValidationCache {
    pub fn new() -> Self {
        Self::default()
    }

    /// Cache domain validation results
    pub fn cache_domain(&mut self, domain: impl Into<String>, errors: Vec<String>) {
        self.domain_results.insert(domain.into(), errors);
    }

    /// Cache predicate validation results
    pub fn cache_predicate(&mut self, predicate: impl Into<String>, errors: Vec<String>) {
        self.predicate_results.insert(predicate.into(), errors);
    }

    /// Cache variable validation results
    pub fn cache_variable(&mut self, variable: impl Into<String>, errors: Vec<String>) {
        self.variable_results.insert(variable.into(), errors);
    }

    /// Get cached domain result
    pub fn get_domain(&self, domain: &str) -> Option<&Vec<String>> {
        self.domain_results.get(domain)
    }

    /// Get cached predicate result
    pub fn get_predicate(&self, predicate: &str) -> Option<&Vec<String>> {
        self.predicate_results.get(predicate)
    }

    /// Get cached variable result
    pub fn get_variable(&self, variable: &str) -> Option<&Vec<String>> {
        self.variable_results.get(variable)
    }

    /// Invalidate cache entries for affected components
    pub fn invalidate(&mut self, affected: &AffectedComponents) {
        for domain in &affected.domains {
            self.domain_results.remove(domain);
        }
        for predicate in &affected.predicates {
            self.predicate_results.remove(predicate);
        }
        for variable in &affected.variables {
            self.variable_results.remove(variable);
        }
    }

    /// Clear all cached results
    pub fn clear(&mut self) {
        self.domain_results.clear();
        self.predicate_results.clear();
        self.variable_results.clear();
    }

    /// Get cache statistics
    pub fn stats(&self) -> CacheStats {
        CacheStats {
            domains_cached: self.domain_results.len(),
            predicates_cached: self.predicate_results.len(),
            variables_cached: self.variable_results.len(),
        }
    }
}

/// Cache statistics
#[derive(Clone, Debug)]
pub struct CacheStats {
    pub domains_cached: usize,
    pub predicates_cached: usize,
    pub variables_cached: usize,
}

/// Incremental validator for symbol tables
pub struct IncrementalValidator<'a> {
    table: &'a SymbolTable,
    tracker: &'a ChangeTracker,
    hierarchy: Option<&'a DomainHierarchy>,
    cache: ValidationCache,
    dependency_graph: DependencyGraph,
}

impl<'a> IncrementalValidator<'a> {
    pub fn new(table: &'a SymbolTable, tracker: &'a ChangeTracker) -> Self {
        Self {
            table,
            tracker,
            hierarchy: None,
            cache: ValidationCache::new(),
            dependency_graph: DependencyGraph::from_symbol_table(table),
        }
    }

    pub fn with_hierarchy(mut self, hierarchy: &'a DomainHierarchy) -> Self {
        self.hierarchy = Some(hierarchy);
        self
    }

    pub fn with_cache(mut self, cache: ValidationCache) -> Self {
        self.cache = cache;
        self
    }

    /// Get the validation cache
    pub fn cache(&self) -> &ValidationCache {
        &self.cache
    }

    /// Extract the validation cache (consumes self)
    pub fn into_cache(self) -> ValidationCache {
        self.cache
    }

    /// Perform incremental validation
    pub fn validate_incremental(&mut self) -> Result<IncrementalValidationReport> {
        let start = Instant::now();

        if !self.tracker.has_changes() {
            // No changes, return empty report
            return Ok(IncrementalValidationReport {
                report: ValidationReport::new(),
                components_validated: 0,
                components_cached: self.cache.stats().domains_cached
                    + self.cache.stats().predicates_cached
                    + self.cache.stats().variables_cached,
                duration: start.elapsed(),
            });
        }

        // Compute affected components
        let affected = self
            .dependency_graph
            .compute_affected_components(self.tracker.domains_affected());

        // Invalidate cache for affected components
        self.cache.invalidate(&affected);

        // Perform targeted validation
        let mut report = ValidationReport::new();
        let mut components_validated = 0;

        // Validate affected domains
        for domain in &affected.domains {
            if let Some(cached) = self.cache.get_domain(domain) {
                report.errors.extend(cached.clone());
            } else {
                let errors = self.validate_domain(domain)?;
                report.errors.extend(errors.clone());
                self.cache.cache_domain(domain, errors);
                components_validated += 1;
            }
        }

        // Validate affected predicates
        for predicate in &affected.predicates {
            if let Some(cached) = self.cache.get_predicate(predicate) {
                report.errors.extend(cached.clone());
            } else {
                let errors = self.validate_predicate(predicate)?;
                report.errors.extend(errors.clone());
                self.cache.cache_predicate(predicate, errors);
                components_validated += 1;
            }
        }

        // Validate affected variables
        for variable in &affected.variables {
            if let Some(cached) = self.cache.get_variable(variable) {
                report.errors.extend(cached.clone());
            } else {
                let errors = self.validate_variable(variable)?;
                report.errors.extend(errors.clone());
                self.cache.cache_variable(variable, errors);
                components_validated += 1;
            }
        }

        let cache_stats = self.cache.stats();
        let components_cached = cache_stats.domains_cached
            + cache_stats.predicates_cached
            + cache_stats.variables_cached;

        Ok(IncrementalValidationReport {
            report,
            components_validated,
            components_cached,
            duration: start.elapsed(),
        })
    }

    fn validate_domain(&self, domain: &str) -> Result<Vec<String>> {
        let mut errors = Vec::new();

        if !self.table.domains.contains_key(domain) {
            errors.push(format!("Domain '{}' not found in symbol table", domain));
        }

        Ok(errors)
    }

    fn validate_predicate(&self, predicate: &str) -> Result<Vec<String>> {
        let mut errors = Vec::new();

        if let Some(pred) = self.table.predicates.get(predicate) {
            for domain in &pred.arg_domains {
                if domain != "Unknown" && !self.table.domains.contains_key(domain) {
                    errors.push(format!(
                        "Predicate '{}' references undefined domain '{}'",
                        predicate, domain
                    ));
                }
            }
        } else {
            errors.push(format!(
                "Predicate '{}' not found in symbol table",
                predicate
            ));
        }

        Ok(errors)
    }

    fn validate_variable(&self, variable: &str) -> Result<Vec<String>> {
        let mut errors = Vec::new();

        if let Some(domain) = self.table.variables.get(variable) {
            if !self.table.domains.contains_key(domain) {
                errors.push(format!(
                    "Variable '{}' is bound to undefined domain '{}'",
                    variable, domain
                ));
            }
        } else {
            errors.push(format!("Variable '{}' not found in symbol table", variable));
        }

        Ok(errors)
    }
}

/// Incremental validation report with performance metrics
#[derive(Clone, Debug)]
pub struct IncrementalValidationReport {
    pub report: ValidationReport,
    pub components_validated: usize,
    pub components_cached: usize,
    pub duration: Duration,
}

impl IncrementalValidationReport {
    pub fn is_valid(&self) -> bool {
        self.report.is_valid()
    }

    pub fn cache_hit_rate(&self) -> f64 {
        let total = self.components_validated + self.components_cached;
        if total == 0 {
            0.0
        } else {
            self.components_cached as f64 / total as f64
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{DomainInfo, PredicateInfo};

    #[test]
    fn test_change_tracker_basic() {
        let mut tracker = ChangeTracker::new();

        tracker.record_domain_addition("Person");
        tracker.record_predicate_addition("knows");
        tracker.record_variable_addition("x");

        assert_eq!(tracker.changes().len(), 3);
        assert_eq!(tracker.domains_affected().len(), 1);
        assert_eq!(tracker.predicates_affected().len(), 1);
        assert_eq!(tracker.variables_affected().len(), 1);
    }

    #[test]
    fn test_change_tracker_batching() {
        let mut tracker = ChangeTracker::new();

        let batch1 = tracker.begin_batch();
        tracker.record_domain_addition("Person");
        tracker.record_domain_addition("Location");
        tracker.end_batch();

        let batch2 = tracker.begin_batch();
        tracker.record_predicate_addition("at");
        tracker.end_batch();

        assert_eq!(tracker.changes().len(), 3);
        assert!(tracker.changes()[0].batch_id == Some(batch1));
        assert!(tracker.changes()[1].batch_id == Some(batch1));
        assert!(tracker.changes()[2].batch_id == Some(batch2));
    }

    #[test]
    fn test_dependency_graph() {
        let mut table = SymbolTable::new();
        table
            .add_domain(DomainInfo::new("Person", 100))
            .expect("unwrap");
        table
            .add_domain(DomainInfo::new("Location", 50))
            .expect("unwrap");

        let knows = PredicateInfo::new("knows", vec!["Person".to_string(), "Person".to_string()]);
        table.add_predicate(knows).expect("unwrap");

        let at = PredicateInfo::new("at", vec!["Person".to_string(), "Location".to_string()]);
        table.add_predicate(at).expect("unwrap");

        let graph = DependencyGraph::from_symbol_table(&table);

        let person_deps = graph.get_dependent_predicates("Person");
        assert_eq!(person_deps.len(), 2);
        assert!(person_deps.contains("knows"));
        assert!(person_deps.contains("at"));

        let location_deps = graph.get_dependent_predicates("Location");
        assert_eq!(location_deps.len(), 1);
        assert!(location_deps.contains("at"));
    }

    #[test]
    fn test_affected_components() {
        let mut table = SymbolTable::new();
        table
            .add_domain(DomainInfo::new("Person", 100))
            .expect("unwrap");

        let knows = PredicateInfo::new("knows", vec!["Person".to_string(), "Person".to_string()]);
        table.add_predicate(knows).expect("unwrap");

        table.bind_variable("x", "Person").expect("unwrap");

        let graph = DependencyGraph::from_symbol_table(&table);

        let mut initial = HashSet::new();
        initial.insert("Person".to_string());

        let affected = graph.compute_affected_components(&initial);

        assert_eq!(affected.domains.len(), 1);
        assert_eq!(affected.predicates.len(), 1);
        assert_eq!(affected.variables.len(), 1);
        assert!(affected.predicates.contains("knows"));
        assert!(affected.variables.contains("x"));
    }

    #[test]
    fn test_validation_cache() {
        let mut cache = ValidationCache::new();

        cache.cache_domain("Person", vec![]);
        cache.cache_predicate("knows", vec!["Error".to_string()]);

        assert_eq!(cache.get_domain("Person"), Some(&vec![]));
        assert_eq!(
            cache.get_predicate("knows"),
            Some(&vec!["Error".to_string()])
        );
        assert_eq!(cache.get_variable("x"), None);

        let stats = cache.stats();
        assert_eq!(stats.domains_cached, 1);
        assert_eq!(stats.predicates_cached, 1);
        assert_eq!(stats.variables_cached, 0);
    }

    #[test]
    fn test_incremental_validation_basic() {
        let mut table = SymbolTable::new();
        let mut tracker = ChangeTracker::new();

        table
            .add_domain(DomainInfo::new("Person", 100))
            .expect("unwrap");
        tracker.record_domain_addition("Person");

        let mut validator = IncrementalValidator::new(&table, &tracker);
        let report = validator.validate_incremental().expect("unwrap");

        assert!(report.is_valid());
        assert_eq!(report.components_validated, 1);
    }

    #[test]
    fn test_incremental_validation_with_cache() {
        let mut table = SymbolTable::new();
        let mut tracker = ChangeTracker::new();

        // First validation
        table
            .add_domain(DomainInfo::new("Person", 100))
            .expect("unwrap");
        tracker.record_domain_addition("Person");

        let mut validator = IncrementalValidator::new(&table, &tracker);
        let report1 = validator.validate_incremental().expect("unwrap");
        assert_eq!(report1.components_validated, 1);

        // Extract cache before second validation
        let cache = validator.cache.clone();

        // Second validation with cache (use fresh references)
        let mut tracker2 = ChangeTracker::new();
        table
            .add_domain(DomainInfo::new("Location", 50))
            .expect("unwrap");
        tracker2.record_domain_addition("Location");

        let mut validator2 = IncrementalValidator::new(&table, &tracker2).with_cache(cache);
        let report2 = validator2.validate_incremental().expect("unwrap");

        // Only Location should be validated, Person should be cached
        assert_eq!(report2.components_validated, 1);
        assert!(report2.components_cached > 0);
    }

    #[test]
    fn test_change_stats() {
        let mut tracker = ChangeTracker::new();

        tracker.record_domain_addition("Person");
        tracker.record_domain_modification("Person");
        tracker.record_predicate_addition("knows");

        let stats = tracker.stats();
        assert_eq!(stats.total_changes, 3);
        assert_eq!(stats.domains_affected, 1);
        assert_eq!(stats.predicates_affected, 1);
        assert_eq!(stats.changes_by_type.get("DomainAdded"), Some(&1));
        assert_eq!(stats.changes_by_type.get("DomainModified"), Some(&1));
        assert_eq!(stats.changes_by_type.get("PredicateAdded"), Some(&1));
    }

    #[test]
    fn test_incremental_validation_no_changes() {
        let table = SymbolTable::new();
        let tracker = ChangeTracker::new();

        let mut validator = IncrementalValidator::new(&table, &tracker);
        let report = validator.validate_incremental().expect("unwrap");

        assert!(report.is_valid());
        assert_eq!(report.components_validated, 0);
    }
}