Skip to content

Fix crash when validated data has keys not defined in the schema - #46

Merged
cmungall merged 1 commit into
mainfrom
worktree-fix-plugin-unknown-slot-crash
Jun 12, 2026
Merged

cmungall merged 1 commit into
mainfrom
worktree-fix-plugin-unknown-slot-crash

Conversation

@cmungall

Copy link
Copy Markdown
Member

Problem

The recursive traversal in ReferenceValidationPlugin._validate_instance walks every key of an instance and resolves it with SchemaView.induced_slot, guarding only with:

slot = self.schema_view.induced_slot(slot_name, class_name)
if not slot:
    continue

But induced_slot raises ValueError for unknown slots — it never returns a falsy value. So any data key that isn't a defined slot on its class (a stray id, a metadata field, a typo) crashes the entire validation, including through the full Validator pipeline used by validate data on the CLI.

Reproduction (a bare id field is enough):

ValueError: No such slot id as an attribute of Community ancestors or as a slot definition in the schema

Fix

Filter keys against the class's declared slots before calling induced_slot:

class_slots = set(self.schema_view.class_slots(class_name))
for slot_name, value in instance.items():
    if value is None or slot_name not in class_slots:
        continue
    ...

This avoids a try/except (per the repo's style guidance) and is the minimal change.

Tests

Added tests/test_unknown_slot_traversal.py (test-first; all three failed with the ValueError before the fix):

  • unknown top-level key is skipped, no crash
  • unknown nested key is skipped, evidence is still reached and its invalid snippet rejected
  • the full Validator pipeline tolerates an unknown id key

Full non-integration suite: 484 passed. mypy and ruff clean.

🤖 Generated with Claude Code

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>
@claude

claude Bot commented Jun 12, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @cmungall's task —— View job


Code Review Complete ✅

Todo List:

  • Read the modified plugin file to understand the fix implementation
  • Read the new test file to evaluate test coverage and quality
  • Analyze code quality and adherence to best practices
  • Check for potential bugs or edge cases
  • Evaluate performance considerations
  • Review security concerns
  • Provide comprehensive feedback

🎯 Summary

This is an excellent fix that addresses a critical crash issue with minimal, surgical changes. The implementation follows best practices and includes comprehensive tests.

✅ Code Quality & Best Practices

Strengths:

  • Minimal, targeted fix: Only 3 lines of actual code change (plus comments)
  • Follows repo style: Avoids try/except blocks per CLAUDE.md guidance
  • Self-documenting: Clear inline comments explaining the rationale
  • Consistent naming: Uses established class_slots pattern
  • Performance-conscious: Pre-computes slot set once vs repeated lookups

Implementation Quality: src/linkml_reference_validator/plugins/reference_validation_plugin.py:245-251

# Only slots actually defined on the class can be induced; data may
# carry extra keys (a stray ``id``, metadata, a typo) that are not
# slots. induced_slot() raises ValueError for those, so skip them.
class_slots = set(self.schema_view.class_slots(class_name))

for slot_name, value in instance.items():
    if value is None or slot_name not in class_slots:
        continue

The fix is elegant - filtering keys before the problematic induced_slot() call rather than wrapping it in exception handling.

🐛 Bug Analysis

Problem correctly identified: SchemaView.induced_slot() raises ValueError for unknown slots rather than returning falsy values, contradicting the original guard logic.

Solution is robust: The pre-filtering approach ensures unknown keys are skipped entirely, preventing crashes while preserving all intended validation behavior.

No edge cases identified: The fix handles all scenarios correctly:

  • Top-level unknown keys ✓
  • Nested unknown keys ✓
  • Mixed valid/invalid keys ✓
  • Empty slot sets ✓

🚀 Performance Considerations

Improvement over original:

  • Before: Every key triggered induced_slot() call + potential ValueError
  • After: Single class_slots() call + O(1) set lookups

Efficiency: Converting to set() ensures O(1) membership testing vs O(n) list searches.

No performance concerns: The overhead of set(self.schema_view.class_slots(class_name)) is negligible and only called once per instance.

🔒 Security Assessment

No security issues identified:

  • Input filtering is restrictive (removes unknown keys)
  • No new attack vectors introduced
  • Maintains existing validation integrity
  • No sensitive data exposure risks

🧪 Test Coverage Excellence

Comprehensive test suite in tests/test_unknown_slot_traversal.py:

  1. test_unknown_top_level_key_does_not_crash: Verifies fix at root level
  2. test_unknown_nested_key_does_not_crash: Tests nested object traversal continues correctly
  3. test_unknown_key_through_full_validator_pipeline: End-to-end integration test

Test quality highlights:

  • Test-driven approach: Tests were written first and failed before the fix
  • Realistic scenarios: Uses actual problematic patterns (stray id fields)
  • Assertion clarity: Clear failure messages explaining expected behavior
  • Good separation: Tests different layers (plugin direct, nested traversal, full pipeline)
  • Fixtures well-designed: Reusable components with proper cleanup

📝 Minor Suggestions

  1. Documentation: Consider adding a docstring example showing how unknown keys are handled:

    Examples:
        >>> # Data with unknown 'id' key is safely processed
        >>> instance = {"id": "stmt:001", "text": "valid content"}
        >>> # 'id' is skipped, 'text' is processed normally
  2. Test naming consistency: The test file name test_unknown_slot_traversal.py is perfect and follows the established naming pattern.

🏆 Verdict

Strongly recommend approval. This PR:

  • ✅ Fixes a critical production crash
  • ✅ Follows all project conventions and style guidelines
  • ✅ Includes comprehensive test coverage
  • ✅ Has no performance or security concerns
  • ✅ Makes minimal, surgical changes
  • ✅ Is well-documented with clear rationale

The fix demonstrates excellent software engineering practices: identifying root cause, choosing the most appropriate solution approach, implementing minimally, and testing thoroughly.


@cmungall
cmungall merged commit 3e79833 into main Jun 12, 2026
7 checks passed
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