Reject conditions built from a different model's fields #133
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
Model 2 · Review Depth (DistilBERT)
Depth Score: 0.17 · 1 substantive comment(s)
Model 3 · Review Timing & Attention
Session adequacy: 100% · Reviewer familiarity: 35%
Bedrock Claude 3 · Risk Narration
(disconnected)
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
davegaeddert
Problem
Order.query.where(User.email.equals("x"))type-checks and then resolves"email"againstOrder:FieldErrorfrom deep in the compiler with no mention ofUser.A type checker can't catch this.
Field[str]isField[str]whichever model declared it — carrying model identity in the annotation would meanField[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.emailbuildsuser__email, which only means anything to anOrderqueryset.with_lookup_prefix()takes that root and stamps it under a separate key, because it dropsmodelon purpose (so a prefixed copy can't pass itself off as a column on the related model).RelatedFieldRefcarries the root unchanged through every hop, so a multi-hop path still belongs to where it started.Field._build_qstamps theQit already builds with(source model, field name)— the field name so the error can name it.Q._condition_originssurvives every method that builds or extends aQ— 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 wrappersBaseExpression.__and__builds ||
create()|Node.createbuilds a plainNodeand reassigns__class__, so__init__never runs ||
add()| mutateschildrenin place:q = Q(); q.add(cond, Q.AND)||
__copy__| which~qandNode.copy()both go through ||
__deepcopy__| |_combine(&,\|) is built fromcreate+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 ownchildrenlist.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 aQwithout recording it is appending toq.childrendirectly, which is reaching past the API intoNode's internals.QuerySet.where()compares each condition's source models against its own and names both.Scope
filter()is untouched. The check iswhere()'s.Q(email="x")stamps nothing and isn't checked — it'sfilter()'s untyped spelling and keeps behaving like it.where()is fine.where()is typed to takeQ, butExists(...)and friends arrive at runtime; they carry no sources and pass through.source_modelis deliberately a property onFieldrather than somethingwhere()digs out, soselect()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-writtenQandfilter()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. IfFieldever 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 reachesQ.__and__— the expression is the left operand, soBaseExpression.__and__runs and wraps both sides inQ(...)before combining, and the wrapper reported no sources. Fixed at the constructor in12ce4ff781, which also coversQ(cond),Q(Q(cond)),~Q(cond)andQ(a, b).Reproducing that turned up a second bug in the same commit:
where()readcondition._condition_originsdirectly and soAttributeErrord on a bare expression —where(Exists(sub))used to work and would have started crashing. It goes throughcondition_origins_of()now, with a test.A later round found two more construction paths that skipped
Q.__init__entirely —Q.create(children=[cond])andq.add(cond, Q.AND)— both of which let a cross-model condition through. Fixed ine0e2c43fa2, which also enumerates the full set of paths in a comment beside the attribute and pins it withTestEveryQConstructionPathCarriesProvenance.A third round closed the shared-
childrenaliasing hole above, renamed the attribute off "source fields" (BaseExpression.get_source_fields()already means something else — theFieldobjects an expression reads), and madecondition_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.e92f0fa3b3Known property, deliberately left alone:
Q.__eq__/__hash__ignore origins, so twoQs differing only in where their conditions came from compare equal. Nothing reaches that today.Checks
./scripts/fix,./scripts/type-check .and the full./scripts/testare 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 togit commitand the signing agent is locked. It reproduces on pristinemasterwith no changes, so it is environmental and unrelated.)