Skip to content

Graph-Native Infrastructure for Context and Accountable AI Systems

feat(semantic_extract): schema-guided validation — SchemaValidator + ExtractionSchema (PR 1/3) (#1527)

Besokus44c0c7a76d66
diff --git a/CHANGELOG.md b/CHANGELOG.md
index ac219efa..87d5065a 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -9,6 +9,15 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
+### Added
+
+- **Schema-guided extraction validation** (#1510) by @Besokus
+ - New `SchemaValidator` (`semantica.semantic_extract`, lazy export): a deterministic sibling of `ExtractionValidator` that checks extraction output for *conformance to a domain ontology* — an axis orthogonal to `ExtractionValidator`'s confidence checks. It mirrors the same interface (`validate_entities()` / `validate_relations()` returning `ValidationResult`, batch-aware), so the two compose back-to-back
+ - Entity labels must be concepts in the schema; relation predicates must be in the schema and satisfy their `domain` / `range`. Violations are reported in `ValidationResult.errors` with counts in `metrics` and `score` = conformance ratio; `filter_by_schema()` / `filter_relations_by_schema()` return the conforming subset (mirroring `filter_by_confidence`). No LLM required
+ - New `ExtractionSchema` (`semantica.semantic_extract`, lazy export): a lightweight, read-only view over a domain ontology (allowed concepts + predicates with optional `domain` / `range`). Reuses the project's existing OWL ontology representation rather than a parallel type — build one from a `generate_ontology`-style dict (`ExtractionSchema.from_ontology`) or an OWL/Turtle file/string (`ExtractionSchema.from_owl`, via the existing `rdflib` dependency). An empty `domain`/`range` means unconstrained, matching OWL
+ - Implements the deterministic core of ontology-based information extraction (OBIE; Wimalasuriya & Dou, 2010). No new runtime dependencies
+ - New `tests/semantic_extract/test_schema_validator.py`
+
## [0.7.0] - 2026-09-07
### Changed
diff --git a/semantica/semantic_extract/__init__.py b/semantica/semantic_extract/__init__.py
index 5db95b4b..d05fc0f7 100644
--- a/semantica/semantic_extract/__init__.py
+++ b/semantica/semantic_extract/__init__.py
@@ -34,11 +34,11 @@ Example Usage:
>>> from semantica.semantic_extract import NamedEntityRecognizer
>>> ner = NamedEntityRecognizer(confidence_threshold=0.7)
>>> entities = ner.extract_entities("Steve Jobs founded Apple.")
-
+
>>> from semantica.semantic_extract import RelationExtractor
>>> rel_extractor = RelationExtractor(confidence_threshold=0.6)
>>> relations = rel_extractor.extract_relations(text, entities=entities)
-
+
>>> from semantica.semantic_extract import TripletExtractor
>>> triplet_extractor = TripletExtractor(include_temporal=True)
>>> triplets = triplet_extractor.extract_triplets(text)
@@ -52,7 +52,6 @@ from __future__ import annotations
import importlib
from typing import Any, Dict, Tuple
-
_LAZY_EXPORTS: Dict[str, Tuple[str, str]] = {
# Named Entity Recognition
"NamedEntityRecognizer": (".named_entity_recognizer", "NamedEntityRecognizer"),
@@ -92,7 +91,10 @@ _LAZY_EXPORTS: Dict[str, Tuple[str, str]] = {
"RoleLabeler": (".semantic_analyzer", "RoleLabeler"),
"SemanticClusterer": (".semantic_analyzer", "SemanticClusterer"),
# Semantic Network
- "SemanticNetworkExtractor": (".semantic_network_extractor", "SemanticNetworkExtractor"),
+ "SemanticNetworkExtractor": (
+ ".semantic_network_extractor",
+ "SemanticNetworkExtractor",
+ ),
"SemanticNode": (".semantic_network_extractor", "SemanticNode"),
"SemanticEdge": (".semantic_network_extractor", "SemanticEdge"),
"SemanticNetwork": (".semantic_network_extractor", "SemanticNetwork"),
@@ -103,6 +105,10 @@ _LAZY_EXPORTS: Dict[str, Tuple[str, str]] = {
# Validation
"ExtractionValidator": (".extraction_validator", "ExtractionValidator"),
"ValidationResult": (".extraction_validator", "ValidationResult"),
+ # Schema-guided validation
+ "ExtractionSchema": (".schema", "ExtractionSchema"),
+ "Predicate": (".schema", "Predicate"),
+ "SchemaValidator": (".schema_validator", "SchemaValidator"),
# Providers
"BaseProvider": (".providers", "BaseProvider"),
"OpenAIProvider": (".providers", "OpenAIProvider"),
@@ -139,6 +145,7 @@ def __getattr__(name: str) -> Any:
globals()[name] = value
return value
+
__all__ = [
# Named Entity Recognition
"NamedEntityRecognizer",
@@ -188,6 +195,10 @@ __all__ = [
# Validation
"ExtractionValidator",
"ValidationResult",
+ # Schema-guided validation
+ "ExtractionSchema",
+ "Predicate",
+ "SchemaValidator",
# Providers
"BaseProvider",
"OpenAIProvider",
diff --git a/semantica/semantic_extract/schema.py b/semantica/semantic_extract/schema.py
new file mode 100644
index 00000000..e5403709
--- /dev/null
+++ b/semantica/semantic_extract/schema.py
@@ -0,0 +1,234 @@
+"""Domain schema view over an ontology, for schema-guided extraction.
+
+An :class:`ExtractionSchema` is a lightweight, read-only view over a domain
+ontology: the set of allowed *concept* names (entity labels) and the allowed
+*predicates* with optional ``domain`` / ``range`` constraints. It is what
+:class:`~semantica.semantic_extract.schema_validator.SchemaValidator` checks
+extraction output against.
+
+The schema deliberately **reuses the project's existing OWL ontology
+representation** instead of introducing a parallel "template" type. Build one
+from the dict produced by :func:`semantica.ontology.generate_ontology`
+(:meth:`ExtractionSchema.from_ontology`), or from an OWL / Turtle file or string
+(:meth:`ExtractionSchema.from_owl`).
+
+An empty ``domain`` / ``range`` means "unconstrained", matching OWL's convention
+that an object property with no ``rdfs:domain`` / ``rdfs:range`` places no
+restriction on its subjects / objects.
+
+Reference
+---------
+Using an ontology to constrain what may be extracted is the defining idea of
+ontology-based information extraction (OBIE): Wimalasuriya & Dou, "Ontology-Based
+Information Extraction: An Introduction and a Survey" (2010).
+"""
+
+from __future__ import annotations
+
+import os
+from dataclasses import dataclass, field
+from typing import Any, Dict, FrozenSet, Iterable, Mapping, Optional, Set
+
+
+def _as_name_set(value: Any) -> Set[str]:
+ """Coerce a ``domain`` / ``range`` value to a set of concept names.
+
+ Accepts a string, an iterable of strings / mappings, a mapping (reads its
+ ``name`` / ``label``), or ``None``. ``None`` / empty yields an empty set,
+ interpreted downstream as "unconstrained".
+ """
+ if value is None:
+ return set()
+ if isinstance(value, str):
+ return {value}
+ if isinstance(value, Mapping):
+ name = value.get("name") or value.get("label")
+ return {str(name)} if name else {str(k) for k in value}
+ if isinstance(value, Iterable):
+ out: Set[str] = set()
+ for item in value:
+ out |= _as_name_set(item)
+ return out
+ return {str(value)}
+
+
+_OWL_THING = {
+ "owl:Thing",
+ "Thing",
+ "http://www.w3.org/2002/07/owl#Thing",
+}
+
+
+def _drop_thing(names: Set[str]) -> Set[str]:
+ """Collapse an ``owl:Thing`` domain / range to *unconstrained* (empty set).
+
+ ``owl:Thing`` is the universal class, so a property whose ``domain`` / ``range``
+ is ``owl:Thing`` places no restriction. ``OntologyGenerator`` emits it as the
+ fallback when it cannot resolve endpoint types; keeping it as a literal
+ ``{"Thing"}`` constraint would reject every real endpoint, so we treat its
+ presence as "any concept".
+ """
+ return set() if names & _OWL_THING else names
+
+
+def _constraint_set(value: Any) -> Set[str]:
+ """A ``domain`` / ``range`` constraint set, with ``owl:Thing`` meaning unconstrained."""
+ return _drop_thing(_as_name_set(value))
+
+
+@dataclass(frozen=True)
+class Predicate:
+ """An allowed predicate with optional ``domain`` / ``range`` constraints.
+
+ Empty ``domain`` / ``range`` means any concept is allowed in that position.
+ """
+
+ name: str
+ domain: FrozenSet[str] = frozenset()
+ range: FrozenSet[str] = frozenset()
+
+
+@dataclass
+class ExtractionSchema:
+ """Read-only view over a domain ontology used to gate extraction.
+
+ Names are matched **exactly**: the schema vocabulary and the extraction labels
+ must share a normalization convention. ``OntologyGenerator`` normalizes concept
+ names to PascalCase and predicate names to camelCase, so entity labels /
+ relation predicates validated against a generated schema should follow the same
+ convention (e.g. label entities ``Person`` rather than ``person``).
+ """
+
+ concepts: FrozenSet[str] = field(default_factory=frozenset)
+ predicates: Dict[str, Predicate] = field(default_factory=dict)
+
+ # ---- constructors -------------------------------------------------
+
+ @classmethod
+ def from_ontology(cls, ontology: Any) -> "ExtractionSchema":
+ """Build a schema from a ``generate_ontology``-style ontology.
+
+ Accepts the mapping returned by :func:`semantica.ontology.generate_ontology`,
+ or an object exposing such a mapping via a ``.data`` attribute — e.g. the
+ ``OntologyData`` returned by ``semantica.ingest.OntologyIngestor``.
+
+ Reads ``ontology["classes"]`` (each carrying a ``name`` / ``label``) as
+ concepts and ``ontology["properties"]`` (each carrying a ``name`` and
+ optional ``domain`` / ``range``) as predicates. Missing ``domain`` /
+ ``range`` means unconstrained; unrecognised keys are ignored.
+
+ Endpoint types named in a property's ``domain`` / ``range`` are also folded
+ into the concept set (consistent with :meth:`from_owl`), so a type referenced
+ only as an endpoint — e.g. one that didn't clear the class-frequency gate
+ during induction — is still a known concept.
+ """
+ if not isinstance(ontology, Mapping) and hasattr(ontology, "data"):
+ ontology = ontology.data # unwrap OntologyData-like objects
+
+ concepts: Set[str] = set()
+ for c in ontology.get("classes", []) or []:
+ name = (c.get("name") or c.get("label")) if isinstance(c, Mapping) else c
+ if name:
+ concepts.add(str(name))
+
+ predicates: Dict[str, Predicate] = {}
+ for p in ontology.get("properties", []) or []:
+ if not isinstance(p, Mapping):
+ continue
+ name = p.get("name") or p.get("label")
+ if not name:
+ continue
+ domain = _constraint_set(p.get("domain"))
+ rng = _constraint_set(p.get("range"))
+ predicates[str(name)] = Predicate(
+ name=str(name),
+ domain=frozenset(domain),
+ range=frozenset(rng),
+ )
+ concepts |= domain | rng
+ return cls(concepts=frozenset(concepts), predicates=predicates)
+
+ @classmethod
+ def from_owl(
+ cls, source: str, *, format: Optional[str] = None
+ ) -> "ExtractionSchema":
+ """Build a schema from an OWL / RDF file path or serialized string.
+
+ ``owl:Class`` / ``rdfs:Class`` become concepts; ``owl:ObjectProperty`` with
+ ``rdfs:domain`` / ``rdfs:range`` becomes a predicate (its domain / range
+ names are folded into the concept set, with ``owl:Thing`` treated as
+ unconstrained). Names prefer an explicit ``rdfs:label``, falling back to the
+ URI's local name, so the vocabulary matches :meth:`from_ontology`. Requires
+ ``rdflib`` (an existing project dependency).
+ """
+ from rdflib import OWL, RDF, RDFS, Graph, URIRef
+
+ graph = Graph()
+ if os.path.exists(source):
+ graph.parse(source, format=format)
+ else:
+ graph.parse(data=source, format=format or "turtle")
+
+ def _local(term: Any) -> str:
+ text = str(term)
+ for sep in ("#", "/"):
+ if sep in text:
+ text = text.rsplit(sep, 1)[-1]
+ return text
+
+ def _name_of(term: Any) -> str:
+ label = graph.value(term, RDFS.label)
+ return str(label) if label is not None else _local(term)
+
+ concepts: Set[str] = {
+ _name_of(c)
+ for class_type in (OWL.Class, RDFS.Class)
+ for c in graph.subjects(RDF.type, class_type)
+ if isinstance(c, URIRef)
+ }
+ predicates: Dict[str, Predicate] = {}
+ for prop in graph.subjects(RDF.type, OWL.ObjectProperty):
+ name = _name_of(prop)
+ domain = _drop_thing(
+ {_name_of(d) for d in graph.objects(prop, RDFS.domain)}
+ )
+ rng = _drop_thing({_name_of(r) for r in graph.objects(prop, RDFS.range)})
+ predicates[name] = Predicate(
+ name=name, domain=frozenset(domain), range=frozenset(rng)
+ )
+ concepts |= domain | rng
+ return cls(concepts=frozenset(concepts), predicates=predicates)
+
+ # ---- queries ------------------------------------------------------
+
+ def has_concept(self, name: str) -> bool:
+ """Whether ``name`` is an allowed concept (entity label)."""
+ return name in self.concepts
+
+ def has_predicate(self, name: str) -> bool:
+ """Whether ``name`` is an allowed predicate."""
+ return name in self.predicates
+
+ def allows_relation(
+ self, subject_label: str, predicate: str, object_label: str
+ ) -> bool:
+ """Whether a relation conforms to the schema.
+
+ True iff subject and object are known concepts, the predicate is known,
+ and subject / object satisfy the predicate's ``domain`` / ``range``
+ (an empty ``domain`` / ``range`` allows any concept).
+
+ Membership is exact; ``subClassOf`` hierarchies are not traversed, so a
+ subclass endpoint is not accepted for a superclass ``domain`` / ``range``
+ (subclass-aware validation is a possible follow-up).
+ """
+ if subject_label not in self.concepts or object_label not in self.concepts:
+ return False
+ pred = self.predicates.get(predicate)
+ if pred is None:
+ return False
+ if pred.domain and subject_label not in pred.domain:
+ return False
+ if pred.range and object_label not in pred.range:
+ return False
+ return True
diff --git a/semantica/semantic_extract/schema_validator.py b/semantica/semantic_extract/schema_validator.py
new file mode 100644
index 00000000..e11852ca
--- /dev/null
+++ b/semantica/semantic_extract/schema_validator.py
@@ -0,0 +1,196 @@
+"""Schema-guided validation for semantic extractions.
+
+:class:`SchemaValidator` is a sibling of
+:class:`~semantica.semantic_extract.extraction_validator.ExtractionValidator`:
+same two entry points (:meth:`validate_entities` / :meth:`validate_relations`)
+returning the same :class:`ValidationResult`, so the two compose back-to-back.
+
+The two validators check **orthogonal** axes. ``ExtractionValidator`` checks
+*confidence* and structural sanity; ``SchemaValidator`` checks *conformance to a
+domain ontology*:
+
+* every entity label must be a concept in the schema;
+* every relation predicate must be in the schema and satisfy its ``domain`` /
+ ``range``.
+
+This is the deterministic core of ontology-based information extraction (OBIE,
+Wimalasuriya & Dou 2010): it needs no LLM and is fully unit-testable.
+:meth:`validate_entities` / :meth:`validate_relations` *report* conformance;
+:meth:`filter_by_schema` / :meth:`filter_relations_by_schema` return the
+conforming subset (mirroring ``ExtractionValidator.filter_by_confidence``).
+"""
+
+from __future__ import annotations
+
+from typing import Any, Dict, List, Optional, Union
+
+from .extraction_validator import ValidationResult
+from .ner_extractor import Entity
+from .relation_extractor import Relation
+from .schema import ExtractionSchema
+
+
+class SchemaValidator:
+ """Validate extractions against a domain ontology (:class:`ExtractionSchema`)."""
+
+ def __init__(
+ self, schema: ExtractionSchema, method: Optional[str] = None, **config: Any
+ ) -> None:
+ """Initialize the validator.
+
+ Args:
+ schema: The domain ontology view to validate against.
+ method: Reserved for future method-specific validation (unused),
+ mirroring ``ExtractionValidator``.
+ **config: Reserved configuration options.
+ """
+ self.schema = schema
+ self.method = method
+ self.config = config
+
+ def validate_entities(
+ self, entities: Union[List[Entity], List[List[Entity]]], **options: Any
+ ) -> Union[ValidationResult, List[ValidationResult]]:
+ """Validate that entity labels are concepts in the schema.
+
+ Handles both a single list and a batch (list of lists), like
+ ``ExtractionValidator.validate_entities``.
+ """
+ if entities and isinstance(entities, list) and isinstance(entities[0], list):
+ results = []
+ for idx, batch in enumerate(entities):
+ res = self.validate_entities(batch, **options)
+ if "batch_index" not in res.metadata:
+ res.metadata["batch_index"] = idx
+ results.append(res)
+ return results
+
+ errors: List[str] = []
+ warnings: List[str] = []
+
+ out_of_vocab = [e for e in entities if not self.schema.has_concept(e.label)]
+ unknown_labels = sorted({e.label for e in out_of_vocab})
+ if out_of_vocab:
+ errors.append(
+ f"{len(out_of_vocab)} entities with labels outside the schema: "
+ f"{', '.join(unknown_labels)}"
+ )
+
+ total = len(entities)
+ conforming = total - len(out_of_vocab)
+ metrics = {
+ "total_entities": total,
+ "in_vocabulary": conforming,
+ "out_of_vocabulary": len(out_of_vocab),
+ "unknown_labels": unknown_labels,
+ "schema_concepts": len(self.schema.concepts),
+ }
+ score = conforming / total if total else 1.0
+
+ return ValidationResult(
+ valid=not errors,
+ score=score,
+ errors=errors,
+ warnings=warnings,
+ metrics=metrics,
+ metadata=self._metadata(entities),
+ )
+
+ def validate_relations(
+ self, relations: Union[List[Relation], List[List[Relation]]], **options: Any
+ ) -> Union[ValidationResult, List[ValidationResult]]:
+ """Validate relation predicates and ``domain`` / ``range`` against the schema.
+
+ Handles both a single list and a batch (list of lists), like
+ ``ExtractionValidator.validate_relations``.
+ """
+ if relations and isinstance(relations, list) and isinstance(relations[0], list):
+ results = []
+ for idx, batch in enumerate(relations):
+ res = self.validate_relations(batch, **options)
+ if "batch_index" not in res.metadata:
+ res.metadata["batch_index"] = idx
+ results.append(res)
+ return results
+
+ errors: List[str] = []
+ warnings: List[str] = []
+
+ # Guard malformed relations (missing subject/object) before dereferencing
+ # their endpoints, matching ExtractionValidator's own leniency.
+ malformed = [r for r in relations if not r.subject or not r.object]
+ well_formed = [r for r in relations if r.subject and r.object]
+
+ unknown_predicate = [
+ r for r in well_formed if not self.schema.has_predicate(r.predicate)
+ ]
+ dr_violation = [
+ r
+ for r in well_formed
+ if self.schema.has_predicate(r.predicate)
+ and not self.schema.allows_relation(
+ r.subject.label, r.predicate, r.object.label
+ )
+ ]
+ if malformed:
+ errors.append(f"{len(malformed)} relations missing a subject or object")
+ if unknown_predicate:
+ preds = sorted({r.predicate for r in unknown_predicate})
+ errors.append(
+ f"{len(unknown_predicate)} relations with predicates outside the "
+ f"schema: {', '.join(preds)}"
+ )
+ if dr_violation:
+ errors.append(
+ f"{len(dr_violation)} relations violating domain/range constraints"
+ )
+
+ total = len(relations)
+ conforming = total - len(malformed) - len(unknown_predicate) - len(dr_violation)
+ metrics = {
+ "total_relations": total,
+ "conforming": conforming,
+ "malformed": len(malformed),
+ "unknown_predicate": len(unknown_predicate),
+ "domain_range_violation": len(dr_violation),
+ "schema_predicates": len(self.schema.predicates),
+ }
+ score = conforming / total if total else 1.0
+
+ return ValidationResult(
+ valid=not errors,
+ score=score,
+ errors=errors,
+ warnings=warnings,
+ metrics=metrics,
+ metadata=self._metadata(relations),
+ )
+
+ def filter_by_schema(self, entities: List[Entity]) -> List[Entity]:
+ """Return only entities whose label is a concept in the schema."""
+ return [e for e in entities if self.schema.has_concept(e.label)]
+
+ def filter_relations_by_schema(self, relations: List[Relation]) -> List[Relation]:
+ """Return only relations that fully conform to the schema."""
+ return [
+ r
+ for r in relations
+ if r.subject
+ and r.object
+ and self.schema.has_predicate(r.predicate)
+ and self.schema.allows_relation(
+ r.subject.label, r.predicate, r.object.label
+ )
+ ]
+
+ @staticmethod
+ def _metadata(items: List[Any]) -> Dict[str, Any]:
+ """Carry ``batch_index`` / ``document_id`` through, like ``ExtractionValidator``."""
+ metadata: Dict[str, Any] = {}
+ if items:
+ first = items[0]
+ if getattr(first, "metadata", None):
+ for key in ("batch_index", "document_id"):
+ if key in first.metadata:
+ metadata[key] = first.metadata[key]
+ return metadata
diff --git a/tests/semantic_extract/test_schema_validator.py b/tests/semantic_extract/test_schema_validator.py
new file mode 100644
index 00000000..504496d5
--- /dev/null
+++ b/tests/semantic_extract/test_schema_validator.py
@@ -0,0 +1,282 @@
+"""Unit tests for ExtractionSchema and SchemaValidator (schema-guided validation)."""
+
+from __future__ import annotations
+
+from semantica.semantic_extract import (
+ Entity,
+ ExtractionSchema,
+ ExtractionValidator,
+ Relation,
+ SchemaValidator,
+ ValidationResult,
+)
+
+ONTOLOGY = {
+ "classes": [{"name": "Person"}, {"name": "Organization"}, {"label": "City"}],
+ "properties": [
+ {"name": "worksAt", "domain": ["Person"], "range": ["Organization"]},
+ {"name": "locatedIn", "domain": "Organization", "range": "City"},
+ {"name": "knows"}, # unconstrained domain / range
+ ],
+}
+
+TTL = """
+@prefix : <https://example.org/> .
+@prefix owl: <http://www.w3.org/2002/07/owl#> .
+@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .
+
+:Person a owl:Class .
+:Organization a owl:Class .
+:worksAt a owl:ObjectProperty ;
+ rdfs:domain :Person ;
+ rdfs:range :Organization .
+"""
+
+
+def _schema() -> ExtractionSchema:
+ return ExtractionSchema.from_ontology(ONTOLOGY)
+
+
+def _person() -> Entity:
+ return Entity(text="Alice", label="Person", start_char=0, end_char=5)
+
+
+def _org() -> Entity:
+ return Entity(text="Acme", label="Organization", start_char=0, end_char=4)
+
+
+def _city() -> Entity:
+ return Entity(text="Paris", label="City", start_char=0, end_char=5)
+
+
+def _product() -> Entity:
+ return Entity(text="Widget", label="Product", start_char=0, end_char=6)
+
+
+# --------------------------------------------------------------------------- #
+# ExtractionSchema
+# --------------------------------------------------------------------------- #
+
+
+def test_from_ontology_parses_concepts_and_predicates() -> None:
+ schema = _schema()
+ assert schema.concepts == frozenset({"Person", "Organization", "City"})
+ assert set(schema.predicates) == {"worksAt", "locatedIn", "knows"}
+ assert schema.predicates["worksAt"].domain == frozenset({"Person"})
+ assert schema.predicates["worksAt"].range == frozenset({"Organization"})
+ # Missing domain / range means unconstrained.
+ assert schema.predicates["knows"].domain == frozenset()
+ assert schema.predicates["knows"].range == frozenset()
+
+
+def test_allows_relation_respects_domain_range() -> None:
+ schema = _schema()
+ assert schema.allows_relation("Person", "worksAt", "Organization")
+ assert not schema.allows_relation("Person", "worksAt", "City") # range violation
+ assert not schema.allows_relation("Person", "unknownPred", "Organization")
+ assert not schema.allows_relation("Product", "worksAt", "Organization") # off-vocab
+ # Unconstrained predicate accepts any known concepts.
+ assert schema.allows_relation("Person", "knows", "City")
+
+
+def test_from_owl_parses_turtle() -> None:
+ schema = ExtractionSchema.from_owl(TTL, format="turtle")
+ assert {"Person", "Organization"} <= schema.concepts
+ assert schema.predicates["worksAt"].domain == frozenset({"Person"})
+ assert schema.predicates["worksAt"].range == frozenset({"Organization"})
+
+
+# --------------------------------------------------------------------------- #
+# SchemaValidator — entities
+# --------------------------------------------------------------------------- #
+
+
+def test_validate_entities_all_conforming() -> None:
+ result = SchemaValidator(_schema()).validate_entities([_person(), _org(), _city()])
+ assert isinstance(result, ValidationResult)
+ assert result.valid
+ assert result.score == 1.0
+ assert result.metrics["out_of_vocabulary"] == 0
+
+
+def test_validate_entities_flags_out_of_vocabulary() -> None:
+ result = SchemaValidator(_schema()).validate_entities([_person(), _product()])
+ assert not result.valid
+ assert result.metrics["out_of_vocabulary"] == 1
+ assert result.metrics["unknown_labels"] == ["Product"]
+ assert result.score == 0.5
+ assert result.errors
+
+
+def test_validate_entities_empty_is_vacuously_valid() -> None:
+ result = SchemaValidator(_schema()).validate_entities([])
+ assert result.valid
+ assert result.score == 1.0
+
+
+def test_validate_entities_batch_returns_list_with_index() -> None:
+ results = SchemaValidator(_schema()).validate_entities([[_person()], [_product()]])
+ assert isinstance(results, list)
+ assert len(results) == 2
+ assert results[0].valid
+ assert not results[1].valid
+ assert results[0].metadata["batch_index"] == 0
+ assert results[1].metadata["batch_index"] == 1
+
+
+# --------------------------------------------------------------------------- #
+# SchemaValidator — relations
+# --------------------------------------------------------------------------- #
+
+
+def test_validate_relations_conforming() -> None:
+ rels = [
+ Relation(subject=_person(), predicate="worksAt", object=_org()),
+ Relation(subject=_person(), predicate="knows", object=_city()),
+ ]
+ result = SchemaValidator(_schema()).validate_relations(rels)
+ assert result.valid
+ assert result.score == 1.0
+
+
+def test_validate_relations_flags_unknown_predicate_and_domain_range() -> None:
+ rels = [
+ Relation(subject=_person(), predicate="worksAt", object=_org()), # ok
+ Relation(subject=_person(), predicate="founded", object=_org()), # unknown pred
+ Relation(subject=_person(), predicate="worksAt", object=_city()), # range viol
+ ]
+ result = SchemaValidator(_schema()).validate_relations(rels)
+ assert not result.valid
+ assert result.metrics["unknown_predicate"] == 1
+ assert result.metrics["domain_range_violation"] == 1
+ assert result.metrics["conforming"] == 1
+ assert result.score == 1 / 3
+
+
+# --------------------------------------------------------------------------- #
+# Filtering
+# --------------------------------------------------------------------------- #
+
+
+def test_filter_by_schema_drops_off_vocabulary() -> None:
+ kept = SchemaValidator(_schema()).filter_by_schema([_person(), _org(), _product()])
+ assert [e.label for e in kept] == ["Person", "Organization"]
+
+
+def test_filter_relations_by_schema_keeps_only_conforming() -> None:
+ rels = [
+ Relation(subject=_person(), predicate="worksAt", object=_org()), # keep
+ Relation(subject=_person(), predicate="founded", object=_org()), # drop
+ Relation(subject=_person(), predicate="worksAt", object=_city()), # drop
+ Relation(subject=_person(), predicate="knows", object=_city()), # keep
+ ]
+ kept = SchemaValidator(_schema()).filter_relations_by_schema(rels)
+ assert [r.predicate for r in kept] == ["worksAt", "knows"]
+
+
+# --------------------------------------------------------------------------- #
+# Composition with the confidence-based ExtractionValidator (orthogonal axis)
+# --------------------------------------------------------------------------- #
+
+
+def test_composes_with_extraction_validator_same_shape() -> None:
+ entities = [_person(), _org()]
+ confidence = ExtractionValidator().validate_entities(entities)
+ conformance = SchemaValidator(_schema()).validate_entities(entities)
+ assert isinstance(confidence, ValidationResult)
+ assert isinstance(conformance, ValidationResult)
+
+
+# --------------------------------------------------------------------------- #
+# Robustness fixes surfaced in review
+# --------------------------------------------------------------------------- #
+
+
+def test_owl_thing_domain_range_is_unconstrained() -> None:
+ # OntologyGenerator emits owl:Thing when it cannot resolve endpoint types;
+ # it must behave as "any concept", not a literal {"Thing"} constraint.
+ ont = {
+ "classes": [{"name": "Person"}, {"name": "Organization"}],
+ "properties": [
+ {"name": "relatedTo", "domain": ["owl:Thing"], "range": ["owl:Thing"]}
+ ],
+ }
+ schema = ExtractionSchema.from_ontology(ont)
+ assert schema.predicates["relatedTo"].domain == frozenset()
+ assert schema.predicates["relatedTo"].range == frozenset()
+ assert schema.allows_relation("Person", "relatedTo", "Organization")
+
+
+def test_from_owl_prefers_rdfs_label_and_supports_rdfs_class() -> None:
+ ttl = """
+ @prefix : <https://example.org/> .
+ @prefix owl: <http://www.w3.org/2002/07/owl#> .
+ @prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .
+
+ :Cls1 a owl:Class ; rdfs:label "Person" .
+ :Org a rdfs:Class .
+ :worksAt a owl:ObjectProperty ;
+ rdfs:domain :Cls1 ;
+ rdfs:range :Org .
+ """
+ schema = ExtractionSchema.from_owl(ttl, format="turtle")
+ # rdfs:label wins over the URI suffix "Cls1"
+ assert "Person" in schema.concepts
+ assert "Cls1" not in schema.concepts
+ # rdfs:Class is picked up too
+ assert "Org" in schema.concepts
+ assert schema.predicates["worksAt"].domain == frozenset({"Person"})
+
+
+def test_validate_relations_handles_malformed_without_crashing() -> None:
+ # A relation missing an endpoint must be reported, not raise AttributeError.
+ good = Relation(subject=_person(), predicate="worksAt", object=_org())
+ bad = Relation(subject=_person(), predicate="worksAt", object=None) # type: ignore[arg-type]
+ result = SchemaValidator(_schema()).validate_relations([good, bad])
+ assert isinstance(result, ValidationResult)
+ assert not result.valid
+ assert result.metrics["malformed"] == 1
+ assert result.metrics["conforming"] == 1
+ # Filtering also drops the malformed one instead of crashing.
+ kept = SchemaValidator(_schema()).filter_relations_by_schema([good, bad])
+ assert kept == [good]
+
+
+def test_from_ontology_folds_endpoint_types_like_from_owl() -> None:
+ # pkupt's case: an endpoint type (Org) that didn't clear the class-frequency
+ # gate is absent from "classes" but referenced in a property's range. Both
+ # constructors must agree that (Person, worksFor, Org) is allowed.
+ ont = {
+ "classes": [{"name": "Person"}],
+ "properties": [{"name": "worksFor", "domain": ["Person"], "range": ["Org"]}],
+ }
+ dict_schema = ExtractionSchema.from_ontology(ont)
+ assert {"Person", "Org"} <= dict_schema.concepts
+ assert dict_schema.allows_relation("Person", "worksFor", "Org")
+
+ ttl = """
+ @prefix : <https://example.org/> .
+ @prefix owl: <http://www.w3.org/2002/07/owl#> .
+ @prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .
+
+ :Person a owl:Class .
+ :worksFor a owl:ObjectProperty ;
+ rdfs:domain :Person ;
+ rdfs:range :Org .
+ """
+ owl_schema = ExtractionSchema.from_owl(ttl, format="turtle")
+ assert owl_schema.allows_relation(
+ "Person", "worksFor", "Org"
+ ) == dict_schema.allows_relation("Person", "worksFor", "Org")
+
+
+def test_from_ontology_accepts_ontologydata_like_object() -> None:
+ # semantica.ingest.OntologyIngestor.ingest_ontology returns an OntologyData
+ # whose ontology dict is held in `.data`; from_ontology should unwrap it
+ # instead of raising AttributeError on `.get()`.
+ from types import SimpleNamespace
+
+ wrapped = SimpleNamespace(data=ONTOLOGY)
+ schema = ExtractionSchema.from_ontology(wrapped)
+ assert schema.concepts == frozenset({"Person", "Organization", "City"})
+ assert "worksAt" in schema.predicates