Skip to content

Commit 0ce485e

Browse files
cmungallclaude
andcommitted
Fix crash when validated data has keys not defined in the schema
The recursive traversal in `_validate_instance` looked up every key in the instance with `SchemaView.induced_slot`, guarding only with `if not slot: continue`. But `induced_slot` raises `ValueError` for unknown slots rather than returning a falsy value, so any data key that is not a defined slot on its class (a stray `id`, a metadata field, a typo) crashed the entire validation — including through the full `Validator` pipeline used by the CLI. Skip keys that are not in the class's slots before calling `induced_slot`. Add tests covering an unknown top-level key, an unknown nested key, and the full Validator pipeline. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
1 parent 36b5cdd commit 0ce485e

2 files changed

Lines changed: 137 additions & 1 deletion

File tree

‎src/linkml_reference_validator/plugins/reference_validation_plugin.py‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -242,8 +242,13 @@ def _validate_instance( # type: ignore
242242
# Break after processing first reference field with a value
243243
break
244244

245+
# Only slots actually defined on the class can be induced; data may
246+
# carry extra keys (a stray ``id``, metadata, a typo) that are not
247+
# slots. induced_slot() raises ValueError for those, so skip them.
248+
class_slots = set(self.schema_view.class_slots(class_name))
249+
245250
for slot_name, value in instance.items():
246-
if value is None:
251+
if value is None or slot_name not in class_slots:
247252
continue
248253

249254
slot = self.schema_view.induced_slot(slot_name, class_name)
Lines changed: 131 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,131 @@
1+
"""Tests that recursive traversal tolerates data keys not defined in the schema.
2+
3+
The plugin walks an instance's keys and looks up each one with
4+
``SchemaView.induced_slot``. That call raises ``ValueError`` for unknown slots,
5+
so any extra key in the data (a stray ``id``, a typo, a metadata field) used to
6+
crash the whole validation instead of being skipped. These tests pin the
7+
behaviour: unknown keys are ignored and known nested evidence is still reached.
8+
"""
9+
10+
from pathlib import Path
11+
12+
import pytest
13+
from linkml_runtime.utils.schemaview import SchemaView # type: ignore[import-untyped]
14+
from linkml.validator import Validator # type: ignore[import-untyped]
15+
from linkml.validator.validation_context import ( # type: ignore[import-untyped]
16+
ValidationContext,
17+
)
18+
19+
from linkml_reference_validator.models import ReferenceValidationConfig
20+
from linkml_reference_validator.plugins.reference_validation_plugin import (
21+
ReferenceValidationPlugin,
22+
)
23+
24+
25+
DATA_DIR = Path(__file__).parent / "data"
26+
FIXTURES_DIR = Path(__file__).parent / "fixtures"
27+
SCHEMA = DATA_DIR / "test_schema.yaml"
28+
29+
30+
def _make_cache(tmp_path):
31+
"""Build a cache dir seeded with the tracked reference fixtures."""
32+
cache_dir = tmp_path / "cache"
33+
cache_dir.mkdir()
34+
for fixture_file in FIXTURES_DIR.glob("*.md"):
35+
(cache_dir / fixture_file.name).write_text(fixture_file.read_text())
36+
for fixture_file in FIXTURES_DIR.glob("*.txt"):
37+
(cache_dir / fixture_file.name).write_text(fixture_file.read_text())
38+
return cache_dir
39+
40+
41+
@pytest.fixture
42+
def plugin(tmp_path):
43+
"""Plugin with a cache seeded from the tracked fixtures."""
44+
config = ReferenceValidationConfig(
45+
cache_dir=_make_cache(tmp_path),
46+
rate_limit_delay=0.0,
47+
)
48+
return ReferenceValidationPlugin(config=config)
49+
50+
51+
@pytest.fixture
52+
def schema_view():
53+
"""SchemaView for the shared test schema."""
54+
return SchemaView(str(SCHEMA))
55+
56+
57+
def test_unknown_top_level_key_does_not_crash(plugin, schema_view):
58+
"""An extra top-level key not in the schema must be skipped, not crash."""
59+
instance = {
60+
"id": "statement:001", # not a slot on Statement
61+
"text": "Protein X functions in cell cycle regulation",
62+
"has_evidence": [
63+
{
64+
"reference": {"id": "PMID:TEST001", "title": "Study of Protein X"},
65+
"supporting_text": "Protein X functions in cell cycle regulation",
66+
}
67+
],
68+
}
69+
70+
context = ValidationContext(schema_view.schema, target_class="Statement")
71+
plugin.pre_process(context)
72+
73+
# Should not raise ValueError for the unknown "id" slot.
74+
list(plugin.process(instance, context))
75+
76+
77+
def test_unknown_nested_key_does_not_crash(plugin, schema_view):
78+
"""An extra key on a nested object must be skipped, not crash."""
79+
instance = {
80+
"text": "Some statement",
81+
"has_evidence": [
82+
{
83+
"id": "evidence:001", # not a slot on Evidence
84+
"category": "experimental", # also not a slot
85+
"reference": {"id": "PMID:TEST001", "title": "Study of Protein X"},
86+
"supporting_text": "fabricated text not in the reference at all",
87+
}
88+
],
89+
}
90+
91+
context = ValidationContext(schema_view.schema, target_class="Statement")
92+
plugin.pre_process(context)
93+
94+
# Traversal must still reach the evidence and reject the bad snippet.
95+
results = list(plugin.process(instance, context))
96+
assert len(results) > 0, (
97+
"Plugin should skip unknown nested keys but still validate the "
98+
"evidence's invalid supporting_text"
99+
)
100+
101+
102+
def test_unknown_key_through_full_validator_pipeline(tmp_path):
103+
"""End-to-end: an unknown key must not break the full Validator pipeline."""
104+
config = ReferenceValidationConfig(
105+
cache_dir=_make_cache(tmp_path),
106+
rate_limit_delay=0.0,
107+
)
108+
plugin = ReferenceValidationPlugin(config=config)
109+
validator = Validator(
110+
schema=str(SCHEMA),
111+
validation_plugins=[plugin],
112+
)
113+
114+
instance = {
115+
"id": "statement:001", # not a slot on Statement
116+
"text": "Some statement",
117+
"has_evidence": [
118+
{
119+
"reference": {"id": "PMID:TEST001"},
120+
"supporting_text": "fabricated text not in the reference at all",
121+
}
122+
],
123+
}
124+
125+
# The reference plugin must run without raising on the unknown "id" key.
126+
report = validator.validate(instance, target_class="Statement")
127+
ref_results = [r for r in report.results if r.type == "reference_validation"]
128+
assert len(ref_results) > 0, (
129+
"Full pipeline should reach the evidence and flag the invalid snippet "
130+
"even when the instance carries an unknown 'id' key"
131+
)

0 commit comments

Comments
 (0)