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
//! Advanced schema merging strategies for combining schemas from different sources.
//!
//! This module provides sophisticated strategies for merging symbol tables with
//! conflict resolution, validation, and detailed merge reports.

use crate::{DomainInfo, PredicateInfo, SymbolTable};
use anyhow::{bail, Result};
use std::collections::HashSet;

/// Strategy for resolving conflicts during schema merging.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MergeStrategy {
    /// Keep the first (base) version in case of conflict
    KeepFirst,
    /// Keep the second (incoming) version in case of conflict
    KeepSecond,
    /// Fail on any conflict
    FailOnConflict,
    /// Union: Keep both if compatible, fail if incompatible
    Union,
    /// Intersection: Only keep items present in both with compatible definitions
    Intersection,
}

/// Result of a merge operation.
#[derive(Debug, Clone)]
pub struct MergeResult {
    /// The merged symbol table
    pub merged: SymbolTable,
    /// Report of the merge operation
    pub report: MergeReport,
}

/// Report of a merge operation.
#[derive(Debug, Clone)]
pub struct MergeReport {
    /// Domains that were added from base
    pub base_domains: Vec<String>,
    /// Domains that were added from incoming
    pub incoming_domains: Vec<String>,
    /// Domains that had conflicts
    pub conflicting_domains: Vec<DomainConflict>,
    /// Predicates that were added from base
    pub base_predicates: Vec<String>,
    /// Predicates that were added from incoming
    pub incoming_predicates: Vec<String>,
    /// Predicates that had conflicts
    pub conflicting_predicates: Vec<PredicateConflict>,
    /// Variables that were merged
    pub merged_variables: Vec<String>,
    /// Variables that had conflicts
    pub conflicting_variables: Vec<VariableConflict>,
    /// Overall merge strategy used
    pub strategy: MergeStrategy,
}

impl MergeReport {
    /// Create a new empty merge report.
    pub fn new(strategy: MergeStrategy) -> Self {
        Self {
            base_domains: Vec::new(),
            incoming_domains: Vec::new(),
            conflicting_domains: Vec::new(),
            base_predicates: Vec::new(),
            incoming_predicates: Vec::new(),
            conflicting_predicates: Vec::new(),
            merged_variables: Vec::new(),
            conflicting_variables: Vec::new(),
            strategy,
        }
    }

    /// Check if there were any conflicts during merging.
    pub fn has_conflicts(&self) -> bool {
        !self.conflicting_domains.is_empty()
            || !self.conflicting_predicates.is_empty()
            || !self.conflicting_variables.is_empty()
    }

    /// Get total number of conflicts.
    pub fn conflict_count(&self) -> usize {
        self.conflicting_domains.len()
            + self.conflicting_predicates.len()
            + self.conflicting_variables.len()
    }

    /// Get total number of merged items.
    pub fn merged_count(&self) -> usize {
        self.base_domains.len()
            + self.incoming_domains.len()
            + self.base_predicates.len()
            + self.incoming_predicates.len()
            + self.merged_variables.len()
    }
}

/// Information about a domain conflict.
#[derive(Debug, Clone)]
pub struct DomainConflict {
    /// Name of the conflicting domain
    pub name: String,
    /// Domain from base table
    pub base: DomainInfo,
    /// Domain from incoming table
    pub incoming: DomainInfo,
    /// How the conflict was resolved
    pub resolution: MergeConflictResolution,
}

/// Information about a predicate conflict.
#[derive(Debug, Clone)]
pub struct PredicateConflict {
    /// Name of the conflicting predicate
    pub name: String,
    /// Predicate from base table
    pub base: PredicateInfo,
    /// Predicate from incoming table
    pub incoming: PredicateInfo,
    /// How the conflict was resolved
    pub resolution: MergeConflictResolution,
}

/// Information about a variable conflict.
#[derive(Debug, Clone)]
pub struct VariableConflict {
    /// Name of the conflicting variable
    pub name: String,
    /// Domain from base table
    pub base_domain: String,
    /// Domain from incoming table
    pub incoming_domain: String,
    /// How the conflict was resolved
    pub resolution: MergeConflictResolution,
}

/// How a merge conflict was resolved.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MergeConflictResolution {
    /// Kept the base version
    KeptBase,
    /// Kept the incoming version
    KeptIncoming,
    /// Failed to resolve
    Failed,
    /// Merged both (only for compatible items)
    Merged,
}

/// A schema merger with configurable strategies.
pub struct SchemaMerger {
    strategy: MergeStrategy,
}

impl SchemaMerger {
    /// Create a new schema merger with the given strategy.
    pub fn new(strategy: MergeStrategy) -> Self {
        Self { strategy }
    }

    /// Merge two symbol tables according to the configured strategy.
    ///
    /// # Examples
    ///
    /// ```
    /// use tensorlogic_adapters::{SymbolTable, DomainInfo, SchemaMerger, MergeStrategy};
    ///
    /// let mut base = SymbolTable::new();
    /// base.add_domain(DomainInfo::new("Person", 100)).expect("unwrap");
    ///
    /// let mut incoming = SymbolTable::new();
    /// incoming.add_domain(DomainInfo::new("Organization", 50)).expect("unwrap");
    ///
    /// let merger = SchemaMerger::new(MergeStrategy::Union);
    /// let result = merger.merge(&base, &incoming).expect("unwrap");
    ///
    /// assert_eq!(result.merged.domains.len(), 2);
    /// ```
    pub fn merge(&self, base: &SymbolTable, incoming: &SymbolTable) -> Result<MergeResult> {
        let mut merged = SymbolTable::new();
        let mut report = MergeReport::new(self.strategy);

        // Merge domains
        self.merge_domains(base, incoming, &mut merged, &mut report)?;

        // Merge predicates
        self.merge_predicates(base, incoming, &mut merged, &mut report)?;

        // Merge variables
        self.merge_variables(base, incoming, &mut merged, &mut report)?;

        Ok(MergeResult { merged, report })
    }

    fn merge_domains(
        &self,
        base: &SymbolTable,
        incoming: &SymbolTable,
        merged: &mut SymbolTable,
        report: &mut MergeReport,
    ) -> Result<()> {
        let base_keys: HashSet<&String> = base.domains.keys().collect();
        let incoming_keys: HashSet<&String> = incoming.domains.keys().collect();

        // Domains only in base
        for key in base_keys.difference(&incoming_keys) {
            let domain = base
                .domains
                .get(*key)
                .expect("key from HashMap iteration is always present");
            merged.add_domain(domain.clone())?;
            report.base_domains.push(key.to_string());
        }

        // Domains only in incoming
        for key in incoming_keys.difference(&base_keys) {
            let domain = incoming
                .domains
                .get(*key)
                .expect("key from HashMap iteration is always present");
            merged.add_domain(domain.clone())?;
            report.incoming_domains.push(key.to_string());
        }

        // Domains in both (conflicts)
        for key in base_keys.intersection(&incoming_keys) {
            let base_domain = base
                .domains
                .get(*key)
                .expect("key from HashMap iteration is always present");
            let incoming_domain = incoming
                .domains
                .get(*key)
                .expect("key from HashMap iteration is always present");

            let (domain, resolution) =
                self.resolve_domain_conflict(base_domain, incoming_domain)?;

            merged.add_domain(domain)?;

            if resolution != MergeConflictResolution::Merged {
                report.conflicting_domains.push(DomainConflict {
                    name: key.to_string(),
                    base: base_domain.clone(),
                    incoming: incoming_domain.clone(),
                    resolution,
                });
            }
        }

        Ok(())
    }

    fn merge_predicates(
        &self,
        base: &SymbolTable,
        incoming: &SymbolTable,
        merged: &mut SymbolTable,
        report: &mut MergeReport,
    ) -> Result<()> {
        let base_keys: HashSet<&String> = base.predicates.keys().collect();
        let incoming_keys: HashSet<&String> = incoming.predicates.keys().collect();

        // Predicates only in base
        for key in base_keys.difference(&incoming_keys) {
            let predicate = base
                .predicates
                .get(*key)
                .expect("key from HashMap iteration is always present");
            merged.add_predicate(predicate.clone())?;
            report.base_predicates.push(key.to_string());
        }

        // Predicates only in incoming
        for key in incoming_keys.difference(&base_keys) {
            let predicate = incoming
                .predicates
                .get(*key)
                .expect("key from HashMap iteration is always present");
            merged.add_predicate(predicate.clone())?;
            report.incoming_predicates.push(key.to_string());
        }

        // Predicates in both (conflicts)
        for key in base_keys.intersection(&incoming_keys) {
            let base_pred = base
                .predicates
                .get(*key)
                .expect("key from HashMap iteration is always present");
            let incoming_pred = incoming
                .predicates
                .get(*key)
                .expect("key from HashMap iteration is always present");

            let (predicate, resolution) =
                self.resolve_predicate_conflict(base_pred, incoming_pred)?;

            merged.add_predicate(predicate)?;

            if resolution != MergeConflictResolution::Merged {
                report.conflicting_predicates.push(PredicateConflict {
                    name: key.to_string(),
                    base: base_pred.clone(),
                    incoming: incoming_pred.clone(),
                    resolution,
                });
            }
        }

        Ok(())
    }

    fn merge_variables(
        &self,
        base: &SymbolTable,
        incoming: &SymbolTable,
        merged: &mut SymbolTable,
        report: &mut MergeReport,
    ) -> Result<()> {
        let base_keys: HashSet<&String> = base.variables.keys().collect();
        let incoming_keys: HashSet<&String> = incoming.variables.keys().collect();

        // Variables only in base
        for key in base_keys.difference(&incoming_keys) {
            let domain = base
                .variables
                .get(*key)
                .expect("key from HashMap iteration is always present");
            merged.bind_variable(key.to_string(), domain.clone())?;
            report.merged_variables.push(key.to_string());
        }

        // Variables only in incoming
        for key in incoming_keys.difference(&base_keys) {
            let domain = incoming
                .variables
                .get(*key)
                .expect("key from HashMap iteration is always present");
            merged.bind_variable(key.to_string(), domain.clone())?;
            report.merged_variables.push(key.to_string());
        }

        // Variables in both (conflicts)
        for key in base_keys.intersection(&incoming_keys) {
            let base_domain = base
                .variables
                .get(*key)
                .expect("key from HashMap iteration is always present");
            let incoming_domain = incoming
                .variables
                .get(*key)
                .expect("key from HashMap iteration is always present");

            let (domain, resolution) =
                self.resolve_variable_conflict(base_domain, incoming_domain)?;

            merged.bind_variable(key.to_string(), domain)?;

            if resolution != MergeConflictResolution::Merged {
                report.conflicting_variables.push(VariableConflict {
                    name: key.to_string(),
                    base_domain: base_domain.clone(),
                    incoming_domain: incoming_domain.clone(),
                    resolution,
                });
            }
        }

        Ok(())
    }

    fn resolve_domain_conflict(
        &self,
        base: &DomainInfo,
        incoming: &DomainInfo,
    ) -> Result<(DomainInfo, MergeConflictResolution)> {
        match self.strategy {
            MergeStrategy::KeepFirst => Ok((base.clone(), MergeConflictResolution::KeptBase)),
            MergeStrategy::KeepSecond => {
                Ok((incoming.clone(), MergeConflictResolution::KeptIncoming))
            }
            MergeStrategy::FailOnConflict => {
                bail!(
                    "Domain conflict for '{}': cardinality {} vs {}",
                    base.name,
                    base.cardinality,
                    incoming.cardinality
                )
            }
            MergeStrategy::Union => {
                // For domains, union means take the larger cardinality
                if base.cardinality >= incoming.cardinality {
                    Ok((base.clone(), MergeConflictResolution::KeptBase))
                } else {
                    Ok((incoming.clone(), MergeConflictResolution::KeptIncoming))
                }
            }
            MergeStrategy::Intersection => {
                // For domains, intersection means take the smaller cardinality
                if base.cardinality <= incoming.cardinality {
                    Ok((base.clone(), MergeConflictResolution::KeptBase))
                } else {
                    Ok((incoming.clone(), MergeConflictResolution::KeptIncoming))
                }
            }
        }
    }

    fn resolve_predicate_conflict(
        &self,
        base: &PredicateInfo,
        incoming: &PredicateInfo,
    ) -> Result<(PredicateInfo, MergeConflictResolution)> {
        // Check if predicates are compatible (same signature)
        let compatible = base.arg_domains == incoming.arg_domains;

        match self.strategy {
            MergeStrategy::KeepFirst => Ok((base.clone(), MergeConflictResolution::KeptBase)),
            MergeStrategy::KeepSecond => {
                Ok((incoming.clone(), MergeConflictResolution::KeptIncoming))
            }
            MergeStrategy::FailOnConflict => {
                bail!(
                    "Predicate conflict for '{}': {:?} vs {:?}",
                    base.name,
                    base.arg_domains,
                    incoming.arg_domains
                )
            }
            MergeStrategy::Union => {
                if compatible {
                    Ok((base.clone(), MergeConflictResolution::Merged))
                } else {
                    bail!(
                        "Incompatible predicate signatures for '{}': {:?} vs {:?}",
                        base.name,
                        base.arg_domains,
                        incoming.arg_domains
                    )
                }
            }
            MergeStrategy::Intersection => {
                if compatible {
                    Ok((base.clone(), MergeConflictResolution::Merged))
                } else {
                    bail!(
                        "Incompatible predicate signatures for '{}': {:?} vs {:?}",
                        base.name,
                        base.arg_domains,
                        incoming.arg_domains
                    )
                }
            }
        }
    }

    fn resolve_variable_conflict(
        &self,
        base_domain: &str,
        incoming_domain: &str,
    ) -> Result<(String, MergeConflictResolution)> {
        match self.strategy {
            MergeStrategy::KeepFirst => {
                Ok((base_domain.to_string(), MergeConflictResolution::KeptBase))
            }
            MergeStrategy::KeepSecond => Ok((
                incoming_domain.to_string(),
                MergeConflictResolution::KeptIncoming,
            )),
            MergeStrategy::FailOnConflict => {
                bail!(
                    "Variable domain conflict: '{}' vs '{}'",
                    base_domain,
                    incoming_domain
                )
            }
            MergeStrategy::Union | MergeStrategy::Intersection => {
                if base_domain == incoming_domain {
                    Ok((base_domain.to_string(), MergeConflictResolution::Merged))
                } else {
                    bail!(
                        "Incompatible variable domains: '{}' vs '{}'",
                        base_domain,
                        incoming_domain
                    )
                }
            }
        }
    }
}

impl Default for SchemaMerger {
    fn default() -> Self {
        Self::new(MergeStrategy::Union)
    }
}

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

    fn create_base_table() -> SymbolTable {
        let mut table = SymbolTable::new();
        table
            .add_domain(DomainInfo::new("Person", 100))
            .expect("unwrap");
        table
            .add_predicate(PredicateInfo::new(
                "knows",
                vec!["Person".to_string(), "Person".to_string()],
            ))
            .expect("unwrap");
        table.bind_variable("x", "Person").expect("unwrap");
        table
    }

    fn create_incoming_table() -> SymbolTable {
        let mut table = SymbolTable::new();
        table
            .add_domain(DomainInfo::new("Person", 150))
            .expect("unwrap"); // Different cardinality
        table
            .add_domain(DomainInfo::new("Organization", 50))
            .expect("unwrap");
        table
            .add_predicate(PredicateInfo::new("age", vec!["Person".to_string()]))
            .expect("unwrap");
        table
    }

    #[test]
    fn test_merge_union_no_conflicts() {
        let base = create_base_table();
        let incoming = create_incoming_table();

        let merger = SchemaMerger::new(MergeStrategy::Union);
        let result = merger.merge(&base, &incoming).expect("unwrap");

        assert_eq!(result.merged.domains.len(), 2); // Person (larger card.) + Organization
        assert_eq!(result.merged.predicates.len(), 2); // knows + age
                                                       // Person domain has conflict but will be resolved by taking larger cardinality
        assert!(result.report.has_conflicts()); // Person domain conflict
    }

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

        let mut incoming = SymbolTable::new();
        incoming
            .add_domain(DomainInfo::new("Person", 200))
            .expect("unwrap");

        let merger = SchemaMerger::new(MergeStrategy::KeepFirst);
        let result = merger.merge(&base, &incoming).expect("unwrap");

        assert_eq!(result.merged.domains.len(), 1);
        assert_eq!(
            result
                .merged
                .domains
                .get("Person")
                .expect("unwrap")
                .cardinality,
            100
        );
        assert!(result.report.has_conflicts());
    }

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

        let mut incoming = SymbolTable::new();
        incoming
            .add_domain(DomainInfo::new("Person", 200))
            .expect("unwrap");

        let merger = SchemaMerger::new(MergeStrategy::KeepSecond);
        let result = merger.merge(&base, &incoming).expect("unwrap");

        assert_eq!(
            result
                .merged
                .domains
                .get("Person")
                .expect("unwrap")
                .cardinality,
            200
        );
    }

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

        let mut incoming = SymbolTable::new();
        incoming
            .add_domain(DomainInfo::new("Person", 200))
            .expect("unwrap");

        let merger = SchemaMerger::new(MergeStrategy::FailOnConflict);
        let result = merger.merge(&base, &incoming);

        assert!(result.is_err());
    }

    #[test]
    fn test_merge_report() {
        let base = create_base_table();
        let incoming = create_incoming_table();

        let merger = SchemaMerger::new(MergeStrategy::Union);
        let result = merger.merge(&base, &incoming).expect("unwrap");

        let report = &result.report;
        // Base has Person (no unique domains after merge since incoming also has Person)
        assert_eq!(report.base_domains.len(), 0);
        // Incoming has Organization (unique)
        assert_eq!(report.incoming_domains.len(), 1);
        // merged_count = base_domains (0) + incoming_domains (1) + base_predicates (1) + incoming_predicates (1) + merged_variables (1)
        assert_eq!(report.merged_count(), 4);
        assert_eq!(report.conflict_count(), 1); // Person domain conflict
    }

    #[test]
    fn test_predicate_conflict_compatible() {
        let mut base = SymbolTable::new();
        base.add_domain(DomainInfo::new("Person", 100))
            .expect("unwrap");
        base.add_predicate(PredicateInfo::new("age", vec!["Person".to_string()]))
            .expect("unwrap");

        let mut incoming = SymbolTable::new();
        incoming
            .add_domain(DomainInfo::new("Person", 100))
            .expect("unwrap");
        incoming
            .add_predicate(PredicateInfo::new("age", vec!["Person".to_string()]))
            .expect("unwrap");

        let merger = SchemaMerger::new(MergeStrategy::Union);
        let result = merger.merge(&base, &incoming).expect("unwrap");

        assert_eq!(result.merged.predicates.len(), 1);
        assert_eq!(result.report.conflicting_predicates.len(), 0);
    }

    #[test]
    fn test_variable_conflict() {
        let mut base = SymbolTable::new();
        base.add_domain(DomainInfo::new("Person", 100))
            .expect("unwrap");
        base.add_domain(DomainInfo::new("Agent", 50))
            .expect("unwrap");
        base.bind_variable("x", "Person").expect("unwrap");

        let mut incoming = SymbolTable::new();
        incoming
            .add_domain(DomainInfo::new("Person", 100))
            .expect("unwrap");
        incoming
            .add_domain(DomainInfo::new("Agent", 50))
            .expect("unwrap");
        incoming.bind_variable("x", "Agent").expect("unwrap");

        let merger = SchemaMerger::new(MergeStrategy::KeepFirst);
        let result = merger.merge(&base, &incoming).expect("unwrap");

        assert_eq!(result.merged.variables.get("x").expect("unwrap"), "Person");
        assert_eq!(result.report.conflicting_variables.len(), 1);
    }
}