Skip to content

fix(context): filter non-mapping entries in _load_views_v1 - #2604

Merged
douenergy merged 3 commits into
mainfrom
fix/load-views-v1-non-mapping
Aug 7, 2026
Merged

douenergy merged 3 commits into
mainfrom
fix/load-views-v1-non-mapping

Conversation

@goldmedal

@goldmedal goldmedal commented Jul 28, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

Fixes #2597. _load_views_v1 was the only project loader that did not filter non-mapping entries out of the list it returns, while its return annotation promises list[dict] and all four of its consumers call .get() / .pop() on the entries.

What failure does this repair?

A legacy (schema_version: 1) project whose hand-written views.yml contains a non-mapping list entry:

views:
  - null
  - "junk"

Every consumer crashes with a bare AttributeError:

consumer failure
validate_project 'NoneType' object has no attribute 'get'
build_manifest / build_json 'NoneType' object has no attribute 'pop' (the _source_dir strip)
_plan_v1_to_v2 'NoneType' object has no attribute 'get'
_apply_v1_to_v2 same — but after the models loop has written the new models/<name>/ directories and unlink()ed the old flat files

The last one is the worst: the migration leaves the project half-converted — models restructured, views.yml untouched, no views/ directory — and reports it as an unhandled AttributeError. The first is the most incongruous: validate_project exists to tell users what is wrong with a hand-edited project, and instead it crashes on one.

The sibling loaders _load_models_v1, _load_models_v2 and _load_views_v2 all guard their items already; this one did not.

The fix

One filter at the loader, covering all four consumers:

views = data.get("views", []) if isinstance(data, dict) else []
return [v for v in views if isinstance(v, dict)]

validate_project additionally reports the bad entries rather than letting them vanish. The issue raised drop-vs-report as an open question; reporting is what the surrounding code already does — both the model-columns loop and the relationships loop isinstance-check each item and append a ValidationError instead of relying on silent filtering. Swallowing a hand-edit mistake would be inconsistent with the function's own conventions and its purpose. The addition is gated behind sv == 1 and an existence check, so it is a no-op for v2+ projects and adds no errors for well-formed v1 ones. Build and migration keep the loader's silent-drop behaviour, matching their siblings.

How is it tested?

Five regression tests in tests/unit/test_context.py, each driving a real consumer on a tmp_path v1 fixture rather than testing the loader helper in isolation — validate_project, build_manifest, build_json, _plan_v1_to_v2, _apply_v1_to_v2. They live under tests/unit/ so the default unit tests job executes them; files under tests/connectors/ are gated behind optional extras or containers and would not run.

pytest tests/unit/ --ignore=tests/unit/test_memory.py --ignore=tests/unit/test_mcp_server.py → 1028 passed, 2 skipped. ruff format --check src/ and ruff check src/ clean.

Duplicate check

No open PR touches _load_views_v1 or the v1 loaders. #2567 patches validate_project for a related non-dict concern but at the consumer rather than the loader, and does not cover build_manifest or either migration path.

Noted, deliberately not fixed here

context.validate_manifest has the same shape — it decodes a base64 manifest and iterates manifest.get("views", []) with .get() calls before WrenEngine is constructed, and construction does not deserialize. It is not reachable with malformed input today: its only caller rebuilds the manifest through build_json(), so it always receives loader-sanitized data and never a hand-edited target/mdl.json. Left alone to keep this change scoped.

🤖 Generated with Claude Code

Summary by CodeRabbit

  • Bug Fixes
    • Improved validation of legacy schema v1 view settings (views.yml), including clear errors when views isn’t a list and when list entries aren’t valid mappings.
    • Prevents malformed view entries from being silently ignored while preserving valid views.
    • Strengthens manifest generation and upgrade behavior so corrupted legacy configurations don’t break upgrades.
  • Tests
    • Added regression tests covering corrupted views.yml scenarios and v1→v2 upgrade resilience.

_load_views_v1 was the only project loader that returned raw list
items without filtering out non-mappings, breaking its list[dict]
contract. A hand-written v1 views.yml with a bad entry (e.g. `- null`)
crashed every consumer with a bare AttributeError: validate_project,
build_manifest/build_json, and both v1->v2 migration steps — the
apply step could even leave a project half-migrated since it unlinks
old model files before reaching the crash in the views loop.

Filter at the loader to match its siblings (_load_models_v1,
_load_models_v2, _load_views_v2), fixing all four consumers with one
change. validate_project additionally re-checks the raw views.yml
entries so a malformed file is reported as a validation error instead
of silently disappearing, consistent with how it already flags
malformed model columns and relationships.

Fixes #2597.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@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

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: 04fd751d-5839-4822-acaa-605d2bbb23a2

📥 Commits

Reviewing files that changed from the base of the PR and between 66722fd and dd99f81.

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

Walkthrough

Schema v1 view loading now filters non-mapping entries. Validation separately reports malformed raw entries, while manifest generation, JSON generation, and v1-to-v2 upgrades are covered against corrupted views.yml files.

Changes

Legacy View Resilience

Layer / File(s) Summary
Filter and validate legacy view entries
core/wren/src/wren/context.py
The v1 loader keeps mapping entries only, while validation reports invalid containers and non-mapping entries found in the raw views.yml.
Cover builders and migration resilience
core/wren/tests/unit/test_context.py
Regression tests verify validation, manifest and JSON output, upgrade planning, and applied migration with malformed entries.

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

Possibly related PRs

Poem

A bunny found bad views in a row,
So filters keep the good ones aglow.
Validation speaks clear,
While upgrades persevere—
And summary hops safely below.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately describes the core fix in _load_views_v1 and matches the main change set.
Description check ✅ Passed The description includes summary, reproduced failure, testing, and duplicate check sections with concrete details.
Linked Issues check ✅ Passed The PR satisfies #2597 by filtering malformed v1 views, covering validate/build/migrate crashes, and adding the required validation behavior.
Out of Scope Changes check ✅ Passed The extra validation and regression tests are directly tied to the linked issue and do not appear out of scope.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/load-views-v1-non-mapping

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

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

1396-1403: 🗄️ Data Integrity & Integration | 🔵 Trivial | ⚡ Quick win

Assert that every malformed entry is reported and excluded.

The fixture contains both null and "junk", but validation only asserts that one matching error exists. The migration tests likewise verify the valid summary output without proving that no invalid view files or directories are planned or written.

Proposed test strengthening
-    assert any("must be a mapping" in e.message for e in hard)
+    mapping_errors = {
+        e.path for e in hard if "must be a mapping" in e.message
+    }
+    assert mapping_errors == {
+        "views.yml > views[0]",
+        "views.yml > views[1]",
+    }

     # The well-formed sibling entry is unaffected.
     assert not any("summary" in e.message for e in errors)

Also assert that migration creates only views/summary/metadata.yml and that the applied project contains no junk view directory.

Also applies to: 1420-1433

🤖 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 1396 - 1403, The
validation test test_validate_project_reports_v1_views_yml_non_mapping_entries
must assert both malformed entries, null and "junk", produce errors while the
valid summary entry remains unaffected. Strengthen the related migration tests
around the applied project to verify only views/summary/metadata.yml is created
and no junk view file or directory is planned or written.
🤖 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 602-603: Update _load_views_v1 in core/wren/src/wren/context.py at
lines 602-603 to normalize views to an empty list unless it is a list, then
filter entries so the method always returns list[dict]. In the views validation
flow at lines 1104-1110, validate that views is a list before calling enumerate
and emit a container-level validation error for null or scalar values.

---

Nitpick comments:
In `@core/wren/tests/unit/test_context.py`:
- Around line 1396-1403: The validation test
test_validate_project_reports_v1_views_yml_non_mapping_entries must assert both
malformed entries, null and "junk", produce errors while the valid summary entry
remains unaffected. Strengthen the related migration tests around the applied
project to verify only views/summary/metadata.yml is created and no junk view
file or directory is planned or written.
🪄 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: a34879ee-678d-4e7f-94c9-cde5c08abbde

📥 Commits

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

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

Comment thread core/wren/src/wren/context.py Resolved
A bare `views:` parses to None, so filtering the list without checking the
container first raised TypeError — and an empty key is a far more likely
hand-edit than a null list entry. Both the loader and the new validation
block now check the container.

`views:` (None) means "no views", same as a missing key, so it is not an
error; a scalar or mapping there is, and is reported once at the container
level rather than once per character.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@goldmedal

Copy link
Copy Markdown
Collaborator Author

Pushed 66722fdf. Both findings were valid — thanks, the first one matters more than its framing suggests.

Non-list views container — real, and arguably the more likely failure of the two. A bare views: with nothing under it parses to None, so filtering the list without first checking the container raised TypeError. An empty views: key is a much more natural hand-edit than a - null list entry, so this shape is probably hit more often than the one the PR set out to fix. Fixed in both places — the loader and the new validation block.

One correction to the suggestion, though: it proposed reporting a container-level error for "null or scalar values". Reporting on null would be wrong — a bare views: legitimately means "no views", exactly like a missing key, and flagging it would fail well-formed projects. So:

  • views: (None) → treated as no views, no error
  • views: <scalar> or views: {…} → one container-level error ('views' must be a list, got str), and the per-entry loop is skipped so a string isn't reported once per character
  • views: [null, "junk", {…}] → unchanged, one error per bad entry

Test strengthening — done. test_validate_project_reports_v1_views_yml_non_mapping_entries now asserts both malformed entries are reported at their own indices (views[0], views[1]) with the offending types named, and still that the valid summary entry is untouched. The migration tests now assert views/summary/metadata.yml is the only file created under views/ and that views/ contains exactly one directory after apply, rather than merely that the good one exists.

Two new tests cover the container shapes: test_validate_project_accepts_empty_v1_views_key (no error, builds to []) and test_validate_project_reports_non_list_v1_views_container (one container error, no per-character noise, build degrades instead of raising).

Unit suite: 1030 passed, 2 skipped. ruff format --check / ruff check clean on src/.

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

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

1413-1432: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Expand malformed-container regression coverage.

This covers None and scalar containers, but not mapping containers, and neither case is exercised through build_json, plan_upgrade, or apply_upgrade. Add those cases (preferably parametrized) so the full resilience contract is protected.

🤖 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 1413 - 1432, Expand the
validation tests near test_validate_project_accepts_empty_v1_views_key to cover
mapping-valued views containers alongside None and scalar inputs, preferably
with parametrization. For each malformed container, assert validation reports
the container once without per-item errors and verify build_json, plan_upgrade,
and apply_upgrade degrade safely without raising.

1457-1466: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick win

Exercise the partially applied migration path.

This test starts from a clean project, so it does not verify the stated interrupted/partially applied migration scenario. Seed the appropriate partial views/ state before apply_upgrade and assert the operation remains safe and leaves only the valid view output.

🤖 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 1457 - 1466, Update
test_apply_upgrade_v1_to_v2_does_not_crash_on_non_mapping_view to seed an
interrupted, partially applied views/ directory state after plan_upgrade and
before apply_upgrade, including any existing valid output expected from that
partial migration. Keep the assertions that apply_upgrade remains safe, produces
the valid summary metadata, removes views.yml, and leaves no junk sibling
entries.
🤖 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.

Nitpick comments:
In `@core/wren/tests/unit/test_context.py`:
- Around line 1413-1432: Expand the validation tests near
test_validate_project_accepts_empty_v1_views_key to cover mapping-valued views
containers alongside None and scalar inputs, preferably with parametrization.
For each malformed container, assert validation reports the container once
without per-item errors and verify build_json, plan_upgrade, and apply_upgrade
degrade safely without raising.
- Around line 1457-1466: Update
test_apply_upgrade_v1_to_v2_does_not_crash_on_non_mapping_view to seed an
interrupted, partially applied views/ directory state after plan_upgrade and
before apply_upgrade, including any existing valid output expected from that
partial migration. Keep the assertions that apply_upgrade remains safe, produces
the valid summary metadata, removes views.yml, and leaves no junk sibling
entries.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 61fa30b5-9d3c-490a-91f1-a5fb883dd032

📥 Commits

Reviewing files that changed from the base of the PR and between c3293bc and 66722fd.

📒 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

…sumers

Covers mapping containers alongside scalar/int, and drives build_json,
plan_upgrade and apply_upgrade rather than build_manifest alone, so the
"degrade to no views" contract is pinned at every consumer.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@goldmedal

Copy link
Copy Markdown
Collaborator Author

Pushed dd99f810 for the first nitpick. Declining the second.

Malformed-container coverage — done. test_validate_project_reports_non_list_v1_views_container is now parametrized over three container shapes (str, int, mapping) and drives every consumer rather than build_manifest alone: build_json, plan_upgrade (asserting nothing under views/ is planned) and apply_upgrade (asserting no views/ directory is created). Unit suite 1032 passed, 2 skipped.

Partially-applied migration — not adding this. The half-migrated state described in #2597 is a consequence of the crash, not a precondition for it: _apply_v1_to_v2 converted the models, then hit AttributeError on the views loop and stopped. With the loader fixed, that state is no longer reachable through this code path.

Seeding a partial views/ state and re-running apply_upgrade would be testing migration resumability — a different property, and one nothing in _apply_v1_to_v2 currently implements. There is no resume logic and no idempotency guarantee to assert; if such a test passed it would be pinning accidental behaviour, and if it failed it would be reporting a feature gap rather than a regression in this change. Either outcome is misleading in a test named for this fix.

What the existing tests do assert is the property that matters here: the migration now runs to completion on a project with a malformed views.yml, and leaves exactly the one well-formed view (views/ contains a single summary directory, views.yml removed). Migration resumability is worth its own issue if we want it.

@goldmedal
goldmedal requested a review from douenergy July 28, 2026 08:52
@douenergy
douenergy merged commit 9bdae39 into main Aug 7, 2026
10 checks passed
@goldmedal
goldmedal deleted the fix/load-views-v1-non-mapping branch August 7, 2026 03:52
Bartok9 added a commit to Bartok9/WrenAI that referenced this pull request Aug 7, 2026
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 added a commit to Bartok9/WrenAI that referenced this pull request Aug 13, 2026
Hand-edited YAML can set columns: to a non-list or mix bare strings into
the list. Mirror Canner#2604: loaders drop/normalise to list[dict]; validate_project
reports must be a list, got <type>. Formatter no longer owns the guard or
infers bare strings as column names.
Bartok9 added a commit to Bartok9/WrenAI that referenced this pull request Aug 17, 2026
Hand-edited YAML can set columns: to a non-list or mix bare strings into
the list. Mirror Canner#2604: loaders drop/normalise to list[dict]; validate_project
reports must be a list, got <type>. Formatter no longer owns the guard or
infers bare strings as column names.
Bartok9 added a commit to Bartok9/WrenAI that referenced this pull request Aug 19, 2026
Hand-edited YAML can set columns: to a non-list or mix bare strings into
the list. Mirror Canner#2604: loaders drop/normalise to list[dict]; validate_project
reports must be a list, got <type>. Formatter no longer owns the guard or
infers bare strings as column names.
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.

context: _load_views_v1 returns non-mapping entries, crashing validate/build/migrate on legacy v1 projects

2 participants