ontocast.tool.facts_invariants¶
Deterministic normalization, repair, and findings for rendered facts.
The renderer LLM is treated as a transcriber, not a guarantor: every check here detects or repairs a concrete violation in code, and only unresolved items go back to the LLM as mandatory fix instructions. All mechanisms are schema-driven and domain-agnostic — alias tables and known-term sets are derived from the ontology context at runtime, never hardcoded per vocabulary.
FactsValidationReport
¶
Bases: BaseModel
Invariant findings over one aggregated facts graph.
Source code in ontocast/tool/facts_invariants.py
error_findings
property
¶
Error-severity findings, whatever their kind.
ShaclRepairResult
¶
Bases: BaseModel
Outcome of the LLM-free SHACL repair pass.
Source code in ontocast/tool/facts_invariants.py
ShaclViolation
¶
Bases: BaseModel
One SHACL validation result, in the form the repair pass needs.
FactsValidationFinding is the reporting shape and deliberately flat;
this keeps the RDF terms (focus node, path, offending value, constraint
component) so a repair can act on them.
Source code in ontocast/tool/facts_invariants.py
as_finding()
¶
Project onto the reported finding shape.
Source code in ontocast/tool/facts_invariants.py
apply_shacl_repairs(graph, shapes_graph, ontology_graph, *, mode='prune', passes=1, fact_namespaces=(), code_predicates=(), inference='rdfs', advanced=True, max_triples=0, initial_violations=None)
¶
Repair SHACL violations in code, with no LLM round-trip.
Bounded validate -> repair -> revalidate loop. A pass is kept only when
it strictly reduces the violation count: a repair that trades triples for
no conformance gain is reverted, the same discipline the un-merge repair
uses.
Repairs by constraint component
sh:datatype: retype a literal that parses as the declared datatype ("2019"^^xsd:string->"2019"^^xsd:gYear).sh:class/sh:nodeKind: replace a string literal with the one catalog IRI declaring it as a surface form (qudt:unit "meV"->unit:MilliElectronVolt). Ambiguous forms are left reported.sh:minCount(modepruneonly): drop a focus node that asserts nothing beyondrdf:type/rdfs:labeland is referenced by at most one subject, together with that reference.
Everything else -- sh:maxCount (owned by the functional-violation and
un-merge machinery), sh:not, sh:qualifiedValueShape, SPARQL
constraints -- is reported, never repaired.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
graph
|
RDFGraph
|
Aggregated facts graph, repaired in place: it may be oxigraph-backed and carry RDF 1.2 triple terms, which a copied rdflib graph would silently drop. A pass that fails the accept test is rolled back triple-for-triple instead. |
required |
shapes_graph
|
RDFGraph | None
|
Shapes to validate against; |
required |
ontology_graph
|
RDFGraph | None
|
Merged ontology context, indexed for surface forms. |
required |
mode
|
str
|
|
'prune'
|
passes
|
int
|
Maximum repair rounds. |
1
|
fact_namespaces
|
Sequence[str]
|
Only nodes under these namespaces are repaired. |
()
|
code_predicates
|
Sequence[str]
|
Code-bearing predicates for surface resolution. |
()
|
inference
|
str
|
pyshacl pre-inference mode. |
'rdfs'
|
advanced
|
bool
|
Enable SHACL Advanced Features. |
True
|
max_triples
|
int
|
Skip validation above this graph size; 0 disables. |
0
|
initial_violations
|
Sequence[ShaclViolation] | None
|
Violations already computed for |
None
|
Returns:
| Type | Description |
|---|---|
ShaclRepairResult
|
The repaired graph, the applied repair records, and fact-scoped |
ShaclRepairResult
|
violation counts before and after (the population |
ShaclRepairResult
|
judged on; the loop's accept test uses the raw count internally). |
Source code in ontocast/tool/facts_invariants.py
1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 | |
build_surface_index(ontology_graph, code_predicates=())
¶
Map exact catalog surface forms to the IRIs declaring them.
Case-sensitive and exact: these are codes and names a model may have
transcribed verbatim ("d", "meV", "CsPbBr3"), not free text to
be fuzzy-matched. A form claimed by more than one IRI stays in the index and
is rejected at lookup time — an ambiguous code is not a repairable one.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ontology_graph
|
RDFGraph | None
|
Merged ontology context to index. |
required |
code_predicates
|
Sequence[str]
|
Extra code-bearing predicates (UCUM codes, symbols, notations) on top of the standard name predicates. |
()
|
Returns:
| Type | Description |
|---|---|
dict[str, set[str]]
|
Surface form -> set of IRIs declaring it. |
Source code in ontocast/tool/facts_invariants.py
collect_catalog_terms(ontology_graph)
¶
All IRIs appearing anywhere in the ontology context.
Source code in ontocast/tool/facts_invariants.py
collect_shacl_shapes(ontology_graph, shapes_dir)
¶
Assemble the SHACL shapes graph for the validation gate.
Sources: every .ttl file under shapes_dir (when configured), plus
the ontology context itself when it already carries sh:NodeShape
declarations inline — the zero-config path for catalogs that ship shapes
next to their schema.
Source code in ontocast/tool/facts_invariants.py
collect_unit_findings(*, graph, ontology_graph, quarantined, extraction_text, fact_namespaces, coverage_limit=30, additional_standard_namespaces=())
¶
Assemble all deterministic findings for one rendered unit graph.
Mandatory: quarantined literals (with closed-range individual
suggestions), forbidden-namespace terms (example.org), doc-namespace
predicates, unresolved catalog near-misses, and predicates asserted on a
subject whose type contradicts their rdfs:domain. Advisory-strong:
numeric mentions of the source text absent from the graph — the renderer
decides per item whether each is an extractable quantity or an artifact.
Source code in ontocast/tool/facts_invariants.py
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 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 | |
domain_violation_findings(graph, ontology_graph)
¶
Report subjects whose asserted type contradicts a predicate's domain.
Asserting a triple whose predicate declares an rdfs:domain entails
that the subject belongs to that domain, so an untyped subject is never a
violation -- the type is simply left to inference. It becomes one when the
subject carries an asserted type that is unrelated to the declared domain:
inference then adds the domain class on top of an incompatible one, and
the contradiction surfaces later as a confusing failure somewhere else
(SHACL reporting a missing property on a class the graph never meant to
assert) rather than at the triple that caused it.
Conservative by construction, since a false accusation costs a render pass.
A subject is reported only when it has at least one asserted type and every
asserted type is unrelated to every declared domain -- neither a subtype
nor a supertype of it, following rdfs:subClassOf and
owl:equivalentClass intersections in both directions. Typing a subject
with a supertype of the domain (sosa:Observation where the domain is
obs:QuantitativeObservation) is consistent: inference specializes it,
it contradicts nothing, and flagging it would bury the real violations.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
graph
|
RDFGraph
|
Rendered facts graph for one unit. |
required |
ontology_graph
|
RDFGraph | None
|
Ontology context the renderer was given. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
list |
list[FactsUnitFinding]
|
One mandatory finding per offending (subject, predicate) pair, |
list[FactsUnitFinding]
|
ordered by subject then predicate. |
Source code in ontocast/tool/facts_invariants.py
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 | |
format_findings_for_prompt(findings)
¶
Render findings as MANDATORY-fixes + coverage blocks for the renderer.
Source code in ontocast/tool/facts_invariants.py
normalize_literals_against_schema(graph, ontology_graph)
¶
Retype literals whose predicate declares a compatible rdfs:range.
Fixes the qudt:numericValue 230 vs "230"^^xsd:decimal drift at parse
time, and the same drift for the date-like datatypes: when the schema
declares a range in :data:_RETYPABLE_RANGE_DATATYPES and the lexical form
parses as that datatype, the literal is rewritten with it.
A literal is only retyped from an untyped, xsd:string, or numeric source
-- a string range must never be able to clobber a correctly typed value --
and language-tagged literals are left alone, since they are
rdf:langString and retyping would discard the tag.
Returns:
| Type | Description |
|---|---|
int
|
Number of retyped literals. |
Source code in ontocast/tool/facts_invariants.py
record_facts_gate_metrics(metrics, *, report, repair_result, ontology_context_empty=False)
¶
Write the validation-gate metrics both entry paths share.
The graph pipeline's VALIDATE_FACTS node and the single-unit gate behind
/process_unit run the same checks minus the un-merge repair, and had
drifted into two hand-maintained copies of these writes — so a metric added
to one path was silently absent from the other, and batch dumps stopped
being comparable across entry paths, which is the one thing they exist for.
Merge-specific counters stay with the graph pipeline: they have no meaning
for a single unit.
Takes a plain mapping rather than AgentState so the tool layer stays
ignorant of the state graph.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
metrics
|
MutableMapping[str, int | float | str | dict]
|
|
required |
report
|
FactsValidationReport
|
Validation report describing the graph that will be served. |
required |
repair_result
|
ShaclRepairResult
|
Outcome of :func: |
required |
ontology_context_empty
|
bool
|
Whether the facts were validated with no
catalog vocabulary at all. The per-term non-catalog check cannot
see this — with no context there is nothing to compare against — so
it is reported here, where an empty context is known to be
unexpected. Only the document path used to report it, which left
|
False
|
Source code in ontocast/tool/facts_invariants.py
repair_literal_type_objects(graph)
¶
Coerce literal rdf:type objects into IRIs.
The renderer sometimes emits a "prefix:Class"^^xsd:string instead of
a prefix:Class (JSON-LD bare-string type values parse the same way).
A literal-typed node is invisible to SPARQL class queries, reasoning, and
the aggregator's URI minting/entity matching, all of which guard on
isinstance(obj, URIRef). Absolute IRIs and compact IRIs bound in the
graph are rewritten deterministically; unresolvable forms become MANDATORY
findings.
Returns:
| Type | Description |
|---|---|
int
|
Tuple of (number of rewritten triples, unresolved findings, |
list[FactsUnitFinding]
|
applied-repair records). |
Source code in ontocast/tool/facts_invariants.py
repair_property_aliases(graph, ontology_graph, *, min_ratio=0.85)
¶
Rewrite near-miss predicates in catalog namespaces; report ambiguity.
A predicate whose namespace belongs to the ontology context but which is
not itself a catalog term is a near-miss (qqval:lowerBound for
qqval:hasLowerBound). When exactly one candidate scores above
min_ratio (token containment counts as 1.0) the rewrite is applied
deterministically; otherwise a mandatory finding carries the top
suggestions.
Returns:
| Type | Description |
|---|---|
int
|
Tuple of (number of rewritten triples, unresolved findings, |
list[FactsUnitFinding]
|
applied-repair records). |
Source code in ontocast/tool/facts_invariants.py
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 | |
resolve_code_literals(graph, ontology_graph, code_predicates=())
¶
Link nodes to the catalog individual whose code they already carry.
A renderer that reads 4-15 days often annotates the value node with the
code it saw — qudt:ucumCode "d" — instead of the object property that
points at the individual — qudt:unit unit:DAY. The graph is well-formed,
so no range check fires, but every query reading the object property gets
an unbound result. The code came from the text and the individual is in the
catalog, so the link is recoverable without asking the model again.
Fully schema-driven, no vocabulary compiled in: the connecting property is whichever object property the ontology context declares with a range the resolved individual is typed as, and a domain the subject satisfies. If the schema offers several such properties, or none, nothing is added.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
graph
|
RDFGraph
|
Rendered facts graph, repaired in place. |
required |
ontology_graph
|
RDFGraph | None
|
Merged ontology context, read-only. |
required |
code_predicates
|
Sequence[str]
|
Predicates carrying machine-resolvable codes. |
()
|
Returns:
| Type | Description |
|---|---|
tuple[int, list[GraphRepairRecord]]
|
Tuple of (number of added triples, applied-repair records). |
Source code in ontocast/tool/facts_invariants.py
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 | |
resolve_unique_surface(index, text)
¶
The single IRI declaring text as a surface form, if exactly one does.
Source code in ontocast/tool/facts_invariants.py
run_shacl(graph, shapes_graph, *, ontology_graph=None, inference='rdfs', advanced=True, max_triples=0)
¶
Validate graph against shapes_graph, returning the violations.
Reaching here means shapes were found, so the caller expects validation to
happen: a missing extra or a skipped run is reported at warning level, not
debug. Silently returning "no violations" is indistinguishable from
"conforms", so those cases return None.
The ontology context is mixed in (ont_graph) rather than left out. A
facts graph states that a value uses unit:DAY; that the individual is
a qudt:Unit is stated only in the catalog. Validating the facts alone
therefore fails every sh:class constraint pointing at a catalog
individual — violations that describe the missing schema, not the data.
RDFS inference is the default for the same reason. SHACL resolves class
targets through rdfs:subClassOf on its own, but property paths carry no
entailment: a shape on obs:hasResult does not see the
life:hasStorageResult the renderer emitted, and reports the more
specific statement as a missing one. Measured on the three-document matsci
pilot: 268 violations at inference="none" against 232 with RDFS.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
graph
|
RDFGraph
|
Data graph to validate. |
required |
shapes_graph
|
RDFGraph
|
Shapes to validate against. |
required |
ontology_graph
|
RDFGraph | None
|
Schema mixed into the data graph for validation. |
None
|
inference
|
str
|
pyshacl pre-inference ( |
'rdfs'
|
advanced
|
bool
|
Enable SHACL Advanced Features. |
True
|
max_triples
|
int
|
Skip validation above this graph size; 0 disables. |
0
|
Returns:
| Type | Description |
|---|---|
list[ShaclViolation] | None
|
Violations in report order, or |
Source code in ontocast/tool/facts_invariants.py
1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 | |
summarize_conformance(findings, *, shacl_evaluated=None, repairs=())
¶
Roll findings up into the shape a report or a client can read.
Counting by constraint component is what separates "168 violations" from "two systematic defects": 71 missing-qualifier violations on one shape are one modelling gap, not 71 problems to triage.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
findings
|
Sequence[FactsValidationFinding]
|
Residual findings after any repair. |
required |
shacl_evaluated
|
bool | None
|
Whether SHACL actually ran (see
:class: |
None
|
repairs
|
Sequence[GraphRepairRecord]
|
LLM-free repairs the gate applied. |
()
|
Returns:
| Type | Description |
|---|---|
dict
|
|
dict
|
finding kind, by SHACL constraint component and shape, and the applied |
dict
|
repair counts by kind. |
Source code in ontocast/tool/facts_invariants.py
validate_aggregated_facts(graph, ontology_graph, *, shapes_graph=None, fact_namespaces=None, suspect_multi_value_severity='error', functional_min_single_support=3, quantity_fallback_vocabulary=None, shacl_inference='rdfs', shacl_advanced=True, shacl_max_triples=0)
¶
Check post-merge invariants over the aggregated facts graph.
Deterministic defense-in-depth behind the merge guards: merge-signature violations here are almost always a bad identity merge, and error-severity findings of those kinds on merged subjects drive the un-merge repair. SHACL findings are reported but never drive it: a constraint violation says a node is under-specified, not that two entities were wrongly identified.
Checks
FUNCTIONAL_VIOLATION: >= 2 distinct objects on a predicate the schema constrains to at most one value (owl:FunctionalPropertyor an OWL max-cardinality-1 restriction).SUSPECT_MULTI_VALUE: >= 2 distinct canonical numeric values on one (subject, predicate); or >= 2 IRI objects on a predicate that is single-valued for a dominant majority of other subjects. Severity is configurable — legitimate multi-value modeling exists, bad merges are far more common.DEGENERATE_COREFERENCE: one IRI object shared by >= 2 distinct functional-ish predicates of one subject (collapsed range bounds).SHACL: optional, whenpyshaclis installed and shapes exist.NON_CATALOG_VOCABULARY: warning-only telemetry for terms the ontology context never supplied, which mark a retrieval miss the renderer papered over with a documented fallback.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
graph
|
RDFGraph
|
Aggregated facts graph. |
required |
ontology_graph
|
RDFGraph | None
|
Merged ontology context (functionality harvest). |
required |
shapes_graph
|
RDFGraph | None
|
Optional SHACL shapes graph. |
None
|
fact_namespaces
|
list[str] | None
|
When set, only subjects under these namespaces are reported (ontology entities are not the gate's business). |
None
|
suspect_multi_value_severity
|
str
|
|
'error'
|
functional_min_single_support
|
int
|
Minimum single-valued subjects before a predicate counts as dominantly single-valued. |
3
|
shacl_inference
|
str
|
pyshacl pre-inference mode (see :func: |
'rdfs'
|
shacl_advanced
|
bool
|
Enable SHACL Advanced Features. |
True
|
shacl_max_triples
|
int
|
Skip SHACL above this graph size; 0 disables. |
0
|
Returns:
| Type | Description |
|---|---|
FactsValidationReport
|
Report with all findings, ordered by subject. |
Source code in ontocast/tool/facts_invariants.py
2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 | |