xlog-logic 0.9.2

Parser, compiler, and optimizer for XLOG logic programs
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
//! Integration tests for xlog-logic
//!
//! Tests the full compilation pipeline from source to execution plan.

use xlog_logic::{compile, parse_program, stratify, Compiler};

// =============================================================================
// Parsing Tests
// =============================================================================

#[test]
fn test_parse_tc_program() {
    let input = include_str!("logic/tc.xlog");
    let result = parse_program(input);
    assert!(
        result.is_ok(),
        "Failed to parse TC program: {:?}",
        result.err()
    );

    let program = result.unwrap();
    assert_eq!(program.rules.len(), 5); // 3 facts + 2 rules
    assert_eq!(program.queries.len(), 1);
}

#[test]
fn test_parse_stratified_program() {
    let input = include_str!("logic/stratified.xlog");
    let result = parse_program(input);
    assert!(
        result.is_ok(),
        "Failed to parse stratified program: {:?}",
        result.err()
    );

    let program = result.unwrap();
    assert!(program.rules.iter().any(|r| r.has_negation()));
}

#[test]
fn test_parse_aggregate_program() {
    let input = include_str!("logic/aggregates.xlog");
    let result = parse_program(input);
    assert!(
        result.is_ok(),
        "Failed to parse aggregate program: {:?}",
        result.err()
    );

    let program = result.unwrap();
    assert!(program.rules.iter().any(|r| r.has_aggregation()));
}

// =============================================================================
// Stratification Tests
// =============================================================================

#[test]
fn test_stratify_tc_program() {
    let input = include_str!("logic/tc.xlog");
    let program = parse_program(input).expect("Parse failed");
    let result = stratify(&program);
    assert!(
        result.is_ok(),
        "Failed to stratify TC program: {:?}",
        result.err()
    );
}

#[test]
fn test_stratify_negation_program() {
    let input = include_str!("logic/stratified.xlog");
    let program = parse_program(input).expect("Parse failed");
    let result = stratify(&program);
    assert!(
        result.is_ok(),
        "Failed to stratify negation program: {:?}",
        result.err()
    );

    let strata = result.unwrap();
    // Should have at least 2 strata (base predicates + predicates with negation)
    assert!(
        strata.len() >= 2,
        "Expected at least 2 strata for negation program"
    );
}

// =============================================================================
// Full Compilation Tests
// =============================================================================

#[test]
fn test_compile_tc_program() {
    let input = include_str!("logic/tc.xlog");
    let mut compiler = Compiler::new();
    let result = compiler.compile(input);
    assert!(
        result.is_ok(),
        "Failed to compile TC program: {:?}",
        result.err()
    );

    let plan = result.unwrap();
    assert!(!plan.sccs.is_empty(), "Expected SCCs in execution plan");
}

#[test]
fn test_compile_stratified_program() {
    let input = include_str!("logic/stratified.xlog");
    let mut compiler = Compiler::new();
    let result = compiler.compile(input);
    assert!(
        result.is_ok(),
        "Failed to compile stratified program: {:?}",
        result.err()
    );

    let plan = result.unwrap();
    assert!(!plan.strata.is_empty(), "Expected strata in execution plan");
}

#[test]
fn test_compile_aggregate_program() {
    let input = include_str!("logic/aggregates.xlog");
    let mut compiler = Compiler::new();
    let result = compiler.compile(input);
    assert!(
        result.is_ok(),
        "Failed to compile aggregate program: {:?}",
        result.err()
    );
}

#[test]
fn test_compile_desugars_query_to_rule() {
    let input = include_str!("logic/tc.xlog");
    let mut compiler = Compiler::new();
    let plan = compiler.compile(input).expect("Compile failed");

    assert!(
        compiler.schemas().contains_key("__xlog_query_0"),
        "Expected query predicate schema to be inferred"
    );

    let has_query_rule = plan
        .rules_by_scc
        .iter()
        .flatten()
        .any(|r| r.head == "__xlog_query_0");
    assert!(
        has_query_rule,
        "Expected a compiled rule for __xlog_query_0"
    );
}

#[test]
fn test_compile_desugars_constraint_to_rule() {
    let input = r#"
        edge(1, 2).
        edge(2, 3).
        reach(X, Y) :- edge(X, Y).
        reach(X, Z) :- reach(X, Y), edge(Y, Z).
        :- reach(X, X).
    "#;

    let mut compiler = Compiler::new();
    let plan = compiler.compile(input).expect("Compile failed");

    assert!(
        compiler.schemas().contains_key("__xlog_constraint_0"),
        "Expected constraint predicate schema to be inferred"
    );

    let has_constraint_rule = plan
        .rules_by_scc
        .iter()
        .flatten()
        .any(|r| r.head == "__xlog_constraint_0");
    assert!(
        has_constraint_rule,
        "Expected a compiled rule for __xlog_constraint_0"
    );
}

#[test]
fn test_compile_convenience_function() {
    let input = include_str!("logic/tc.xlog");
    let result = compile(input);
    assert!(
        result.is_ok(),
        "Convenience compile failed: {:?}",
        result.err()
    );
}

// =============================================================================
// Error Handling Tests
// =============================================================================

#[test]
fn test_compile_unstratifiable_program() {
    // p depends negatively on q, q depends negatively on p - cycle through negation
    let input = r#"
        p :- not q.
        q :- not p.
    "#;
    let mut compiler = Compiler::new();
    let result = compiler.compile(input);
    assert!(result.is_err(), "Should fail with stratification cycle");
}

#[test]
fn test_compile_syntax_error() {
    let input = "edge(1, 2"; // Missing closing paren and period
    let mut compiler = Compiler::new();
    let result = compiler.compile(input);
    assert!(result.is_err(), "Should fail with syntax error");
}

// =============================================================================
// Learnable Rule Tests (ILP)
// =============================================================================

#[test]
fn test_parse_learnable_rule() {
    let input = include_str!("logic/learnable.xlog");
    let result = parse_program(input);
    assert!(
        result.is_ok(),
        "Failed to parse learnable program: {:?}",
        result.err()
    );

    let program = result.unwrap();
    assert_eq!(program.learnable_rules.len(), 1);

    let lr = &program.learnable_rules[0];
    assert_eq!(lr.mask_name, "W_mask");
    assert_eq!(lr.head.predicate, "reach");
    assert_eq!(lr.head.terms.len(), 2);
    assert_eq!(lr.body.len(), 2);
}

#[test]
fn test_parse_learnable_rule_preserves_normal_rules() {
    let input = include_str!("logic/learnable.xlog");
    let program = parse_program(input).unwrap();

    // 3 facts (edge) are in program.rules
    assert_eq!(program.facts().count(), 3);
    // The learnable rule is NOT in program.rules
    assert_eq!(program.proper_rules().count(), 0);
    // It's in learnable_rules
    assert_eq!(program.learnable_rules.len(), 1);
    // Query still parsed
    assert_eq!(program.queries.len(), 1);
}

#[test]
fn test_stratify_with_learnable_rule() {
    let input = r#"
        edge(1, 2).
        edge(2, 3).
        learnable(W) :: reach(X, Y) :- b1(X, Z), b2(Z, Y).
    "#;
    let program = parse_program(input).unwrap();
    let result = stratify(&program);
    assert!(result.is_ok(), "Stratification failed: {:?}", result.err());
    // Verify the learnable rule's head predicate appears in the strata
    let strata = result.unwrap();
    let all_preds: Vec<&str> = strata
        .iter()
        .flat_map(|s| s.predicates.iter().map(|p| p.as_str()))
        .collect();
    assert!(
        all_preds.contains(&"reach"),
        "Learnable rule head 'reach' should appear in strata, got: {:?}",
        all_preds
    );
    assert!(
        all_preds.contains(&"b1"),
        "Learnable rule body 'b1' should appear in strata, got: {:?}",
        all_preds
    );
    assert!(
        all_preds.contains(&"b2"),
        "Learnable rule body 'b2' should appear in strata, got: {:?}",
        all_preds
    );
}

#[test]
fn test_compile_learnable_rule_produces_tmj() {
    let input = r#"
        edge(1, 2).
        edge(2, 3).
        learnable(W) :: reach(X, Y) :- b1(X, Z), b2(Z, Y).
    "#;
    let mut compiler = Compiler::new();
    let result = compiler.compile(input);
    assert!(result.is_ok(), "Compilation failed: {:?}", result.err());

    // Verify we can find a TensorMaskedJoin in the plan
    let plan = result.unwrap();
    let has_tmj = plan
        .rules_by_scc
        .iter()
        .flatten()
        .any(|rule| matches!(rule.body, xlog_ir::rir::RirNode::TensorMaskedJoin { .. }));
    assert!(has_tmj, "Expected TensorMaskedJoin in compiled plan");
}

#[test]
fn test_learnable_rule_body_validation() {
    // Body must have exactly 2 positive atoms
    let input = r#"
        learnable(W) :: h(X) :- b1(X, Z).
    "#;
    let mut compiler = Compiler::new();
    let result = compiler.compile(input);
    assert!(result.is_err(), "Should reject single-body learnable rule");
}

// =============================================================================
// M1 Gap Tests — Syntax & IR
// =============================================================================

// T1.2: Parse failure on malformed learnable rule
#[test]
fn test_parse_learnable_malformed_fails() {
    // Missing mask name
    let input = "learnable() :: h(X) :- b1(X, Z), b2(Z, Y).";
    assert!(parse_program(input).is_err());

    // Missing :: separator
    let input2 = "learnable(W) h(X,Y) :- b1(X,Z), b2(Z,Y).";
    assert!(parse_program(input2).is_err());
}

// T1.4: referenced_relations() includes all rel_index entries
#[test]
fn test_tmj_referenced_relations_complete() {
    let input = r#"
        edge(1,2).
        learnable(W) :: reach(X, Y) :- b1(X, Z), b2(Z, Y).
    "#;
    let mut compiler = Compiler::new();
    let program = parse_program(input).unwrap();
    let plan = compiler.compile_program(&program).unwrap();

    for rule in plan.rules_by_scc.iter().flatten() {
        if let xlog_ir::rir::RirNode::TensorMaskedJoin { ref rel_index, .. } = rule.body {
            let collected = rule.body.referenced_relations();
            for (rel_id, _) in rel_index {
                assert!(
                    collected.contains(rel_id),
                    "referenced_relations missing RelId {:?}",
                    rel_id
                );
            }
            return;
        }
    }
    panic!("No TensorMaskedJoin found in compiled plan");
}

// T1.8: Optimizer handles TensorMaskedJoin without panic
#[test]
fn test_optimizer_handles_tmj() {
    let input = r#"
        edge(1,2).
        edge(2,3).
        learnable(W) :: reach(X, Y) :- b1(X, Z), b2(Z, Y).
        ?- reach(1, N).
    "#;
    let mut compiler = Compiler::new();
    let program = parse_program(input).unwrap();
    let result = compiler.compile_program(&program);
    assert!(
        result.is_ok(),
        "Optimizer should handle TensorMaskedJoin: {:?}",
        result.err()
    );
}

// T2: Learnable head validation — unbound variable must fail
#[test]
fn test_learnable_head_unbound_variable_fails() {
    let input = r#"
        edge(1, 2).
        learnable(W) :: reach(X, Q) :- b1(X, Z), b2(Z, Y).
    "#;
    let mut compiler = Compiler::new();
    let result = compiler.compile(input);
    assert!(result.is_err(), "Should reject head variable Q not in body");
    let err = result.unwrap_err().to_string();
    assert!(
        err.contains("not found in body"),
        "Error should mention unbound var: {}",
        err
    );
}

// T2: Learnable head validation — constant in head must fail
#[test]
fn test_learnable_head_constant_fails() {
    let input = r#"
        edge(1, 2).
        learnable(W) :: reach(1, Y) :- b1(X, Z), b2(Z, Y).
    "#;
    let mut compiler = Compiler::new();
    let result = compiler.compile(input);
    assert!(result.is_err(), "Should reject constant in learnable head");
    let err = result.unwrap_err().to_string();
    assert!(
        err.contains("only variables"),
        "Error should mention variables-only: {}",
        err
    );
}

// Note: Full execution tests require xlog-cuda and xlog-runtime
// which depend on CUDA hardware. These will be added in later tasks.