Skip to content

fix(genbi): treat blank provider tokens as missing - #2584

Closed
Bartok9 wants to merge 4 commits into
Canner:mainfrom
Bartok9:fix/resolve-token-blank-env
Closed

Bartok9 wants to merge 4 commits into
Canner:mainfrom
Bartok9:fix/resolve-token-blank-env

Conversation

@Bartok9

@Bartok9 Bartok9 commented Jul 25, 2026 •

Copy link
Copy Markdown
Contributor

Summary

resolve_token returned whitespace-only env values as tokens, so deploy used Authorization: Bearer and failed opaquely.

Changes

  • Strip and reject blank tokens at all 3 lookup tiers

Summary by CodeRabbit

  • Bug Fixes
    • Blank or whitespace-only token values are now treated as missing (including when provided via process environment), preventing invalid/blocked authorization.
    • Token values are trimmed and normalized consistently across environment and .env sources, so blank env entries won’t prevent valid .env values.
    • Seed query generation is more defensive against malformed manifest data by safely skipping unexpected non-dict entries in models and relationships.
  • Tests
    • Added unit tests for blank/whitespace token normalization and .env fallback behavior.
    • Added unit tests ensuring seed query generation tolerates malformed manifest entries.

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

coderabbitai Bot commented Jul 25, 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: 37472780-765e-4ceb-8281-2a1f3806d8bc

📥 Commits

Reviewing files that changed from the base of the PR and between 5aede49 and 46e8b59.

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

Walkthrough

Token resolution now trims values and treats blank environment or dotenv entries as missing, while seed query generation skips malformed model and relationship manifest entries.

Changes

Token resolution

Layer / File(s) Summary
Normalize token lookup and validate blank values
core/wren/src/wren/genbi/tokens.py, core/wren/tests/unit/test_resolve_token_blank.py
Adds _as_token normalization across environment and dotenv sources, including fallback past blank shell values, with tests for trimming and blank handling.

Seed query validation

Layer / File(s) Summary
Filter malformed manifest entries
core/wren/src/wren/memory/seed_queries.py, core/wren/tests/unit/test_seed_queries_nonduct_models.py
Filters invalid model entries, skips non-dictionary relationships during seed generation and join-column parsing, and tests valid query output from malformed manifests.

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

Possibly related PRs

  • Canner/WrenAI#2424: Hardens relationship seed generation for unexpected relationship metadata.
  • Canner/WrenAI#2533: Hardens manifest processing for malformed model and relationship entries.
  • Canner/WrenAI#2542: Directly hardens seed_queries.py against invalid manifest entries.

Suggested reviewers: goldmedal

Poem

I’m a rabbit with tokens to trim,
Blank values vanish at the rim.
Odd seeds hop away,
Valid queries stay,
Clean configs make the burrow grin.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 66.67% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly matches the main change: blank provider tokens are now treated as missing.
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

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

6-20: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Add coverage for the dotenv lookup tiers.

These tests only exercise os.environ; stubbing _ensure_env_loaded and omitting .env files means regressions in standard dotenv loading and explicit project .env normalization will go undetected. Add cases for a blank process value with a valid standard .env, plus a blank/whitespace value in the explicit project .env.

🤖 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_resolve_token_blank.py` around lines 6 - 20, Extend
the resolve_token tests around test_resolve_token_treats_blank_env_as_missing
and test_resolve_token_strips to cover dotenv lookup tiers: create a valid
standard .env and verify a blank process value falls back to it, then create an
explicit project .env containing a blank or whitespace token and verify that
value is normalized as missing. Exercise the real _ensure_env_loaded path for
these cases instead of stubbing it, while preserving the existing
environment-value assertions.
🤖 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/genbi/tokens.py`:
- Around line 35-43: Update the token lookup flow around `_as_token` and
`_ensure_env_loaded` so a whitespace-only process environment value cannot block
a valid token from the standard dotenv sources; clear or otherwise bypass the
blank value before resolving tier 2, while preserving precedence for nonblank
process values. Add a regression test covering a blank shell value and a valid
standard `.env` token.

---

Nitpick comments:
In `@core/wren/tests/unit/test_resolve_token_blank.py`:
- Around line 6-20: Extend the resolve_token tests around
test_resolve_token_treats_blank_env_as_missing and test_resolve_token_strips to
cover dotenv lookup tiers: create a valid standard .env and verify a blank
process value falls back to it, then create an explicit project .env containing
a blank or whitespace token and verify that value is normalized as missing.
Exercise the real _ensure_env_loaded path for these cases instead of stubbing
it, while preserving the existing environment-value assertions.
🪄 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: 9ece4469-e063-44fc-b489-a1f91e7dd7a1

📥 Commits

Reviewing files that changed from the base of the PR and between d472877 and 4f7c2a4.

📒 Files selected for processing (2)
  • core/wren/src/wren/genbi/tokens.py
  • core/wren/tests/unit/test_resolve_token_blank.py

Comment thread core/wren/src/wren/genbi/tokens.py Resolved
A whitespace-only shell value (VERCEL_TOKEN=) stayed in os.environ and
blocked load_dotenv(override=False) from resolving a valid token in the
standard .env tier. Delete the blank key before dotenv discovery; add
regression tests for dotenv fallback and blank project-.env values.
@Bartok9

Bartok9 commented Jul 25, 2026

Copy link
Copy Markdown
Contributor Author

Good catch on the dotenv-tier gap. Fixed in 3bfc92f: a blank/whitespace-only shell value could stay in os.environ and shadow a valid token from the standard .env (since load_dotenv(override=False) skips keys already set). Now the blank key is dropped before tier-2 discovery. Added regression tests exercising the real _ensure_env_loaded path (blank shell → valid $CWD/.env) plus a blank value in the explicit project .env.

@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_seed_queries_nonduct_models.py (1)

26-38: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

Strengthen the assertions to prove malformed entries are skipped.

The current checks only require one orders result and a "sql" key. Add a valid customers model, assert the valid relationship seed is retained, and assert malformed model/relationship entries do not produce output (preferably with exact expected pairs or counts).

🤖 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_seed_queries_nonduct_models.py` around lines 26 -
38, Strengthen the assertions around generate_seed_queries by adding a valid
customers model to the manifest, then verify the valid orders/customers
relationship seed is retained. Assert that the malformed "bad-rel" model and
relationship entries produce no seed output, using exact expected pairs or
counts rather than only checking for an orders result and a sql key.
🤖 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_seed_queries_nonduct_models.py`:
- Line 34: Add production validation in generate_seed_queries before the
model-layer comprehension and subsequent model loop access model entries as
dictionaries, and before the relationship loop calls _relationship_seed. Reject
or skip invalid "bad"/None model entries and the "bad-rel" relationship entry so
dictionary subscripting and _relationship_seed’s .get() are never invoked on
unsupported values, while preserving valid seed-query generation.

---

Nitpick comments:
In `@core/wren/tests/unit/test_seed_queries_nonduct_models.py`:
- Around line 26-38: Strengthen the assertions around generate_seed_queries by
adding a valid customers model to the manifest, then verify the valid
orders/customers relationship seed is retained. Assert that the malformed
"bad-rel" model and relationship entries produce no seed output, using exact
expected pairs or counts rather than only checking for an orders result and a
sql key.
🪄 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: 30d65780-dfd1-4f2e-a83a-eba4cb88a0ba

📥 Commits

Reviewing files that changed from the base of the PR and between 4f7c2a4 and 3bfc92f.

📒 Files selected for processing (3)
  • core/wren/src/wren/genbi/tokens.py
  • core/wren/tests/unit/test_resolve_token_blank.py
  • core/wren/tests/unit/test_seed_queries_nonduct_models.py
🚧 Files skipped from review as they are similar to previous changes (1)
  • core/wren/src/wren/genbi/tokens.py

@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: 2

🤖 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/memory/seed_queries.py`:
- Around line 34-38: The model filtering in the seed-query construction must
reject whitespace-only and non-string names before they reach _norm_ident().
Update the models comprehension to require a string name whose stripped value is
non-empty, and add regression coverage for whitespace-only and integer name
values.
- Around line 54-56: Normalize and filter each relationship in the
relationship-processing flow so only dictionaries with valid string model names
in models and a string condition reach _relationship_seed; apply the same
validation before sqlglot.parse_one in core/wren/src/wren/memory/seed_queries.py
at lines 54-56 and 176-178, respectively. Reuse the normalized fields for both
consumers and skip malformed relationships.
🪄 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: dc1d0645-99d1-4baf-8ded-1a498665c88e

📥 Commits

Reviewing files that changed from the base of the PR and between 3bfc92f and 5aede49.

📒 Files selected for processing (1)
  • core/wren/src/wren/memory/seed_queries.py

Comment on lines 54 to +56
for rel in manifest.get("relationships", []):
if not isinstance(rel, dict):
continue

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 | 🟠 Major | ⚡ Quick win

Validate relationship fields once before both consumers.

Checking isinstance(rel, dict) is insufficient: malformed dictionaries can crash _relationship_seed() or SQL parsing. Normalize/filter relationships so models contains valid string names and condition is a string before using them in either path.

  • core/wren/src/wren/memory/seed_queries.py#L54-L56: validate before calling _relationship_seed.
  • core/wren/src/wren/memory/seed_queries.py#L176-L178: apply the same validation before sqlglot.parse_one.
📍 Affects 1 file
  • core/wren/src/wren/memory/seed_queries.py#L54-L56 (this comment)
  • core/wren/src/wren/memory/seed_queries.py#L176-L178
🤖 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/memory/seed_queries.py` around lines 54 - 56, Normalize
and filter each relationship in the relationship-processing flow so only
dictionaries with valid string model names in models and a string condition
reach _relationship_seed; apply the same validation before sqlglot.parse_one in
core/wren/src/wren/memory/seed_queries.py at lines 54-56 and 176-178,
respectively. Reuse the normalized fields for both consumers and skip malformed
relationships.

Reject whitespace-only and non-string model names in seed-query generation, and reformat the model_layers comprehension to satisfy ruff format --check.
@Bartok9

Bartok9 commented Jul 25, 2026

Copy link
Copy Markdown
Contributor Author

Pushed 46e8b59:

  • Lint fix: ran ruff format on seed_queries.py (the model_layers comprehension now fits on one line) — ruff format --check src/ and ruff check src/ both pass locally.
  • CodeRabbit nit: the model filter now requires a non-empty string name (isinstance(name, str) and name.strip()), so whitespace-only and non-string names are dropped before _norm_ident(). Added regression coverage for whitespace-only and integer names in test_seed_queries_nonduct_models.py (40 passing).

@goldmedal

Copy link
Copy Markdown
Collaborator

Closing this as-is, but the core idea is worth resubmitting — please split it.

What's good: _as_token is a real fix. A blank or whitespace-only VERCEL_TOKEN is truthy enough for if value := os.environ.get(...), so deploy sends Authorization: Bearer and fails opaquely. Stripping and treating blank as missing is right.

Why I can't take this diff:

  1. It mutates the process environment. del os.environ[env_var] inside resolve_token is a global side effect in what reads as a pure lookup function. Anything later in the process that reads that variable — including subprocesses spawned by deploy — now sees it absent because a resolver decided its value was blank. If the goal is to stop load_dotenv(override=False) from being shadowed by a blank key, read the files directly (dotenv_values) and merge in priority order instead of deleting from os.environ.
  2. It carries unrelated changes. core/wren/src/wren/memory/seed_queries.py gets non-dict guards that have nothing to do with provider tokens, and duplicate the ones in fix(memory): skip non-dict models/columns in seed query generation #2542.
  3. The third test pokes a private one-shot latch (monkeypatch.setattr(profile, "_env_loaded", False)) to force re-discovery, which will break quietly if that latch is ever renamed.

A PR touching only genbi/tokens.py + its test, resolving precedence without mutating os.environ, would be an easy review. Please open that and I'll pick it up.

@Bartok9

Bartok9 commented Jul 27, 2026

Copy link
Copy Markdown
Contributor Author

All fair — especially the process-environment mutation. del os.environ[...] inside what reads as a pure resolver is a global side effect that would bite subprocesses; reading files directly with dotenv_values and merging in priority order is the right shape. Closing this. I'll resubmit a PR touching only genbi/tokens.py + its test, resolving precedence without mutating os.environ, and drop the unrelated seed_queries guards. Thanks!

@Bartok9 Bartok9 closed this Jul 27, 2026
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