Skip to content

ontocast.tool.ontology_validation

Deterministic validation of ontology deltas.

Two lanes with different authorities: unit_findings validates a unit's delta against its own (possibly partial) prompt snapshot inside the loop; reconcile checks the merged document delta against the FULL catalog terminals at reduce time, where duplicates invisible to a retrieved snapshot become detectable.

Modules:

Name Description
axiom_hygiene

Deterministic clean-up of a document's ontology delta before it is written.

catalog_terms

The catalog's terms as the ontology prompts list them.

consolidate

Compile term actions into a graph patch, deterministically.

label_repair

LLM-free labels for newly minted ontology terms.

plan

The document ontology plan: model-free checks and the reduce-time split.

reconcile

Reduce-time reconciliation of minted terms against the whole catalog.

shape

Model-free measures of an ontology's shape, and a whole-catalog name index.

unit_findings

Deterministic per-unit findings on a unit's ontology delta.

Attributes

__all__ = ['CatalogSurfaceIndex', 'MintedDuplicate', 'apply_minted_duplicate_rewrites', 'build_catalog_surface_index', 'collect_ontology_unit_findings', 'count_fixes_targeting_snapshot', 'detect_minted_duplicates'] module-attribute

Classes

CatalogSurfaceIndex

Bases: BaseModel

Names of every catalog term, case-insensitive, by label and local name.

Source code in ontocast/tool/ontology_validation/shape.py
class CatalogSurfaceIndex(BaseModel):
    """Names of every catalog term, case-insensitive, by label and local name."""

    by_label: dict[str, set[str]] = Field(default_factory=dict)
    by_local: dict[str, set[str]] = Field(default_factory=dict)
    #: Every named subject of the catalog.
    terms: set[str] = Field(default_factory=set)
    properties: set[str] = Field(default_factory=set)
    classes: set[str] = Field(default_factory=set)

    def is_empty(self) -> bool:
        """Whether the index holds no term."""
        return not self.terms

Attributes

by_label = Field(default_factory=dict) class-attribute instance-attribute
by_local = Field(default_factory=dict) class-attribute instance-attribute
classes = Field(default_factory=set) class-attribute instance-attribute
properties = Field(default_factory=set) class-attribute instance-attribute
terms = Field(default_factory=set) class-attribute instance-attribute

Methods:

is_empty()

Whether the index holds no term.

Source code in ontocast/tool/ontology_validation/shape.py
def is_empty(self) -> bool:
    """Whether the index holds no term."""
    return not self.terms

MintedDuplicate

Bases: BaseModel

One minted term that names an existing catalog term.

Source code in ontocast/tool/ontology_validation/reconcile.py
class MintedDuplicate(BaseModel):
    """One minted term that names an existing catalog term."""

    minted_iri: str
    catalog_iri: str
    #: The name both terms share: a label, preferred label or notation, or
    #: the local name.
    surface: str
    #: ``"property"`` / ``"class"`` / ``"unknown"`` — the minted term's role
    #: as evidenced by the delta itself.
    role: str
    #: Which name matched.
    key: TypingLiteral["label", "local_name"] = "label"

Attributes

catalog_iri instance-attribute
key = 'label' class-attribute instance-attribute
minted_iri instance-attribute
role instance-attribute
surface instance-attribute

Functions:

apply_minted_duplicate_rewrites(merged_inserts, duplicates)

Rewrite minted IRIs to their catalog IRIs, in place.

Substitutes in subject and object position — a second minted term referencing the duplicate must end up pointing at the catalog term, or the rewrite would strand it. Predicate position is included for completeness (a minted property duplicate used as a predicate elsewhere in the delta).

Returns:

Type Description
int

Number of triples rewritten.

Source code in ontocast/tool/ontology_validation/reconcile.py
def apply_minted_duplicate_rewrites(
    merged_inserts: RDFGraph,
    duplicates: list[MintedDuplicate],
) -> int:
    """Rewrite minted IRIs to their catalog IRIs, in place.

    Substitutes in subject **and** object position — a second minted term
    referencing the duplicate must end up pointing at the catalog term, or the
    rewrite would strand it. Predicate position is included for completeness
    (a minted property duplicate used as a predicate elsewhere in the delta).

    Returns:
        Number of triples rewritten.
    """
    if not duplicates:
        return 0
    mapping = {
        URIRef(duplicate.minted_iri): URIRef(duplicate.catalog_iri)
        for duplicate in duplicates
    }
    rewritten = 0
    for triple in list(merged_inserts):
        subject, predicate, obj = triple
        replaced = (
            mapping.get(subject, subject) if isinstance(subject, URIRef) else subject,
            mapping.get(predicate, predicate)
            if isinstance(predicate, URIRef)
            else predicate,
            mapping.get(obj, obj) if isinstance(obj, URIRef) else obj,
        )
        if replaced == triple:
            continue
        merged_inserts.remove(triple)
        merged_inserts.add(replaced)
        rewritten += 1
    return rewritten

build_catalog_surface_index(graphs)

Index the labels, notations and local names of every subject.

Source code in ontocast/tool/ontology_validation/shape.py
def build_catalog_surface_index(graphs: Iterable[RDFGraph]) -> CatalogSurfaceIndex:
    """Index the labels, notations and local names of every subject."""
    index = CatalogSurfaceIndex()
    for graph in graphs:
        for subject in graph.subjects():
            if not isinstance(subject, URIRef):
                continue
            iri = str(subject)
            if iri in index.terms:
                continue
            index.terms.add(iri)
            local = _local_name(iri)
            if local and local != iri:
                index.by_local.setdefault(local.casefold(), set()).add(iri)
        for predicate in SURFACE_PREDICATES:
            for subject, value in graph.subject_objects(predicate):
                if not isinstance(subject, URIRef) or not isinstance(value, RDFLiteral):
                    continue
                key = normalize_surface(str(value))
                if key:
                    index.by_label.setdefault(key, set()).add(str(subject))
        properties, classes = _catalog_term_roles(graph)
        index.properties |= properties
        index.classes |= classes
    index.classes -= index.properties & index.classes
    return index

collect_ontology_unit_findings(*, inserts, deletes, snapshot_graph, merged_graph=None, fact_namespaces=(), policy=None, max_class_depth=6, catalog_index=None, home_namespace=None)

Assemble all deterministic findings for one unit's ontology delta.

Parameters:

Name Type Description Default
inserts RDFGraph

Net new triples this unit adds (build_delta().inserts).

required
deletes RDFGraph

Snapshot triples this unit removes.

required
snapshot_graph RDFGraph | None

The prompt ontology context; None/empty means the fresh-create path, where every catalog-relative check is skipped.

required
merged_graph RDFGraph | None

snapshot + delta when the caller already has it (working_graph after updates apply) — passing it avoids a snapshot copy. Built here when omitted.

None
fact_namespaces Sequence[str]

Facts/document namespaces; ontology terms minted there are mandatory findings.

()
policy ValidationPolicy | None

Deployment namespace exemptions; None (tests) uses the built-in standard namespaces only.

None
max_class_depth int

Deepest named-superclass chain a minted class may sit on.

6
catalog_index CatalogSurfaceIndex | None

Names of every catalog term, for the duplicate check; None skips it.

None
home_namespace str | None

The document's home namespace: where every new term belongs. None accepts any namespace the snapshot declares.

None

Returns:

Type Description
list[OntologyUnitFinding]

Findings, mandatory first is not guaranteed — order follows the

list[OntologyUnitFinding]

check sequence; callers filter on mandatory.

Source code in ontocast/tool/ontology_validation/unit_findings.py
def collect_ontology_unit_findings(
    *,
    inserts: RDFGraph,
    deletes: RDFGraph,
    snapshot_graph: RDFGraph | None,
    merged_graph: RDFGraph | None = None,
    fact_namespaces: Sequence[str] = (),
    policy: ValidationPolicy | None = None,
    max_class_depth: int = 6,
    catalog_index: CatalogSurfaceIndex | None = None,
    home_namespace: str | None = None,
) -> list[OntologyUnitFinding]:
    """Assemble all deterministic findings for one unit's ontology delta.

    Args:
        inserts: Net new triples this unit adds (``build_delta().inserts``).
        deletes: Snapshot triples this unit removes.
        snapshot_graph: The prompt ontology context; ``None``/empty means the
            fresh-create path, where every catalog-relative check is skipped.
        merged_graph: ``snapshot + delta`` when the caller already has it
            (``working_graph`` after updates apply) — passing it avoids a
            snapshot copy. Built here when omitted.
        fact_namespaces: Facts/document namespaces; ontology terms minted
            there are mandatory findings.
        policy: Deployment namespace exemptions; ``None`` (tests) uses the
            built-in standard namespaces only.
        max_class_depth: Deepest named-superclass chain a minted class may
            sit on.
        catalog_index: Names of every catalog term, for the duplicate check;
            ``None`` skips it.
        home_namespace: The document's home namespace: where every new term
            belongs. ``None`` accepts any namespace the snapshot declares.

    Returns:
        Findings, mandatory first is *not* guaranteed — order follows the
        check sequence; callers filter on ``mandatory``.
    """
    active_policy = policy or ValidationPolicy()
    if merged_graph is None:
        merged_graph = RDFGraph()
        if snapshot_graph is not None:
            for triple in snapshot_graph:
                merged_graph.add(triple)
        for triple in inserts:
            merged_graph.add(triple)

    declared = collect_declared_namespaces(snapshot_graph)
    findings: list[OntologyUnitFinding] = [
        *_namespace_findings(
            inserts,
            declared,
            fact_namespaces,
            active_policy.standard_namespaces(),
            home_namespace=home_namespace,
            snapshot_graph=snapshot_graph,
        ),
        *_degenerate_restriction_findings(inserts),
        *_missing_label_findings(inserts, snapshot_graph),
        *_subclass_cycle_findings(inserts, merged_graph),
        *_role_confusion_findings(inserts, snapshot_graph),
        *_cardinality_contradiction_findings(inserts, merged_graph),
        *_foreign_delete_findings(deletes, snapshot_graph, inserts),
        *_label_collision_findings(inserts, snapshot_graph),
        *_hierarchy_depth_findings(
            inserts, snapshot_graph, merged_graph, max_class_depth
        ),
        *_value_set_sibling_findings(inserts, snapshot_graph, merged_graph),
        *_specific_label_leaf_findings(inserts, snapshot_graph, merged_graph),
        *_catalog_duplicate_findings(inserts, snapshot_graph, catalog_index),
    ]
    return findings

count_fixes_targeting_snapshot(fixes, snapshot_graph, insert_subjects)

Critic fixes aimed at catalog content this unit's delta never touched.

The ontology critic is shown snapshot + delta and can reject a unit for pre-existing catalog defects the renderer cannot own. This counts the proposed fixes whose incorrect_value names a snapshot-declared subject absent from the unit's inserts — by full-IRI or prefixed-name substring match, so it is a lower bound, recorded as telemetry rather than used for control flow.

Source code in ontocast/tool/ontology_validation/unit_findings.py
def count_fixes_targeting_snapshot(
    fixes: Sequence[TripleFix],
    snapshot_graph: RDFGraph | None,
    insert_subjects: set[str],
) -> int:
    """Critic fixes aimed at catalog content this unit's delta never touched.

    The ontology critic is shown ``snapshot + delta`` and can reject a unit
    for pre-existing catalog defects the renderer cannot own. This counts the
    proposed fixes whose ``incorrect_value`` names a snapshot-declared subject
    absent from the unit's inserts — by full-IRI or prefixed-name substring
    match, so it is a lower bound, recorded as telemetry rather than used for
    control flow.
    """
    if snapshot_graph is None or not fixes:
        return 0
    prefix_map = [
        (prefix, str(namespace))
        for prefix, namespace in snapshot_graph.namespaces()
        if prefix
    ]
    snapshot_only: set[str] = set()
    qnames: set[str] = set()
    for subject in snapshot_graph.subjects():
        if not isinstance(subject, URIRef):
            continue
        text = str(subject)
        if text in insert_subjects or text in snapshot_only:
            continue
        snapshot_only.add(text)
        for prefix, namespace in prefix_map:
            if text.startswith(namespace) and len(text) > len(namespace):
                qnames.add(f"{prefix}:{text[len(namespace) :]}")
    count = 0
    for fix in fixes:
        haystack = fix.incorrect_value or ""
        if not haystack:
            continue
        if any(iri in haystack for iri in snapshot_only) or any(
            qname in haystack for qname in qnames
        ):
            count += 1
    return count

detect_minted_duplicates(merged_inserts, catalog_index)

Find minted terms that name an existing catalog term.

Parameters:

Name Type Description Default
merged_inserts RDFGraph

Document-level merged insert delta.

required
catalog_index CatalogSurfaceIndex

Names of every catalog term.

required

Returns:

Type Description
list[MintedDuplicate]

One record per minted term with a unique, role-compatible match,

list[MintedDuplicate]

ordered by minted IRI. Detection only — the caller decides whether to

list[MintedDuplicate]

rewrite.

Source code in ontocast/tool/ontology_validation/reconcile.py
def detect_minted_duplicates(
    merged_inserts: RDFGraph,
    catalog_index: CatalogSurfaceIndex,
) -> list[MintedDuplicate]:
    """Find minted terms that name an existing catalog term.

    Args:
        merged_inserts: Document-level merged insert delta.
        catalog_index: Names of every catalog term.

    Returns:
        One record per minted term with a unique, role-compatible match,
        ordered by minted IRI. Detection only — the caller decides whether to
        rewrite.
    """
    if catalog_index.is_empty() or len(merged_inserts) == 0:
        return []
    roles = minted_roles(merged_inserts)
    duplicates: list[MintedDuplicate] = []
    for subject in sorted(
        {s for s in merged_inserts.subjects() if isinstance(s, URIRef)}, key=str
    ):
        match = match_catalog_term(
            subject, merged_inserts, catalog_index, roles.get(subject, "unknown")
        )
        if match is not None:
            duplicates.append(match)
    return duplicates