Skip to content

fix(context): treat non-list relationship models as validation error - #2607

Closed
Bartok9 wants to merge 1 commit into
Canner:mainfrom
Bartok9:fix/context-rel-models-type
Closed

Bartok9 wants to merge 1 commit into
Canner:mainfrom
Bartok9:fix/context-rel-models-type

Conversation

@Bartok9

@Bartok9 Bartok9 commented Jul 28, 2026 •

Copy link
Copy Markdown
Contributor

Summary

validate_project reports a hard error when a relationship's models is not a list, instead of iterating a string as character endpoint names.

Motivation

Related to #2590. Manifest validation should surface structural type errors.

Real behavior proof

pytest tests/unit/test_context.py::test_validate_relationship_models_must_be_list -q
# 1 passed

Test plan

  • string models → must-be-list error

Summary by CodeRabbit

  • Bug Fixes
    • Improved project validation for relationship model definitions.
    • Invalid non-list values now produce a clear validation error instead of being processed incorrectly.
    • Missing or null relationship model lists continue to be handled safely.

@github-actions github-actions Bot added python Pull requests that update Python code core labels Jul 28, 2026
@coderabbitai

coderabbitai Bot commented Jul 28, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Walkthrough

validate_project now validates relationship models fields as lists, reports structural errors for invalid types, and adds a unit test covering string input.

Changes

Relationship model validation

Layer / File(s) Summary
Validate relationship models input
core/wren/src/wren/context.py, core/wren/tests/unit/test_context.py
Missing relationship models default to an empty list; non-list values produce hard validation errors, with unit coverage for string input.

Estimated code review effort: 2 (Simple) | ~10 minutes

Possibly related PRs

  • Canner/WrenAI#2494: Also updates relationship models: null handling in validate_project and adds related regression coverage.

Suggested reviewers: goldmedal

Poem

I’m a bunny guarding models in a list,
Strings at the gate are firmly dismissed.
Nulls hop gently to an empty array,
Errors now bloom when types go astray.
Tests nibble the edge cases bright—
Validation’s tidy tonight!

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and accurately summarizes the main change: non-list relationship models are now validated as errors.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@core/wren/src/wren/context.py`:
- Around line 1161-1171: Update the relationship-model validation loop in the
context validation logic to verify each entry is a string before checking
membership in all_entity_names. For non-string entries, append a ValidationError
using the indexed models path (including the relationship name and entry index),
then continue validating subsequent entries without performing set membership on
the invalid value.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 1fd0b408-fc9c-4773-81bc-4b366fab0723

📥 Commits

Reviewing files that changed from the base of the PR and between a93184d and 8bf7983.

📒 Files selected for processing (2)
  • core/wren/src/wren/context.py
  • core/wren/tests/unit/test_context.py

Comment on lines +1161 to 1171
if not isinstance(ref_models, list):
errors.append(
ValidationError(
"error",
f"relationships > {rel_name}",
f"'models' must be a list, got {type(ref_models).__name__}",
)
)
ref_models = []
for m in ref_models:
if m not in all_entity_names:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🩺 Stability & Availability | 🔴 Critical | ⚡ Quick win

Validate each relationship model entry before set membership.

A value such as models: [{}] passes the list check, then m not in all_entity_names raises TypeError: unhashable type: 'dict' instead of returning validation errors. Reject non-string entries with an indexed path and continue validation.

Proposed fix
-        for m in ref_models:
+        for j, m in enumerate(ref_models):
+            if not isinstance(m, str):
+                errors.append(
+                    ValidationError(
+                        "error",
+                        f"relationships > {rel_name} > models[{j}]",
+                        "'models' entries must be strings",
+                    )
+                )
+                continue
             if m not in all_entity_names:
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if not isinstance(ref_models, list):
errors.append(
ValidationError(
"error",
f"relationships > {rel_name}",
f"'models' must be a list, got {type(ref_models).__name__}",
)
)
ref_models = []
for m in ref_models:
if m not in all_entity_names:
if not isinstance(ref_models, list):
errors.append(
ValidationError(
"error",
f"relationships > {rel_name}",
f"'models' must be a list, got {type(ref_models).__name__}",
)
)
ref_models = []
for j, m in enumerate(ref_models):
if not isinstance(m, str):
errors.append(
ValidationError(
"error",
f"relationships > {rel_name} > models[{j}]",
"'models' entries must be strings",
)
)
continue
if m not in all_entity_names:
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@core/wren/src/wren/context.py` around lines 1161 - 1171, Update the
relationship-model validation loop in the context validation logic to verify
each entry is a string before checking membership in all_entity_names. For
non-string entries, append a ValidationError using the indexed models path
(including the relationship name and entry index), then continue validating
subsequent entries without performing set membership on the invalid value.

@goldmedal

Copy link
Copy Markdown
Collaborator

This is the reporting half of a change whose loader half is in #2613 — and #2604 landed as 9bdae39 after this branch was opened, setting the convention both should follow.

_load_views_v1 drops malformed entries silently and validate_project reports them, so a hand-edit never vanishes without the user hearing about it. The merged comment states the rule explicitly:

load_views() silently drops those (matching the other loaders), but validate_project's job is to tell the user about hand-edited mistakes rather than let them vanish quietly, so re-check the raw entries here.

Measured on main + this branch, with the same shape of bad data in each file:

views.yml — reported (9bdae39):

[ERROR] views.yml > views[0]: view entry must be a mapping, got str
[ERROR] views.yml > views[1]: view entry must be a mapping, got int

relationships.yml — silently gone:

relationships:
  - not-a-mapping
  - 42
  - {name: ok, models: [...], join_type: MANY_TO_ONE, condition: ...}

load_relationships() -> [{'name': 'ok', ...}]       # the two junk entries dropped
validate_project()   -> no message mentions them at all

Same repo, same file type, same class of bad data, opposite user experience.

What to do

#2613 and #2607 are the two halves of one change and should be a single PR — the relationships counterpart of 9bdae39:

Note the ordering trap: with #2613's filter in place, validate_project never sees the junk entries, so the reporting must read the raw YAML the way 9bdae39 does — not the loader output.

That pair also makes #2606 (memory/seed_queries.py) and #2608 (mcp_server.py) unnecessary: once context.py normalises relationships to list[dict], re-guarding at each consumer is exactly the downstream duplication #2613's own comment argues against ("so every consumer trusts the contract without re-filtering at each callsite"). Please close those two rather than landing three copies of one guard — the contribution bar asks for a mechanical change repeated across files to come as one PR.

Rebase

This branch is 17 commits behind main and its CI ran against a base that predates 9bdae39. It merges cleanly, but a textually clean merge is not a semantically correct one — please rebase and re-run.

@Bartok9

Bartok9 commented Aug 7, 2026

Copy link
Copy Markdown
Contributor Author

Closing per @goldmedal on #2613/#2607: relationships hardening belongs in one context.py PR matching 9bdae39 (#2604).

Superseded by #2613 (load + validate raw YAML). Downstream consumer re-guards are redundant once context normalizes list[dict].

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

core python Pull requests that update Python code

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants