Skip to content

[mirror] fix(shaclgen): keep the bounds of any_of branches and of types - #75

Open
jdsika wants to merge 1 commit into
mainfrom
fix/shaclgen-any-of-bounds
Open

jdsika wants to merge 1 commit into
mainfrom
fix/shaclgen-any-of-bounds

Conversation

@jdsika

@jdsika jdsika commented Dec 3, 2026

Copy link
Copy Markdown

Mirror of linkml#4335, same head. Review there; this PR tracks the fork stack.

The description below is the one on linkml#4335.

Summary

Fixes # (no issue yet; I ran into this while generating the SHACL shapes for ASCS-eV/ontology-management-base#81, where values that linkml-validate rejects passed SHACL validation)

gen-shacl drops minimum_value / maximum_value in two places:

  • on an any_of branch: only the branch's pattern reaches its sh:or node;
  • on a type: _add_type writes the type's datatype and pattern but not its bounds, although TypeDefinition has both slots and inherits them along typeof.

Writing those bounds brings up two problems with how gen-shacl writes bounds in general:

  • a type and the slot that uses it can each have a bound, but a SHACL shape has at most one sh:minInclusive;
  • a bound is written as Literal(value), so its datatype comes from the Python value, not from the range. A decimal slot gets "0.1"^^xsd:double, and a numeric bound on a string slot rejects every string.

In plain words

A schema can say "this number is between 0 and 100" on a type such as Percentage, or on one option of an any_of. linkml-validate enforces that. The SHACL that gen-shacl writes for the same schema doesn't, so data that linkml-validate rejects passes SHACL validation. This PR writes those limits into the shapes, and writes each one in a form SHACL can compare with the data. A limit that SHACL can't compare with the data would reject every value, so gen-shacl skips it and logs a warning.

Reproduce

bounds.yaml:

id: https://example.org/bounds
name: bounds
prefixes:
  linkml: https://w3id.org/linkml/
  ex: https://example.org/bounds/
default_prefix: ex
default_range: string
imports:
  - linkml:types
types:
  Percentage:
    typeof: decimal
    minimum_value: 0
    maximum_value: 100
  Noughties:
    typeof: date
    minimum_value: "2000-01-01"
    maximum_value: "2009-12-31"
classes:
  Interval:
    attributes:
      low:
        range: integer
  Lane:
    attributes:
      count:
        any_of:
          - range: integer
            minimum_value: 1
          - range: Interval
      share:
        range: Percentage
      occupancy:
        any_of:
          - range: Percentage
          - range: Interval
      opened:
        range: Noughties
      pass_mark:
        range: Percentage
        minimum_value: 50
      code:
        range: string
        minimum_value: 1

For each case, e.g. count-0.yaml containing count: 0:

gen-shacl bounds.yaml > bounds.shacl.ttl
linkml-validate -s bounds.yaml -C Lane count-0.yaml
linkml-convert --no-validate -s bounds.yaml -C Lane -t ttl -o count-0.ttl count-0.yaml
pyshacl -s bounds.shacl.ttl count-0.ttl
data schema says linkml-validate gen-shacl main (fb4339c) this PR
count: 1, share: 50, occupancy: 50, opened: 2005-06-01, pass_mark: 75 valid valid conforms conforms
count: 0 invalid invalid conforms violation
share: 100.5 invalid invalid conforms violation
occupancy: 101 invalid invalid conforms violation
opened: 2010-01-01 invalid valid ¹ conforms violation
pass_mark: 49 invalid invalid violation violation
pass_mark: 100.5 invalid invalid conforms violation
code: abc valid valid violation conforms ²

¹ linkml-validate goes through JSON Schema, which has no bounds for dates.
² main writes sh:minInclusive 1 on a string property, and no string compares with 1. This PR skips the bound with WARNING: Range 'string' has bound 1, which SHACL cannot compare with values of datatype http://www.w3.org/2001/XMLSchema#string; skipping it.

A decimal range, score: {range: decimal, minimum_value: 0.1, maximum_value: 0.3}, with the data as xsd:decimal literals (ex:score 0.1), on pySHACL 0.40.2 and rudof (pyrudof 0.3.42):

ex:score main: "0.1"^^xsd:double … pySHACL main … rudof this PR: 0.1 … pySHACL this PR … rudof
0.1 violation conforms conforms conforms
0.3 violation conforms conforms conforms

I used hand-written Turtle for this one because linkml-convert writes the YAML 0.3 as 0.299999999999999988897769753748434595763683319091796875, which is a separate issue.

Why this is wrong

  • LinkML minimum_value: "For ordinal ranges, the value must be equal to or higher than this". It is a slot of AnonymousSlotExpression (an any_of member) and of TypeDefinition, and types inherit it along typeof. gen-json-schema already writes both.
  • LinkML constraints are monotonic: "it's not possible to override existing constraints, new constraints are always additive and "layered on"". The bound of a type and the bound of a slot using it both hold, so the tighter one decides.
  • SHACL §4.3.2: "A shape has at most one value for sh:minInclusive", and "For each value node v where the SPARQL expression $minInclusive <= v does not return true, there is a validation result with v as sh:value." §4.3.4 says the same for sh:maxInclusive.
  • SPARQL 1.1 §17.3 defines <= for numerics, simple literals and xsd:string, xsd:boolean and xsd:dateTime. Any other pair is a type error, which "does not return true", so every value is a violation. pySHACL 0.40.2 and rudof 0.3.42 both also order xsd:date and xsd:time as XPath does (op:date-less-than, op:time-less-than). For xsd:gYear, which XPath only defines equality for, they disagree: pySHACL rejects "2000"^^xsd:gYear against sh:minInclusive "1900"^^xsd:gYear, while rudof accepts it.
  • XSD 1.1 §3.3.3.1: the decimal lexical space has no exponent form, so "1e-07"^^xsd:decimal is ill-typed.

The change

  • An any_of branch gets sh:minInclusive / sh:maxInclusive on its node, next to its sh:pattern.
  • _add_type takes the bounds of the slot or branch whose range is the type, and _add_bounds writes the tightest of these and the type's own bounds, one value per predicate.
  • bound_literal writes each bound as a literal that compares with the range's values:
    • numeric ranges: the range's datatype when the bound is a valid value of it, else xsd:integer or xsd:decimal, never in exponent form. So 0.5 on an integer slot becomes "0.5"^^xsd:decimal, and 0 on a positiveInteger becomes 0 (xsd:integer);
    • date, datetime, time (and xsd:dateTimeStamp): a valid literal of the range's datatype;
    • string: a string bound, written as before;
    • anything else is skipped with the warning above: a number on a string range, a datatype outside XSD, a class or an enum, which SPARQL cannot compare, and xsd:gYear, where the engines disagree.
  • Bounds of a slot whose range is a class or an enum, and the slot-level bounds of an any_of slot, are written as before.

How was this tested?

  • 40 new test cases in test_shaclgen.py; 24 of them fail on main:
    • test_any_of_and_type_bounds_pyshacl_end_to_end (25 cases): values in, at and out of the bounds of input/shaclgen/any_of_bounds.yaml, validated with pySHACL against the generated shapes, which are themselves checked with meta_shacl=True;
    • test_bound_is_valid_literal_of_comparable_datatype (8 cases): the literal written for each kind of range;
    • test_incomparable_bound_is_skipped_with_warning (7 cases).
  • I ran 14 hand-made mutants of the new code against these tests; 13 are caught. The survivor writes a decimal bound in exponent form, which rdflib normalizes back by default (rdflib.NORMALIZE_LITERALS).
  • gen-shacl on all 411 schemas under tests/ and examples/, main vs this branch: 19 outputs differ, all in sh:minInclusive / sh:maxInclusive:
    • 7 compliance outputs gain the bound of a type (minimum_value: 0);
    • 10 outputs (8 copies of personinfo, 2 of an inference example) write decimal bounds as xsd:decimal instead of xsd:double or xsd:integer;
    • 1 string slot loses its numeric 1..100 bounds, with the warning;
    • 1 is the new test schema.
  • uv run python -m pytest tests -n 8 on Windows: 14858 passed, 8 failed, 5 errors. None of them involve gen-shacl: run on their own, all pass except test_datadict_personinfo (calls kroki.io, fails on main too) and test_template_noblack (requests-cache.sqlite locked by another process).
  • ruff check and ruff format --check at the pre-commit pin (v0.11.13): clean.

Areas of uncertainty

  • A slot bound wider than its type's. With range: Percentage (0..100) and maximum_value: 200 on the slot, this PR keeps 100, following the monotonic semantics above. gen-json-schema lets the slot's keyword replace the type's (get_value_constraints_for_slot), so it accepts 150. I think the JSON Schema side should change, but that is outside this PR.
  • Skipping instead of failing. A bound SHACL can't compare is skipped with a warning, so existing schemas keep generating. Raising would be stricter. The warning repeats for each slot that uses the type.
  • Decimal bounds change datatype. With SPARQL's numeric type promotion, 0.1 and "0.1"^^xsd:double compare as equal, and rudof agrees. pySHACL compares the exact values and rejects (table above). Writing the bound in the range's own datatype gives the same result in both.
  • Class and enum ranges. Their slot-level bounds are still written untyped, as on main. I left them alone because I don't know what a bound on a class should mean.

Checklist

  • My code follows the contributor guidelines
  • I have added tests that prove my fix/feature works
  • Existing tests pass locally with my changes

AI Assistance

If you used AI tools while preparing this PR, you are still the author and responsible for understanding, verifying, and defending your submission. Please engage with reviewers personally rather than through your agent during feedback and revisions. See our AI Covenant for details.

gen-shacl dropped minimum_value and maximum_value when they were set on an
any_of branch or on a type, so out-of-range values conformed to the shapes
while the JSON Schema from the same schema rejected them.

A branch now gets sh:minInclusive / sh:maxInclusive on its node, like its
pattern. The bounds of a type and of the slot or branch whose range it is
all hold, and SHACL allows one sh:minInclusive and one sh:maxInclusive per
shape, so they are merged into the tightest.

Each bound is written as a valid literal that compares with the range's
values: the range's own datatype where the bound is a value of it, else
xsd:integer or xsd:decimal, with no exponent form. A decimal 0.1 no longer
falls below a bound written as the double 0.1. A bound that SHACL cannot
order against the range's values (a number on a string range, gYear,
non-XSD datatypes, classes, enums) would reject every value, so it is
skipped with a warning.

Signed-off-by: Carlo van Driesten <carlo.van-driesten@vdl.digital>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant