← Back to Pull requests

Reject conditions built from a different model's fields #133

Closed
unknown closed this pull request without merging on Sep 20, 2026 02:14 UTC
View on GitHub
unknown unknown commented on Sep 19, 2026 19:24 UTC
Author

Problem

Order.query.where(User.email.equals("x")) type-checks and then resolves "email" against Order:

  • when both models have a column by that name, it silently filters the wrong column and returns wrong rows;

  • when they don't, it surfaces as a FieldError from deep in the compiler with no mention of User.
  • A type checker can't catch this. Field[str] is Field[str] whichever model declared it — carrying model identity in the annotation would mean Field[Model, T] everywhere — so the condition has to carry its origin at runtime.

    Mechanism

    The carrier is the field's model, which it already has.

  • Field.source_model — the model a condition built from this field belongs to. For an attached field that's the model it was declared on. For a traversed copy it's the root the traversal started from, not the related model the column lives on: Order.user.email builds user__email, which only means anything to an Order queryset. with_lookup_prefix() takes that root and stamps it under a separate key, because it drops model on purpose (so a prefixed copy can't pass itself off as a column on the related model).

  • RelatedFieldRef carries the root unchanged through every hop, so a multi-hop path still belongs to where it started.

  • Field._build_q stamps the Q it already builds with (source model, field name) — the field name so the error can name it.

  • Q._condition_origins survives every method that builds or extends a Q — a guard with a way around it is not a guard. The complete set, all overridden:
  • | path | why it needs carrying |
    | --- | --- |
    | __init__ | Q(cond), and the wrappers BaseExpression.__and__ builds |
    | create() | Node.create builds a plain Node and reassigns __class__, so __init__ never runs |
    | add() | mutates children in place: q = Q(); q.add(cond, Q.AND) |
    | __copy__ | which ~q and Node.copy() both go through |
    | __deepcopy__ | |

    _combine (&, \|) is built from create + add, so it needs nothing of its own. Pickling preserves the instance attribute as-is. Each path reads only its immediate children, which already carry their own subtree's origins, so nothing walks the tree.

    __copy__ also gives the copy its own children list. Node.__copy__ shares it, so extending a copy appended into the original while only the copy recorded the origin — where(original) then ran a foreign condition silently. With that closed, the only way left to put a condition into a Q without recording it is appending to q.children directly, which is reaching past the API into Node's internals.

  • QuerySet.where() compares each condition's source models against its own and names both.
  • TypeError: where() got a condition built from Widget.name, but this is a
    DefaultsExample queryset. Build the condition on DefaultsExample's own field,
    or traverse to it from DefaultsExample.
    

    Scope

  • filter() is untouched. The check is where()'s.

  • A hand-written Q(email="x") stamps nothing and isn't checked — it's filter()'s untyped spelling and keeps behaving like it.

  • A detached field (built for an aggregate, never attached) has no source model, and conditions from it go unchecked rather than guessing.

  • An expression reaching where() is fine. where() is typed to take Q, but Exists(...) and friends arrive at runtime; they carry no sources and pass through.
  • source_model is deliberately a property on Field rather than something where() digs out, so select() can reuse the same check — #89 has the identical hole (Order.query.select(User.email)) and will pick this up once this merges.

    Tests

    tests/public/test_typed_where.py::TestConditionsBelongToTheirModel — same-model passes; other-model raises when the column exists (the silent-wrong-rows case) and when it doesn't; negated (~q), &, | and ~(a & b) all checked; hand-written Q and filter() unaffected.

    tests/public/test_typed_where_fk.py::TestTraversedConditionsBelongToTheirRoot — a traversed condition passes on its root, raises on another model, is not attributed to the related model (the tempting wrong answer), and a two-hop path keeps the root.

    tests/typing/conditions_value_types.py — a must-accept claim that the cross-model call type-checks clean, with a comment saying that's exactly why the runtime check exists. If Field ever carries model identity, that line starts erroring and someone comes and reads it.

    Review follow-up

    Codex caught a hole in the first commit: Exists(sub) & Widget.name.equals("x") never reaches Q.__and__ — the expression is the left operand, so BaseExpression.__and__ runs and wraps both sides in Q(...) before combining, and the wrapper reported no sources. Fixed at the constructor in 12ce4ff781, which also covers Q(cond), Q(Q(cond)), ~Q(cond) and Q(a, b).

    Reproducing that turned up a second bug in the same commit: where() read condition._condition_origins directly and so AttributeErrord on a bare expression — where(Exists(sub)) used to work and would have started crashing. It goes through condition_origins_of() now, with a test.

    A later round found two more construction paths that skipped Q.__init__ entirely — Q.create(children=[cond]) and q.add(cond, Q.AND) — both of which let a cross-model condition through. Fixed in e0e2c43fa2, which also enumerates the full set of paths in a comment beside the attribute and pins it with TestEveryQConstructionPathCarriesProvenance.

    A third round closed the shared-children aliasing hole above, renamed the attribute off "source fields" (BaseExpression.get_source_fields() already means something else — the Field objects an expression reads), and made condition_origins_of() trust only a frozenset, so a conditional object with a catch-all __getattr__ can't break every construction path with an opaque error. e92f0fa3b3

    Known property, deliberately left alone: Q.__eq__/__hash__ ignore origins, so two Qs differing only in where their conditions came from compare equal. Nothing reaches that today.

    Checks

    ./scripts/fix, ./scripts/type-check . and the full ./scripts/test are green — 27 packages, 0 failures, plain-postgres 1085 passed / 5 skipped (up from 1048).

    (One plain-dev test, test_nested_app_directories_do_not_collide_across_worktrees, fails in my environment because it shells out to git commit and the signing agent is locked. It reproduces on pristine master with no changes, so it is environmental and unrelated.)

    Diff: 650 lines (+487 / -163) across 8 files Reviewer: davegaeddert Review duration: 410m
    All Vouch review confidence checks passed
    Residual risk 0.21 = Change Risk (0.52) × (1 − Review Confidence (0.60)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.52 · 650 lines diff across 8 files
    0.52
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.17 · 1 substantive comment(s)
    0.17
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 35%
    60%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.388
    Shallow Review Depth shallow_review_depth
    0.289
    Real PR Conversation Timeline
    1 comments
    "Review active on #133"
    general weight: 0.35
    Reviewers
    Assignees
    Unassigned
    Labels
    risk: low confidence: 60.5% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 52% (MEDIUM) · Higher = larger blast radius
    52%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 60.5% · Lower = rushed or shallow review
    60.5%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 20.5% · Safe to merge
    20.5%
    Repository