shifty-engine 0.2.2

SHACL validation and SHACL-AF inference execution over the IR
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
use oxrdf::{NamedNode, Triple};
use shifty_engine::{infer, validate, validate_report};
use std::path::{Path, PathBuf};

fn fixture(path: &str) -> PathBuf {
    Path::new(env!("CARGO_MANIFEST_DIR"))
        .join("../../testdata")
        .join(path)
}

fn load(path: &str) -> (shifty_parse::Loaded, shifty_parse::ParseOutput) {
    let path = fixture(path).canonicalize().expect("fixture");
    let bytes = std::fs::read(&path).expect("fixture");
    let base = format!("file://{}", path.display());
    let loaded = shifty_parse::load_turtle(&bytes, Some(&base)).expect("valid Turtle");
    let parsed = shifty_parse::parse_turtle(&bytes, Some(&base)).expect("valid shapes");
    assert!(
        parsed.diagnostics.is_empty(),
        "diags: {:?}",
        parsed.diagnostics
    );
    (loaded, parsed)
}

#[test]
fn w3c_node_sparql_constraint() {
    let (loaded, parsed) =
        load("data-shapes/data-shapes-test-suite/tests/sparql/node/sparql-001.ttl");
    let outcome = validate(&loaded.graph, &parsed.schema).expect("stratifiable");
    assert!(!outcome.conforms);
    assert_eq!(outcome.violations.len(), 2);
    assert_eq!(
        outcome
            .violations
            .iter()
            .map(|violation| violation.reasons.len())
            .sum::<usize>(),
        3
    );
}

#[test]
fn w3c_property_sparql_constraint_prebinds_path() {
    let (loaded, parsed) =
        load("data-shapes/data-shapes-test-suite/tests/sparql/property/sparql-001.ttl");
    let outcome = validate(&loaded.graph, &parsed.schema).expect("stratifiable");
    assert!(!outcome.conforms);
    assert_eq!(outcome.violations.len(), 1);
    assert_eq!(outcome.violations[0].reasons.len(), 1);
    assert_eq!(
        outcome.violations[0].reasons[0].value.to_string(),
        "\"Spain\"@en"
    );
}

#[test]
fn w3c_sparql_target() {
    let (loaded, parsed) = load("test-suite/advanced/target/sparqlTarget-001.test.ttl");
    let outcome = validate(&loaded.graph, &parsed.schema).expect("stratifiable");
    assert!(!outcome.conforms);
    assert_eq!(outcome.violations.len(), 1);
    assert_eq!(
        outcome.violations[0].focus.to_string(),
        "<http://datashapes.org/sh/tests/sparql/target/sparqlTarget-001.test#InvalidInstance1>"
    );
}

#[test]
fn w3c_sparql_construct_rule() {
    let (loaded, parsed) = load("test-suite/advanced/rules/sparql/classify-square.test.ttl");
    let outcome = infer(&loaded.graph, &parsed.schema).expect("stratifiable");
    assert!(
        outcome.diagnostics.is_empty(),
        "diags: {:?}",
        outcome.diagnostics
    );
    assert!(outcome.graph.contains(&Triple::new(
        NamedNode::new(
            "http://datashapes.org/shasf/tests/rules/sparql/classify-square.test#SquareRectangle",
        )
        .unwrap(),
        NamedNode::new("http://www.w3.org/1999/02/22-rdf-syntax-ns#type").unwrap(),
        NamedNode::new(
            "http://datashapes.org/shasf/tests/rules/sparql/classify-square.test#Square",
        )
        .unwrap(),
    )));
}

/// SHACL `$PATH` prebinding for complex (non-predicate) property shapes.
/// Each sub-test uses `validate_report` so that `collect_sparql` on the
/// report path exercises the same `compile_constraint` code that the
/// algebra path uses.
mod complex_path_prebinding {
    use super::*;

    fn shapes_data(shapes_ttl: &str) -> shifty_parse::Loaded {
        shifty_parse::load_turtle(shapes_ttl.as_bytes(), None).expect("valid Turtle")
    }

    fn prefix() -> &'static str {
        r#"
        @prefix sh:  <http://www.w3.org/ns/shacl#> .
        @prefix ex:  <http://example.org/> .
        @prefix xsd: <http://www.w3.org/2001/XMLSchema#> .
        "#
    }

    /// `$PATH` is an `sh:alternativePath` — rewrites the BGP triple to a
    /// SPARQL `|` property-path pattern.
    #[test]
    fn alternative_path() {
        let ttl = format!(
            r#"{prefix}
            ex:S a sh:PropertyShape ;
                sh:path [ sh:alternativePath ( ex:p ex:q ) ] ;
                sh:targetClass ex:C ;
                sh:sparql [
                    sh:select """
                        SELECT $this ?value
                        WHERE {{ $this $PATH ?value .
                                 FILTER (isLiteral(?value) && str(?value) = "bad") }}
                    """ ] .
            ex:Good  a ex:C ; ex:p "ok" .
            ex:Bad1  a ex:C ; ex:p "bad" .
            ex:Bad2  a ex:C ; ex:q "bad" .
            "#,
            prefix = prefix()
        );
        let loaded = shapes_data(&ttl);
        let report = validate_report(&loaded, &loaded.graph);
        assert!(!report.conforms);
        let focuses: Vec<_> = report.results.iter().map(|r| r.focus.to_string()).collect();
        assert!(
            focuses.contains(&"<http://example.org/Bad1>".to_string()),
            "{focuses:?}"
        );
        assert!(
            focuses.contains(&"<http://example.org/Bad2>".to_string()),
            "{focuses:?}"
        );
        assert!(
            !focuses.contains(&"<http://example.org/Good>".to_string()),
            "{focuses:?}"
        );
    }

    /// `$PATH` is an `sh:inversePath` — rewrites to `^ex:p`.
    #[test]
    fn inverse_path() {
        let ttl = format!(
            r#"{prefix}
            ex:S a sh:PropertyShape ;
                sh:path [ sh:inversePath ex:child ] ;
                sh:targetClass ex:Person ;
                sh:sparql [
                    sh:select """
                        SELECT $this ?value
                        WHERE {{ $this $PATH ?value .
                                 FILTER (!isIRI(?value)) }}
                    """ ] .
            ex:Alice a ex:Person .
            ex:Bob   a ex:Person ; ex:child ex:Alice .
            "#,
            prefix = prefix()
        );
        let loaded = shapes_data(&ttl);
        let report = validate_report(&loaded, &loaded.graph);
        // ex:Alice has ex:Bob as inverse-child (ex:Bob ex:child ex:Alice)
        // ex:Bob has no inverse-child
        // The constraint fires when the value node is not an IRI, but
        // ex:Bob is an IRI, so nothing should violate.
        assert!(report.conforms, "results: {:?}", report.results);
    }

    /// `$PATH` is an `sh:sequencePath` — rewrites to `ex:p/ex:q`.
    #[test]
    fn sequence_path() {
        let ttl = format!(
            r#"{prefix}
            ex:S a sh:PropertyShape ;
                sh:path ( ex:p ex:q ) ;
                sh:targetClass ex:C ;
                sh:sparql [
                    sh:select """
                        SELECT $this ?value
                        WHERE {{ $this $PATH ?value .
                                 FILTER (str(?value) = "bad") }}
                    """ ] .
            ex:Good a ex:C ; ex:p [ ex:q "ok" ] .
            ex:Bad  a ex:C ; ex:p [ ex:q "bad" ] .
            "#,
            prefix = prefix()
        );
        let loaded = shapes_data(&ttl);
        let report = validate_report(&loaded, &loaded.graph);
        assert!(!report.conforms);
        let focuses: Vec<_> = report.results.iter().map(|r| r.focus.to_string()).collect();
        assert!(
            focuses.contains(&"<http://example.org/Bad>".to_string()),
            "{focuses:?}"
        );
        assert!(
            !focuses.contains(&"<http://example.org/Good>".to_string()),
            "{focuses:?}"
        );
    }

    /// `$PATH` is an `sh:zeroOrMorePath` — rewrites to `ex:p*`.
    #[test]
    fn zero_or_more_path() {
        let ttl = format!(
            r#"{prefix}
            ex:S a sh:PropertyShape ;
                sh:path [ sh:zeroOrMorePath ex:next ] ;
                sh:targetClass ex:Node ;
                sh:sparql [
                    sh:select """
                        SELECT $this ?value
                        WHERE {{ $this $PATH ?value .
                                 FILTER (?value = ex:Sink) }}
                    """ ] .
            ex:A a ex:Node ; ex:next ex:B .
            ex:B a ex:Node ; ex:next ex:Sink .
            ex:Sink a ex:Node .
            "#,
            prefix = prefix()
        );
        let loaded = shapes_data(&ttl);
        let report = validate_report(&loaded, &loaded.graph);
        // ex:A and ex:B can reach ex:Sink via ex:next*; ex:Sink reaches itself.
        // All three violate the constraint (they all reach ex:Sink).
        assert!(!report.conforms);
        let focuses: Vec<_> = report.results.iter().map(|r| r.focus.to_string()).collect();
        assert!(
            focuses.contains(&"<http://example.org/A>".to_string()),
            "{focuses:?}"
        );
        assert!(
            focuses.contains(&"<http://example.org/B>".to_string()),
            "{focuses:?}"
        );
    }
}

#[test]
fn construct_blank_nodes_are_rejected_to_preserve_termination() {
    let ttl = br#"
        @prefix sh: <http://www.w3.org/ns/shacl#> .
        @prefix ex: <http://ex/> .
        ex:S a sh:NodeShape ;
            sh:targetNode ex:x ;
            sh:rule [
                a sh:SPARQLRule ;
                sh:construct "CONSTRUCT { $this ex:p [] } WHERE {}"
            ] .
    "#;
    let loaded = shifty_parse::load_turtle(ttl, None).expect("valid Turtle");
    let parsed = shifty_parse::parse_turtle(ttl, None).expect("valid shapes");
    let outcome = infer(&loaded.graph, &parsed.schema).expect("stratifiable");
    assert!(outcome.inferred.is_empty());
    assert!(
        outcome
            .diagnostics
            .iter()
            .any(|message| message.contains("blank nodes"))
    );
}

/// A CONSTRUCT rule whose body has a `GROUP BY`/`COUNT` aggregate cannot lower to
/// the native executor, so it runs on the Spareval fallback. This checks the
/// aggregate is evaluated correctly end-to-end through `infer`: only the focus
/// whose grouped distinct count is 1 gets the inferred triple. (The free-`?this`
/// batched path that large focus sets take is covered deterministically by the
/// `batched_construct_matches_per_focus` unit test in `sparql.rs`.)
#[test]
fn aggregate_construct_rule_infers_only_eligible_focus() {
    let ttl = br#"
        @prefix sh: <http://www.w3.org/ns/shacl#> .
        @prefix ex: <http://ex/> .

        ex:MeterShape a sh:NodeShape ;
            sh:targetClass ex:Meter ;
            sh:rule [
                a sh:SPARQLRule ;
                sh:construct """
                    CONSTRUCT { $this ex:uniqueKind ?k }
                    WHERE {
                        { SELECT $this (COUNT(DISTINCT ?k0) AS ?c)
                          WHERE { $this ex:reads/ex:kind ?k0 }
                          GROUP BY $this }
                        FILTER(?c = 1)
                        $this ex:reads/ex:kind ?k .
                    }
                """
            ] .

        # M1 reads two properties of the same kind -> distinct count 1 -> inferred.
        ex:M1 a ex:Meter ; ex:reads ex:p1, ex:p2 .
        ex:p1 ex:kind ex:Temp .
        ex:p2 ex:kind ex:Temp .

        # M2 reads two properties of different kinds -> count 2 -> not inferred.
        ex:M2 a ex:Meter ; ex:reads ex:q1, ex:q2 .
        ex:q1 ex:kind ex:Temp .
        ex:q2 ex:kind ex:Flow .
    "#;
    let loaded = shifty_parse::load_turtle(ttl, None).expect("valid Turtle");
    let parsed = shifty_parse::parse_turtle(ttl, None).expect("valid shapes");
    let outcome = infer(&loaded.graph, &parsed.schema).expect("stratifiable");
    assert!(
        outcome.diagnostics.is_empty(),
        "diags: {:?}",
        outcome.diagnostics
    );

    let unique_kind = NamedNode::new("http://ex/uniqueKind").unwrap();
    let m1 = NamedNode::new("http://ex/M1").unwrap();
    let m2 = NamedNode::new("http://ex/M2").unwrap();
    let temp = NamedNode::new("http://ex/Temp").unwrap();

    // M1 (grouped count 1) gets the triple; M2 (grouped count 2) does not.
    assert!(
        outcome
            .graph
            .contains(&Triple::new(m1, unique_kind.clone(), temp))
    );
    assert!(
        !outcome
            .inferred
            .iter()
            .any(|t| t.subject == m2.clone().into() && t.predicate == unique_kind)
    );
    // Exactly one triple is inferred (M1 ex:uniqueKind ex:Temp).
    assert_eq!(
        outcome.inferred.len(),
        1,
        "inferred: {:?}",
        outcome.inferred
    );
}

/// All reason messages produced by the plan-path validator for `ttl`.
fn reason_messages(ttl: &[u8]) -> Vec<String> {
    let loaded = shifty_parse::load_turtle(ttl, None).expect("valid Turtle");
    let parsed = shifty_parse::parse_turtle(ttl, None).expect("valid shapes");
    assert!(
        parsed.diagnostics.is_empty(),
        "diags: {:?}",
        parsed.diagnostics
    );
    let outcome = validate(&loaded.graph, &parsed.schema).expect("stratifiable");
    assert!(!outcome.conforms);
    outcome
        .violations
        .iter()
        .flat_map(|v| v.reasons.iter().map(|r| r.message.clone()))
        .collect()
}

#[test]
fn sparql_violation_uses_message_binding() {
    // A `?message` binding in the SELECT result is the violation message.
    let ttl = br#"
        @prefix sh: <http://www.w3.org/ns/shacl#> .
        @prefix ex: <http://ex/> .
        ex:AgeShape a sh:NodeShape ;
            sh:targetNode ex:bob ;
            sh:sparql [
                a sh:SPARQLConstraint ;
                sh:select "SELECT $this ?value ?message WHERE { $this <http://ex/age> ?value . FILTER(?value < 0) BIND(CONCAT('age is negative: ', STR(?value)) AS ?message) }"
            ] .
        ex:bob <http://ex/age> -5 .
    "#;
    assert_eq!(reason_messages(ttl), vec!["age is negative: -5"]);
}

#[test]
fn sparql_violation_falls_back_to_sh_message() {
    // No `?message` binding → the constraint's `sh:message` is used.
    let ttl = br#"
        @prefix sh: <http://www.w3.org/ns/shacl#> .
        @prefix ex: <http://ex/> .
        ex:AgeShape a sh:NodeShape ;
            sh:targetNode ex:bob ;
            sh:sparql [
                a sh:SPARQLConstraint ;
                sh:message "Age must not be negative" ;
                sh:select "SELECT $this ?value WHERE { $this <http://ex/age> ?value . FILTER(?value < 0) }"
            ] .
        ex:bob <http://ex/age> -5 .
    "#;
    assert_eq!(reason_messages(ttl), vec!["Age must not be negative"]);
}

#[test]
fn sparql_violation_default_names_shape() {
    // Neither `?message` nor `sh:message` → a constructed message naming the shape.
    let ttl = br#"
        @prefix sh: <http://www.w3.org/ns/shacl#> .
        @prefix ex: <http://ex/> .
        ex:AgeShape a sh:NodeShape ;
            sh:targetNode ex:bob ;
            sh:sparql [
                a sh:SPARQLConstraint ;
                sh:select "SELECT $this ?value WHERE { $this <http://ex/age> ?value . FILTER(?value < 0) }"
            ] .
        ex:bob <http://ex/age> -5 .
    "#;
    let messages = reason_messages(ttl);
    assert_eq!(messages.len(), 1);
    assert!(
        messages[0].contains("SPARQL constraint at") && messages[0].contains("http://ex/AgeShape"),
        "unexpected default message: {}",
        messages[0]
    );
}