Skip to content

rusi: resolve calls through trait impls under a context type parameter - #243

Merged
prabhu merged 17 commits into
mainfrom
fix/rusi-context-impls
Nov 27, 2026
Merged

prabhu merged 17 commits into
mainfrom
fix/rusi-context-impls

Conversation

@prabhu

@prabhu prabhu commented Nov 27, 2026

Copy link
Copy Markdown
Member

Closes #214

rusi now resolves calls through trait impls that carry a context type parameter, such as impl ToJson<ApiCtx> for Uuid next to impl ToJson<RpcCtx> for Uuid, which serializers, codecs and ORMs use to work around the orphan rule. All five call-graph expectations and the environment -> process-exec slices from handler and handler2 in the issue hold in both backends. AI agents did the implementation and a separate review pass, and the fixes from that review are part of this pull request.

What changed

Trait impl methods are named after their impl block, the way rustc spells them: app::model::<impl ToJson<ApiCtx> for fakeuuid::Uuid>::to_json. The name carries the impl's module, the trait's arguments as written, and the self type qualified to the crate and module that own it. Two impls of one trait for one type under different context arguments get distinct declaration ids, and canonical_name reduces the stable and compiler spellings to the same implementing type, so the two backends join on it. canonical_name also stops reading a turbofish (Vec::<u8>::push) as a qualified self.

Both backends resolve fully qualified calls (<T as Trait<A>>::m, Trait::<A>::m) and trait-object receivers (&dyn ToJson<ApiCtx>) against the impls whose arguments may match. Only an argument pair that provably names different types rules an impl out. A defaulted argument left off one side, a generic parameter anywhere in an argument, a lifetime, or a path written differently from an imported name all keep the candidate. The compiler backend decides with a structural type matcher and reads impl identity from rustc (trait_impl_of_assoc, impl_trait_ref) instead of parsing printed names.

A call inside a generic impl whose trait arguments are still generic (<Uuid as ToJson<Ctx>>::to_json inside impl<Ctx> ToJson<Ctx> for Product) takes the bounded set of matching local impls. The compiler backend adds trait-callback edges for a generic function's trait bounds, both method and path calls: Client::<ApiCtx>::enc::<Uuid> reaches the ApiCtx impl of ToJson for Uuid. The call's own edge keeps its type, and the callback edges fill the rest of --max-call-candidates. 0 now means no cap in the compiler backend too, and a cut edge carries candidateCount and candidatesTruncated.

In the stable backend's data flow, calls the trait-impl index can answer resolve once per call site: a method call by its receiver's type, its generic parameter's trait bounds, or its trait object's arguments, capped the same way. Calls with no type information keep the old unresolved reading, so a bare method name never fans out to every impl of that name.

Smaller fixes made along the way:

  • A method call no longer resolves to a crate-root free function of the same name. This bug predates the branch.
  • External nodes are attributed by their type rather than their first path segment, so String::from_utf8_lossy and <std::vec::Vec<u8> as Deref>::deref no longer get pkg:cargo/String or pkg:cargo/%3Cstd purls, and Result::unwrap on a dependency constructor's result is no longer named after the dependency's type.
  • Candidate lookups in call resolution use hash sets.
  • canonical_name compares bytes, so a non-ASCII identifier no longer panics it.

Performance

The hash-set lookups remove most of the call-graph time the 4.4.0 baseline in #241 found. Measured with --deps --dataflow security-deps on macOS arm64, main at 14dee4e6 against this branch:

project main s branch s main peak MB branch peak MB
anyhow 6.30 5.82 1440 1469
hyper 11.28 10.51 2389 2406
axum 32.48 31.67 5096 5318
mini-redis 322.01 27.26 2378 2424

The mini-redis report is the same apart from the renames: 216 slices of the same kinds, and edges within 0.3%.

Golden changes

Each changed digest was checked against main's output for the same project:

  • Renames (dyn-dispatch-app, dyn-bounds-app, dyn-collection-app, fixpoint-flow-app): the edges and slices are renamed to the impl-block spelling.
  • Data flow through trait dispatch: flows now run end to end instead of stopping at the impl. dyn-dispatch-app gains env -> filesystem-write and env -> network-connect from main, and fixpoint-flow-app gains env -> process-exec from dispatch::run.
  • async-semantic-app: Box::pin loses its pkg:cargo/Box purl, callable.execute becomes receiver-typed through the tuple-struct constructor, and waker.clone() no longer resolves to the fixture's free fn clone.
  • context-impl-app: the fixture is new, and has probe cases for each shape above.
  • anyhow, log, mini-redis (compiler): the new trait-callback edges. In mini-redis these are format!("{:?}", frame) calls reaching Frame::fmt.

Precision and recall stay at 1.0 on every fixture with annotated flows, and every run is byte-identical on re-run.

Checks

  • make fmt-check, make lint, make test (465 passed).
  • RUSTC_BOOTSTRAP=1 cargo test -- --ignored --test-threads=1 (27 passed). The compiler wrapper was built with stable 1.100 and nightly 1.101, which sit on either side of the Remove GenericArgRef rust-lang/rust#165079 API change.
  • scripts/eval/run.py --tier small --backend both: no failed runs, determinism or golden checks.
  • cdxgen evinse -l rust against the fixture with this binary, on both backends.
  • cdxgen's rusi.poku.js passes, though it stubs the spawn and does not run the binary.

The compiler-backend fixture tests return early when the backend collects no evidence. During this work that hid a wrapper build failure on nightly 1.101 until the corpus showed it. That behaviour is older than this change and was left alone here.

Rust libraries work around the orphan rule by giving a trait a defaulted
context parameter (`trait ToJson<Ctx = ()>`), and user crates then implement
it for a third-party type under local marker types. The new
context-impl-app fixture holds that pattern: two marker contexts over a
foreign Uuid stand-in, a generic impl whose where-clauses defer to those
impls, a newtype impl, and two handlers whose `env::var` source should
reach the `Command::arg` sink through the impls. The context-impl-tojson
crate owns the trait and the generic `Client` codec, and the fakeuuid
crate keeps the self type foreign while building offline, in the layout
deps-app and dep-helper-lib use. The fixture is registered in the
fixtures tier of corpus.toml.

The tests cover the issue's five call-graph expectations in both backends
(the compiler-backend ones are ignored tests, like the other compiler
tests) and an environment -> process-exec slice from each handler, which
needs `--deps --dataflow security-deps` where a handler's chain passes
through a dependency body. Run on main, the stable tests fail where the
issue says they do: `api` dispatches to the abstract trait item instead of
the Product impl, and the only slice is `param-0 -> process-exec` inside
the impl.

Refs #214
The wrapper decided "this target is the method of a trait impl" by parsing
the printed name, and rustc prints such a method in two shapes: `<Type as
Trait>::method` when the self type is local to the crate, and
`crate::<impl Trait<Args> for Type>::method` when it is foreign. The
parser only accepted the first, so every impl of the context-parameter
pattern, whose whole point is a foreign self type, read as an abstract
trait item, and edge reconciliation dropped it whenever a concrete edge to
a same-named method existed. That is how `&dyn ToJson<ApiCtx>` lost
exactly the impls it was built to reach.

The fact is now recorded where the edge or call record is created, from
`tcx.trait_impl_of_assoc` and `tcx.impl_trait_ref` (the queries the pinned
nightly carries), as the trait each target implements, and edge
reconciliation reads it instead of the printed name. Callers that only
have a name, such as the data-flow trait-impl index and a crate artifact
read back from disk, are served by `impl_trait_method_parts`, which now
accepts both spellings, handles nesting, and carries unit tests for the
two forms.

A `dyn` receiver's candidates are also filtered by the trait's generic
arguments now: `impl_trait_ref`'s arguments, skipping `Self`, are compared
with the object type's principal arguments, and an argument that is still
one of the impl's own generic parameters keeps the candidate, so
`&dyn ToJson<ApiCtx>` no longer reaches the `RpcCtx` impl or the
`ToJson<()>` one, while the generic `Product` impl stays as the
over-approximation the language allows.

`canonical_name` had the same blind spot from the other side: a
crate-prefixed qualifier was not reduced, so
`app::<impl ToJson<ApiCtx> for uuid::Uuid>::to_json` reduced to
`app::to_json`, and the compiler's declarations could not join anything.
The reduction now drops the crate prefix along with the qualifier, so both
spellings of one impl method reduce to `uuid::Uuid::to_json`.

On the context-impl-app fixture the compiler backend now resolves `rpc`
and the two `dyn` receivers to the impls of their written context, and
`newtype` to the `MyUuid` impl alone.

Refs #214
qualified calls against them

The two context impls of one type shared one identity: the trait's name
was read from the path idents alone, so `ToJson<ApiCtx>` and
`ToJson<RpcCtx>` both produced `Uuid::to_json`, one declaration id, and
one merged call-graph node carrying both bodies, which is how reaching
the RpcCtx impl could look like reaching the ApiCtx one. A trait impl's
method is now named after the impl block, rustc's spelling
(`app::<impl ToJson<ApiCtx> for uuid::Uuid>::to_json`, the trait's
generic arguments as written, the self type qualified to the crate that
owns it), which gives the two impls distinct ids and distinct nodes, and
lets `merge_compiler_declarations` replace the stable declaration with
the compiler's twin, whose canonical name now reduces from both
spellings to `uuid::Uuid::to_json`. That twin replacement is what keeps
the stable declarations out of a compiler report; there was no filter to
add.

Fully qualified calls resolve against the trait-impl index now, by the
self type and the trait arguments the call wrote
(`<Product as ToJson<ApiCtx>>::to_json(p)`,
`ToJson::<RpcCtx>::to_json(&id)`, and a trait-form call's receiver taken
from its first argument). A trait argument that is one of the caller's
own generic parameters cannot be pinned, so every local impl of the
trait for the named self type stays a candidate, the same fallback a dyn
dispatch uses, and a trait object's written arguments
(`&dyn ToJson<ApiCtx>`) filter its dispatch the same way, which is how
`method_api` dispatches to the ApiCtx impl alone. A tuple-struct
constructor types its receiver (`MyUuid(id).to_json()` reaches the
MyUuid impl alone), and a method chain built on a dependency's
constructor names its external node after the chain
(`context_impl_tojson::Client::enc`), which gives the codec calls their
purl.

The data-flow engine resolves the same qualified calls against the same
index, keyed per caller, and joins the summaries of everything a call
resolves to, which is the over-approximation the call graph's bounded
edges carry; a bare method name that no single local function owns can
still be a trait dispatch, so the impl methods of that name are the last
resort of its resolution, as they already were in the call graph.

On the context-impl-app fixture the stable backend now reports each
context impl as its own declaration, dispatches each `dyn` receiver and
fully qualified call to the impl of its written context, and carries an
environment -> process-exec slice from each handler when the
dependency bodies are read.

Refs #214
…mpls

Two calls inside the context-parameter pattern ended where typeck leaves
them. A call inside a generic impl whose trait arguments are still the
impl's own parameters (`<Uuid as ToJson<Ctx>>::to_json` inside
`impl<Ctx> ToJson<Ctx> for Product`) resolves to the trait's method, and
a call into a dependency's generic function
(`Client::<ApiCtx>::enc::<Uuid>`) ends at that function, so the
dependency's calls through its own bounds never reached the user's
impls.

Of the two ways to pin the first one, `Instance::try_resolve` over the
crate's mono items is the exact answer where the caller is
monomorphic, but a `cargo check` run emits metadata only and the mono
collector those instances come from is empty (the pass now says so in a
debug line), so the resolution takes the issue's fallback: a bounded
edge to every local impl of the trait for the self type the call wrote,
with an argument that is one of the caller's own parameters treated as
open. The second is answered by reading the trait bounds on the
callee's signature with the arguments the call site wrote
(`T: ToJson<X>` becomes `Uuid: ToJson<ApiCtx>`), which gives an edge to
the matching local impl, marked `trait-callback` and capped the way
`--max-call-candidates` caps an over-approximated call site, with the
limit passed to the wrapper through `RUSI_MAX_CALL_CANDIDATES`.

The driver carries `max_call_candidates` into the compiler run, and the
JSON attribute reference and the analysis architecture describe the new
call type. On the context-impl-app fixture, Product's generic impl now
reaches both Uuid impls as a bounded set, and `via_client`'s call into
the codec reaches the ApiCtx impl alone through the callback.

Refs #214
The pass counts what it walked and what it resolved, and its debug line
now names the pass, which is what a --debug run reads when a devirtualized
edge is missing.

Refs #214
The purl inference takes the first segment of a qualified symbol for the
crate to attribute, and two shapes it met on the context-impl-app fixture
are not crate segments: a bare standard-library type whose path lost its
root, which turned String::from_utf8_lossy into pkg:cargo/String, and the
qualified self of a deref through a standard-library type, which turned
<std::vec::Vec<u8> as std::ops::Deref>::deref into pkg:cargo/%3Cstd. A
qualified self and a known standard-library type now carry no purl, the
way the std, core and alloc roots already do, and the resolution carries
unit tests for all three shapes.

Refs #214
The per-caller lookup method that the joined-summary helpers outgrew is
removed, the contextual re-summary blocks read as plain maps, and the
qualified-target lookups collapse their emptiness checks into the
lookup.

Refs #214
The digests of the trait-dispatch fixtures rename to the impl-block
spelling, the data-flow slices now run end to end through trait dispatch
instead of stopping at the impl, and the compiler report carries one
joined name per item instead of both backends' spellings. The change log
in scripts/eval/golden records each cause and why the new output is more
correct, as the runner's self-bless rule asks; precision and recall
against the annotated expected flows stay at 1.0 everywhere they are
measured.

Closes #214
The receiver-type filter matches a candidate against the type an impl
block implements for, read out of the method's qualified name; the tests
pin the match against the bare token, the qualified token, another
type's token, and another method's name, and the plain qualified-name
matching an inherent method keeps.
canonical_name treated any top-level `::<` as the start of a qualified
self, so `alloc::vec::Vec::<u8>::push` reduced to `u8::push` and
`Client::<ApiCtx>::new` to `ApiCtx::new`. The reduction now takes the
crate-prefixed branch only when the group is `<impl Trait for Type>` or
`<Type as Trait>`, and drops a turbofish's arguments otherwise. Unit tests
cover both turbofish inputs and a module-qualified impl name.

Refs #214
Impl methods were named after the crate without their module, so two
`impl Display for Err` blocks in different modules shared one name and one
declaration id. The impl prefix and a local self type now carry the
module path, types are collected per module before any item is visited,
and `crate::`, `self::` and `super::` paths are made absolute, so the
names reduce to the same canonical name as rustc's spelling.

The trait-argument filter dropped impls it could not rule out. An impl
that leaves a defaulted argument out, a method's own generic parameter,
a nested generic (`Vec<T>`), a path against an imported name and two
lifetimes are now all kept; only arguments that differ after lifetimes
are dropped and paths are reduced to their last segment rule an impl
out. Argument text keeps the space between two words, so `&'a str` no
longer reads `&'astr`. Trait impls are indexed by the trait's last path
segment, so `impl tj::Pair` and `impl fmt::Display` are found by a
qualified call or a trait object of the bare name.

A method call (`j.pair()`) could resolve to a crate-root free function
of the same name before receiver typing ran; method calls now skip that
name lookup. `Result::unwrap` on a dependency constructor's result is no
longer named after the dependency's type: a standard-library chain
method is never attributed, and only unwrapping or type-preserving links
carry the type further.

Data flow resolved a bare method name with no single owner to every impl
of that name in the workspace and its dependencies, uncapped, and keyed
qualified calls per package, so the ApiCtx and RpcCtx flows crossed.
Calls the trait-impl index can answer are now resolved once per call
site, keyed by caller: a qualified call by the self type and arguments
it wrote, a method call by its receiver's type, its generic parameter's
trait bounds (functions now record them) or its trait object's written
arguments. Each answer is capped by --max-call-candidates, and a call
with no type information keeps the old unresolved reading. Type bindings
are computed only for functions with such a call, and the return-type
index is built once. A taint path names the callee text instead of an
arbitrary target when a call reaches several.

The context-impl-app fixture gains probes for each of these shapes, and
the RpcCtx impl writes a file so the two contexts' sinks differ; new
tests in both backends assert the probes and that the ApiCtx and RpcCtx
flows stay apart.

Refs #214
The dyn filter, the generic-call fallback and the trait-callback lookup
compared impl and call arguments with plain equality, treating only a
bare top-level parameter as open. That dropped impls with lifetime
parameters (regions are erased differently on the two sides), impls with
nested parameters such as `impl<T> Sink<Vec<T>>`, impls checked against
an object argument that is the caller's own parameter (`&dyn
ToJson<C>`), and impls whose self type is generic (`impl<T> .. for
Wrapper<T>`). A structural matcher now decides: a parameter on either
side, a region, a projection, a trait object or a closure never rules an
impl out, and only two types whose rigid structure differs do.

`RUSI_MAX_CALL_CANDIDATES=0` meant 8 in the wrapper while the command
line documents 0 as no cap; it now means no cap. The generic-call
fallback had no cap at all, and the callback cap cut before the call's
own targets were counted and left no mark. Both now append to the
call's own targets up to the limit, and a cut edge carries
candidateCount and candidatesTruncated like the stable backend's.

Path calls of a generic function now get trait-callback edges too, not
only method calls. Stranded doc comments are back on their items, and
the docs describe the matcher and the cap.

Refs #214
The generic-call fallback dereferenced the result of
`impl_trait_ref.args.get(index)`, which compiles on 1.100, where the list
hands out references, but not on the 1.101 nightlies, where
rust-lang/rust#165079 made it hand out values. The wrapper failed to build
there and the compiler backend fell back to the stable one. It now reads
the argument through `CallArgAt::arg_at`, which both shapes implement,
and builds on stable 1.100 and nightly 1.101.

The lifetime probe's compiler test looked for a name ending in `Named`,
which rustc's `<Named as Pair<&'a str, u8>>::pair` spelling never does;
it now looks for the impl by its self type.

Refs #214
A call that gained trait-callback targets took the trait-callback type
for every edge, its own direct target included, and the exact or bounded
suffix counted the callbacks too, so `main -> forward` in
receiver-sink-app turned from static-exact into trait-callback-bounded.
The call now records where its callback targets begin; only those edges
are trait-callback, the direct targets keep the call's type, and each
suffix counts only the targets of its own kind. A unit test covers the
labels.

Refs #214
Each digest change has one of these causes, checked against main's
output for the same project:

- async-semantic-app (stable): `waker.clone()` no longer resolves to the
  fixture's free `fn clone`, because a method call never names a free
  function.
- context-impl-app (both): the fixture gained the probe module, the
  api_direct and rpc_direct handlers, and a file write in the RpcCtx impl.
- fixpoint-flow-app (both): the Stage impl methods carry their module,
  `dispatch::<impl Stage for dispatch::StageNN>::apply`.
- anyhow, log, mini-redis (compiler): path calls of generic functions now
  get trait-callback edges (in mini-redis, `format!("{:?}", frame)` to
  `Frame::fmt`), next to the call's own edge, which keeps its type.

Determinism and precision/recall on the annotated fixtures are unchanged
(1.0 wherever measured).

Refs #214
find_top_level walks a name byte by byte and sliced the str at each
position, which panics when the position falls inside a multi-byte
character. The qualified-self reduction now searches every name for a
top-level `::<`, so a non-ASCII identifier anywhere in a name (axum has
one) aborted the run. The comparison now works on the byte slice, and a
unit test reduces names with a multi-byte identifier.

Refs #214
The receiver-typed and trait-dispatch steps of resolve_call_targets
deduplicated and filtered candidate declaration ids with Vec::contains,
which is linear per lookup. Indexing trait impls by the trait's last path
segment makes those lists longer, and on anyhow with
`--deps --dataflow security-deps` the string comparisons took the run
from 6.2 to 6.9 seconds. Both lookups now go through a HashSet, and the
same run takes 5.7 seconds, faster than main's 6.2. The candidate order
is unchanged.

Refs #214
@prabhu prabhu added bug Something isn't working ai-auto A person set the task, and AI agents carried it through to completion rusi labels Nov 27, 2026
@prabhu
prabhu enabled auto-merge November 27, 2026 19:31
@prabhu
prabhu added this pull request to the merge queue Nov 27, 2026
Merged via the queue into main with commit ad78528 Nov 27, 2026
@prabhu
prabhu deleted the fix/rusi-context-impls branch November 27, 2026 19:58
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ai-auto A person set the task, and AI agents carried it through to completion bug Something isn't working rusi

Projects

None yet

Development

Successfully merging this pull request may close these issues.

rusi: trait impls under a context marker type (orphan-rule workaround) break call-graph and data-flow resolution

1 participant