Repository navigation
Narrow TypeGuard/TypeIs subjects bound by keyword argument - #5535
Keviniscool-boy wants to merge 1 commit into
Conversation
|
Hi @Keviniscool-boy! Thank you for your pull request and welcome to our community. Action RequiredIn order to merge any pull request (code, docs, etc.), we require contributors to sign our Contributor License Agreement, and we don't seem to have one on file for you. ProcessIn order for us to review and merge your suggested changes, please sign at https://code.facebook.com/cla. If you are contributing on behalf of someone else (eg your employer), the individual CLA may not be sufficient and your employer may need to sign the corporate CLA. Once the CLA is signed, our tooling will perform checks and validations. Afterwards, the pull request will be tagged with If you have received this in error or have any questions, please contact us at cla@meta.com. Thanks! |
|
@Keviniscool-boy Looks like we're missing a few things from you before we can review this PR: a signed CLA (see the meta-cla bot comment for instructions) and some of the checklist items here: https://github.com/meta/pyrefly/blob/main/CONTRIBUTING.md#making-a-pull-request. |
|
Thank you for signing our Contributor License Agreement. We can now accept your code for this (and any) Meta Open Source project. Thanks! |
|
✅ This PR meets all requirements from our pull request checklist. Optional recommendations:
Note: this comment updates automatically after changes to the PR. Updates may take up to half an hour. |
stroxler
left a comment
There was a problem hiding this comment.
Thanks for the PR!
I think this is broadly the right direction, it seems like it addreses the problem.
But based on an initial AI-assisted review, I think there are a combination of correctness and performance issues we need to improve before this can be merged:
Overload eligibility uses a different signature from return inference
Location: pyrefly/lib/alt/narrow.rs:149–164.
from typing import TypeGuard, Literal, overload
@overload
def guard(a: object, b: object, *, mode: Literal['a']) -> TypeGuard[str]: ...
@overload
def guard(b: object, a: object, *, mode: Literal['b']) -> TypeGuard[int]: ...
def guard(*args: object, **kwargs: object) -> bool:
key = 'a' if kwargs.get('mode') == 'a' else 'b'
value = kwargs[key] if key in kwargs else args[0]
return isinstance(value, str if key == 'a' else int)
def unsafe(a: object, b: object) -> None:
if guard(a=a, b=b, mode='b'):
print(a + 1)
unsafe(None, 1)The second overload's guard checks b, not a. Head nevertheless narrows both to int: keyword a qualifies through the first overload while the inferred guard result comes from the second. The isolated file produces zero errors at head; base diagnoses a + 1 on object. Python raises TypeError because a is None.
The implementation signature accepts the overloads without an inconsistent-overload diagnostic. This is a crafted case, but it is an actual soundness regression. Mypy and Pyright also choose an incorrect subject in this crafted ordering case; they are not used to validate the expected subject here. Runtime behavior and the guard's single-input meaning establish the problem.
Unbound keyword method call narrows self
Location: pyrefly/lib/alt/narrow.rs:119–148.
from typing import TypeGuard, assert_type
class Guard:
def is_text(self, value: str | None) -> TypeGuard[str]:
return value is not None
def unbound(c: Guard, value: str | None) -> None:
if Guard.is_text(self=c, value=value):
assert_type(c, Guard)
assert_type(value, str)At head, c becomes str and value remains str | None. At base, c stays Guard. The guard's result provides no evidence that its receiver is a string. The helper skips a receiver only for Type::BoundMethod; this unbound function path checks the literal first parameter named self.
Claude's blind unbound-positional example exposed a related preexisting subject-selection issue. This review charges only the newly introduced keyword-receiver narrowing to I1, not the unchanged positional issue.
Candidate collection destroys negative TypeIs narrowing
Location: pyrefly/lib/binding/narrow.rs:1346–1357.
from typing import TypeIs, assert_type
def text_is(value: str | None) -> TypeIs[str]:
return value is not None
def check(value: str | None) -> None:
if text_is(value=value):
assert_type(value, str)
else:
assert_type(value, None) # Head reports str | None.Starting from an empty map, and_all seeds Placeholder AND Call. Negating the operation produces Placeholder OR NotCall; the unconstrained branch then prevents negative narrowing. This occurs with a single keyword, not just with multiple candidate subjects. The true branch of if not text_is(value=value) fails identically.
The new kw_is test expects the unchanged union in else, which masks the incomplete support. Candidate collection needs an insertion/merge operation appropriate to one predicate, without boolean placeholders.
No-narrow calls pay quadratic work
Location: the same per-keyword binder loop, plus and_all.
Even an ordinary bool predicate with keyword arguments is processed here. The full Arguments AST is cloned for every keyword before determining whether that value has a narrowable subject. Distinct name-valued arguments additionally accumulate placeholders and repeated accumulated-name scans. Base produced no guard-subject bindings for these calls.
Synthetic fixture: 200 repetitions of if ordinary(p0=x0, ..., pN=xN): pass, where ordinary has ordinary object parameters and returns bool. Three runs per size, median elapsed seconds, one checker thread, identical Buck dev configuration, same host. Base executable and changed library were transferred to that host; unchanged dependency libraries were reused, and baseline behavior was rechecked after transfer.
| Keywords per call | Base | Head | Head/base |
|---|---|---|---|
| 1 | 1.4647 s | 1.4886 s | 1.02× |
| 8 | 1.5150 s | 1.6516 s | 1.09× |
| 32 | 1.7290 s | 2.5208 s | 1.46× |
| 128 | 2.5188 s | 9.7637 s | 3.88× |
These timings illustrate the structural cost on an adversarial synthetic workload; they do not estimate real-project slowdown. Candidate discovery should avoid repeated full-call AST copies and placeholder expansion, including when guard/shape-related dependencies are absent.
|
This pull request has been imported. If you are a Meta employee, you can view this in D131105783. (Because this pull request was imported automatically, there will not be any future comments.) |
stroxler
left a comment
There was a problem hiding this comment.
Thanks!
I think this PR still has some structural issues.
Call argument-to-parameter mapping
It seems like it is trying to reconstruct the argument-to-parameter mapping using new logic and heuristics, but call semantics are pretty complex so we really want to reuse the standard logic.
When I say use the existing logic, I mean that Pyrefly already knows that, for example in
class Checker:
def is_text(self, value: object, *, tag: str) -> TypeGuard[str]: ...
if checker.is_text(tag="example", value=x):
...
we need to associate
self ← checker # supplied by method binding
value ← x
tag ← "example"
The guard's designated parameter is value, so its result constrains x. Keyword order and the spelling of the receiver are irrelevant.
A sketch of how we might implement this
callable_infer_params already matches actual arguments against formal parameters. Its named-keyword path finds the matching parameter. At that point, retain which actual argument supplies the guarded parameter. There is no need to expose a complete new parameter map just for this feature.
Conceptually, the extra result would be:
GuardEffect {
argument: the actual argument bound to the guarded parameter,
kind: TypeGuard or TypeIs,
narrowed_type: the instantiated return-type argument,
}
This is proposed plumbing, not an existing struct. For overloads, the argument association and return type must come from the same call-resolution result. If applicable alternatives disagree on the subject, declining to narrow is fine.
There's exactly one narrow per call
During solving, only the candidate identified by the logic above contributes a narrow. Other candidates contribute nothing—they are not additional predicates to AND together and later negate.
The current logic appears to mishandle this, I think we might be treating each potentially-matched keyword as a separate narrow and combining them with AND, which isn't right because AND has specific consequences, for example when negated.
This shows up as wrong behavior in a case like this:
if is_type_guard_on_value(value=value, other_parameter=value):
# narrowing works, because we AND'ed two checks on value
else:
# whoops, negative narrowing does *not* work, because when we
# negate it we get an OR. This is incorrect for TypeIs
|
One more thing: be sure to request review when you're ready. Otherwise, the status stays tagged as waiting-for-author, and I'm likely to not look at it because we use the tags to help us skim the backlog |
|
According to mypy_primer, this change doesn't affect type check results on a corpus of open source code. ✅ |
|
Thanks for the detailed review - both points are addressed in 16f007f, with the argument-to-parameter mapping now coming entirely from the standard call-resolution logic. Call argument-to-parameter mapping. Overloads. The association comes from the same call-resolution result as the return type: per-candidate results carry their own Exactly one narrow per call. Binding now records one operation per subject for a keyword-only call, grouping the keywords whose values share that subject into a single candidate set, instead of one AND-combined predicate per keyword. During solving, the call is resolved once through the ordinary call machinery (errors swallowed, as the existing One deliberate behavior change worth flagging: an unbound method call that supplies the receiver by keyword ( |
7a7dea1 to
b61e053
Compare
|
Thanks for the careful review - all three concerns are addressed in 15275ab (rebased onto trunk, history rewritten to a single commit as requested). Unbound keyword calls no longer narrow the receiver. The designated parameter is now skipped based on the function being a method ( Two facets of one object no longer break negative No repeated full call resolution. Also rebased onto trunk as requested (the branch is now a single commit on top of the current trunk tip). |
stroxler
left a comment
There was a problem hiding this comment.
Thanks for the changes @Keviniscool-boy!
This is coming along, unfortunately it's a pretty complex change, so it's taking more rounds of review than typical.
At the moment the biggest issue is that your last update has some debug logging we should get rid of, plus it has many thousands of lines of formatting changes. The formatting changes in particular are so big that I can't easily merge it (and almost any attempt to do so is very likely to fail to merge anyway).
Could you rebase and eliminate both debug logs and the large formatting changes in, for example, narrow.rs, call.rs, and callable.rs?
378906a to
64950aa
Compare
|
Done - thanks for pointing those out, and sorry about the noise. The branch is rebased onto the current trunk tip (single commit, 64950aa). The PR diff is now ~944 additions / ~353 deletions across 7 files with no debug logging and no line-ending or formatting churn (the previous push accidentally contained a stray debug print in On top of that, the rebase onto the newer trunk surfaced one more fix this change needed: Re-verified on the rebased tree: the keyword-narrowing testcases, the two-facet negative narrowing, the unbound-receiver cases (receiver never narrowed, |
|
Thanks! Looks like this needs another rebase before we can merge it |
|
This pull request has been automatically marked as stale because it has been waiting for its author for more than 2 weeks. Please take the action it is waiting for, or close the PR if you are no longer working on it. Thank you for your contributions! |
Summary
Fixes #5263
TypeGuard/TypeIsnarrowing was not applied when the guarded argument is passed by keyword: the binding step only recorded a narrowing operation for a call with at least one positional argument, and attached it toargs.args[0]. A keyword-only call such asis_str(x=x)therefore produced no narrowing operation at all, and the subject stayedstr | Noneinside the positive branch. mypy and pyright both narrow whichever argument is bound to the guard's designated parameter, however it is passed.Approach (reworked from the ground up on this round's review, three parts):
pyrefly/lib/alt/callable.rs— standard call resolution retains which actual argument supplies the designated parameter of the resolvedTypeGuard/TypeIsresult (GuardSubject, derived from the sameArgMapthatcallable_infer_paramsbuilds). The receiver of a method is skipped based on the function being a method (FuncDefId::cls, excluding staticmethods) — independently of how the receiver was supplied — soGuards.is_str(self=g, value=x)narrowsxand never the receiver, and unbound positional calls no longer narrow the receiver either. When the information is unavailable (gradual signatures, lambdas), narrowing is declined rather than guessing.pyrefly/lib/binding/narrow.rs— binding records one predicate per subject root holding the argument/facet alternatives of the call (candidates whose value expressions share a root share the entry; candidates of different calls are separate predicates). The old per-keyword AND-of-candidates is gone.pyrefly/lib/alt/narrow.rs— the answers phase selects, before producing any facet-aware narrow and before applying polarity, the candidate that standard call resolution identifies as the guarded argument; it is applied through the facet-aware path (narrow_by_facet, extracted from the existing facet arm so the subject itself is filtered through its facet). Unselected candidates are absent effects, not operands to AND or OR, so both polarities narrow consistently — including the two-facets-of-one-object case (is_text(value=b.value, other=b.other)), where negativeTypeIsnarrowing was previously erased.Performance: non-guard callees are rejected before any call resolution (zero resolutions for ordinary
boolpredicates), and the resolution result (narrowed type + guarded argument) is consumed directly for selection, narrowing and polarity — the call is resolved once per evaluation instead of twice.Disclosure: this fix was prepared with AI assistance, as marked per AI_POLICY.md. The description above is LLM-generated; the human author will review the diff and complete the attestation below after doing so.
Test Plan
pyrefly/lib/test/narrow.rs: keywordTypeGuard/TypeIsnarrowing in both polarities, a keyword bound to a later parameter, a keyword on a positional-only parameter (declined, plus itsunexpected-keyworderror), bound-method receivers, unbound calls with an explicit receiver in both spellings (the receiver is never narrowed —g.upper()reportsmissing-attributeas on trunk), overloads (the resolved signature's subject narrows, the other signature's subject is untouched), facet subjects,while/assert, the single-predicate property (value=value, other_parameter=valuenarrows in both branches), and two facets of one object (is_text(value=b.value, other=b.other)narrowsb.valuein both branches and leavesb.otheruntouched).cargo test -p pyrefly --lib: 10695 passed, 0 failed (Linux, rustc 1.99.0), with two pre-existing trunk failures excluded and verified to fail identically on clean trunk.cargo clippy -p pyrefly: clean.cargo fmt --check: clean.checker.is_text(tag="example", value=x)narrowsx; the unboundGuards.is_str(self=g, value=x)narrowsxand reportsg.upper()asmissing-attribute;is_text(value=b.value, other=b.other)narrowsb.valuetostr/intacross branches.