Skip to content

fix(context): harden relationships load + validate like views - #2613

Merged
goldmedal merged 4 commits into
Canner:mainfrom
Bartok9:fix/load-relationships-dict-items
Aug 10, 2026
Merged

goldmedal merged 4 commits into
Canner:mainfrom
Bartok9:fix/load-relationships-dict-items

Conversation

@Bartok9

@Bartok9 Bartok9 commented Jul 29, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Relationships counterpart of 9bdae39 (#2604):

  • load_relationships filters to list[dict] (drop non-mapping entries)
  • validate_project re-reads raw relationships.yml and reports:
    • 'relationships' must be a list, got …
    • relationship entry must be a mapping, got …

Motivation

After #2604, views report hand-edited junk; relationships silently dropped it. Same class of bad data, opposite UX.

Note on siblings

This supersedes the split approach in #2607 (reporting half only / models-field only). Downstream consumer re-guards #2606/#2608 become unnecessary once context normalizes the contract — closing those as follow-through.

Verification

cd core/wren && python -m pytest tests/unit/test_context.py -q -k relationship

Summary by CodeRabbit

  • Bug Fixes
    • Improved validation for relationship configuration files.
    • Invalid relationship entries are now reported clearly instead of causing unexpected behavior.
    • Relationship collections with unsupported formats now produce validation errors.
    • Valid relationship definitions continue to load while malformed entries are safely ignored.
    • Validation now preserves the original location of entries, making configuration errors easier to identify and fix.

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

coderabbitai Bot commented Jul 29, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: df3de0b9-bf8e-485f-8803-3004e9b70cd7

📥 Commits

Reviewing files that changed from the base of the PR and between 1df2510 and 0d16697.

📒 Files selected for processing (1)
  • core/wren/tests/unit/test_context.py
🚧 Files skipped from review as they are similar to previous changes (1)
  • core/wren/tests/unit/test_context.py

Walkthrough

load_relationships() accepts mapping-root YAML with list-valued relationships and filters non-mapping entries. validate_project() reports malformed roots, collections, and entries while preserving source indices. Unit tests cover these cases.

Changes

Relationship YAML validation

Layer / File(s) Summary
Validate and test relationship loading
core/wren/src/wren/context.py, core/wren/tests/unit/test_context.py
load_relationships() filters invalid relationship entries. validate_project() reports malformed roots and collections, removes duplicate entry errors, and preserves source indices for later checks. Unit tests cover each validation case.

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

Possibly related PRs

  • Canner/WrenAI#2604: Both changes update relationship YAML loading and validation in context.py, with corresponding tests.

Poem

A rabbit checks each YAML line,
Keeps valid mappings neat and fine.
Bad entries raise a clear alert,
Source indices stay in place.
Tests guard every case.
🐇

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description includes the summary and test command but omits the required failure reproduction with actual error output and the duplicate check. Add the observed reproduction and actual error output under “What failure does this repair?” and list the open PRs checked under “Duplicate check”.
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly identifies the main change: hardening relationship loading and validation in context.
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.

@goldmedal

Copy link
Copy Markdown
Collaborator

The loader half here is right, but #2604 landed as 9bdae39 after this branch was opened and set the convention for exactly this situation — and this PR implements only half of it.

_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.

Match 9bdae39 (Canner#2604): load_relationships drops non-dict entries;
validate_project re-reads raw relationships.yml and reports malformed
list/entries so hand-edits do not vanish silently.
@Bartok9
Bartok9 force-pushed the fix/load-relationships-dict-items branch from 0245eba to f70dd32 Compare August 7, 2026 04:14
@Bartok9 Bartok9 changed the title fix(context): filter non-dict items in load_relationships fix(context): harden relationships load + validate like views Aug 7, 2026
@Bartok9

Bartok9 commented Aug 7, 2026

Copy link
Copy Markdown
Contributor Author

Thanks @goldmedal — agreed on the #2604 pattern.

Rebased onto current main and folded both halves into this PR:

  1. load_relationships → list[dict] (silent drop, same as views loaders)
  2. validate_project re-checks raw YAML for non-list relationships and non-mapping entries (so junk is reported, not only filtered)

Also closing #2607 as the incomplete reporting-only half, and #2606/#2608 as redundant consumer re-guards once this lands.

@coderabbitai

coderabbitai Bot commented Aug 7, 2026

Copy link
Copy Markdown
Contributor

Note

GitHub couldn't provide a complete incremental comparison for this pull request, so CodeRabbit is performing a full review instead. This review may take a little longer.

@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

🧹 Nitpick comments (1)
core/wren/tests/unit/test_context.py (1)

1761-1766: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

Assert the concrete type in the validation message.

The validation contract includes the offending type. This assertion only checks the prefix, so it would pass if got str were removed.

Proposed test assertion
-    assert any("'relationships' must be a list" in m for m in msgs)
+    assert any("'relationships' must be a list, got str" in m for m in msgs)
🤖 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/tests/unit/test_context.py` around lines 1761 - 1766, Strengthen
test_validate_project_reports_relationships_not_list by asserting the complete
validation message includes both "'relationships' must be a list" and the
offending type "got str", rather than checking only the message prefix.
🤖 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/tests/unit/test_context.py`:
- Line 10: Fix the import statement in test_context.py by moving
load_relationships and validate_project inside the parenthesized from
wren.context import list, preserving the existing imported symbols and valid
Python syntax.

---

Nitpick comments:
In `@core/wren/tests/unit/test_context.py`:
- Around line 1761-1766: Strengthen
test_validate_project_reports_relationships_not_list by asserting the complete
validation message includes both "'relationships' must be a list" and the
offending type "got str", rather than checking only the message prefix.
🪄 Autofix

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: 61fcd03b-3ca1-4dde-9141-5e8da4ea159f

📥 Commits

Reviewing files that changed from the base of the PR and between 9bdae39 and f70dd32.

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

Comment thread core/wren/tests/unit/test_context.py Resolved
Include load_relationships/validate_project inside the import paren list.

@goldmedal goldmedal left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Approve with changes. The core fix is correct and the motivation checks out. Three things should be cleaned up first; one is cosmetic-but-real, two are behavioral.

What I verified

CI is green across all 8 jobs. pytest tests/unit/test_context.py → 132 passed locally.

The fix is genuinely worth having — I reproduced the before/after on relationships: nope:

MAIN:  load_relationships() -> 'nope'          # str, not list[dict]
       [ERROR] relationships[0]: relationship entry must be an object
       [ERROR] relationships[1]: ... [2] ... [3]     # iterating "n","o","p","e"

PR:    load_relationships() -> []
       [ERROR] relationships.yml > relationships: 'relationships' must be a list, got str

Four garbage errors from iterating a string's characters → one accurate one. The loader also now actually honors its list[dict] annotation, which is what makes the downstream re-guards unnecessary as claimed — mcp_server.describe_model (rel.get("models"), line 267) and context_cli.py:553 both consume it unguarded today.

1. Duplicate imports in the test file — should fix

from wren.context import (
    load_relationships,      # ← added
    validate_project,        # ← added
    UpgradeError,
    ...
    load_relationships,      # ← already there (line 25)
    ...
    validate_project,        # ← already there (line 30)
)

Both names were already imported. The follow-up commit a54c844b moved them inside the parens (addressing the earlier syntax catch) but didn't notice they were redundant. Net effect: ruff check tests/unit/test_context.py now fails I001.

CI won't catch this — the lint job runs ruff check src/ only, not tests/ — so it's not a merge blocker, but the file goes from lint-clean to not. Fix is deleting the two added lines.

2. The PR leaves dead code behind — should fix

context.py:1223-1232, inside the "Check relationships" loop:

for i, rel in enumerate(relationships):
    if not isinstance(rel, dict):
        errors.append(ValidationError("error", f"relationships[{i}]",
                      "relationship entry must be an object"))
        continue

relationships now comes from the filtering loader, so this branch is unreachable. It also carries a different message for the same condition than the new block ("must be an object" vs "must be a mapping, got int"). The views precedent (9bdae39) has no equivalent guard in its loop — removing this is what actually makes the two paths symmetric.

3. Entry indices no longer match the file — worth a look

Because filtering happens before the loop, indices in the main loop are now positions in the filtered list. Repro — file with - 42 at index 0 and an unnamed relationship at index 1:

MAIN:  [ERROR]   relationships[0]: relationship entry must be an object
       [WARNING] relationships > relationships[1]: missing join_type      ← correct

PR:    [ERROR]   relationships.yml > relationships[0]: ... got int
       [WARNING] relationships > relationships[0]: missing join_type      ← now wrong

Two errors both labelled relationships[0], pointing at different entries. #2604 has the same wart for views, so it's inherited rather than introduced here — but it bites harder in this file, since f"relationships[{i}]" is the fallback display name for real relationships that lack a name. Either enumerate raw and continue on non-dicts in the main loop, or carry a raw index on the filtered entries.

4. Nit — the one hand-edit that still vanishes quietly

A relationships.yml whose root is a bare list (i.e. someone omitted the relationships: key — plausibly the most likely hand-edit mistake) still produces zero diagnostics:

root is a bare list: load=[] relationship_errors=[]
root is a scalar:    load=[] relationship_errors=[]

The new block guards with isinstance(raw, dict) and then does nothing when that's false. Given the PR's stated premise, cheap to close:

if raw and not isinstance(raw, dict):
    errors.append(ValidationError("error", "relationships.yml",
                  f"relationships.yml must be a mapping with a 'relationships' key, got {type(raw).__name__}"))

On the outstanding CodeRabbit nit

It asks the not-a-list test to assert the concrete type. Agreed it's trivial — the other two tests already assert got str / got int; only test_validate_project_reports_relationships_not_list stops at the prefix.

Not worth changing

validate_project now parses relationships.yml twice (once via load_relationships at line 948, once in the new block). Matches the views precedent, and the alternative is threading raw data through the loader — leave it.

- Drop duplicate test imports (ruff I001)
- Remove unreachable non-dict guard in filtered loop
- Walk raw relationship list so file indices stay stable
- Report bare-list/scalar relationships.yml roots
- Tighten not-a-list assertion + cover bare root + index cases
@Bartok9

Bartok9 commented Aug 10, 2026

Copy link
Copy Markdown
Contributor Author

Thanks @goldmedal — addressed all four points on the latest push:

  1. Duplicate imports — removed the redundant load_relationships / validate_project entries (ruff I001 clean).
  2. Dead non-dict branch — removed the unreachable "must be an object" guard in the filtered loop (raw pass owns that report).
  3. File indices — the field-check loop now enumerates the raw list when present, so junk at [0] no longer renumbers later unnamed relationships (e.g. missing join_type stays relationships[1]).
  4. Bare root — non-mapping relationships.yml roots now error: must be a mapping with a 'relationships' key, got ….

Also tightened the CodeRabbit not-a-list assertion to got str, and added tests for bare-root + index stability. pytest tests/unit/test_context.py -k relationship → 8 passed.

@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/tests/unit/test_context.py`:
- Around line 1794-1799: Strengthen the assertions near the `errors` diagnostic
checks so a single error message contains both `relationships[1]` and
`join_type`. Keep the existing checks for the integer type error, but replace
the separate combined-blob assertions with a per-diagnostic assertion that
prevents these details from being satisfied by different errors.
🪄 Autofix

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: c7bfe4d3-4edc-4ac1-b373-627d7456dc0b

📥 Commits

Reviewing files that changed from the base of the PR and between a54c844 and 1df2510.

📒 Files selected for processing (2)
  • core/wren/src/wren/context.py
  • core/wren/tests/unit/test_context.py
🚧 Files skipped from review as they are similar to previous changes (1)
  • core/wren/src/wren/context.py

Comment thread core/wren/tests/unit/test_context.py Resolved
CodeRabbit: require relationships[1] and join_type on one diagnostic.
@Bartok9

Bartok9 commented Aug 10, 2026

Copy link
Copy Markdown
Contributor Author

Thanks — tightened the index-stability test so one diagnostic must contain both relationships[1] and join_type (not split across errors). Pushed.

@goldmedal goldmedal left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Thanks @Bartok9 👍

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