Skip to content

feat(swift): dispatch a protocol requirement to its single conformer - #4035

Closed
GAURAV-1313 wants to merge 2 commits into
Graphify-Labs:v8from
GAURAV-1313:feat/swift-protocol-dispatch-gate
Closed

GAURAV-1313 wants to merge 2 commits into
Graphify-Labs:v8from
GAURAV-1313:feat/swift-protocol-dispatch-gate

Conversation

@GAURAV-1313

Copy link
Copy Markdown
Contributor

What does this PR do?

Fixes #4032.

Links a Swift protocol requirement to the method of its single conformer with a member-level dispatches_to edge: the Swift twin of #3003.

Builds on #4034, the refactor that lifts the C# mechanism into graphify.interface_dispatch; cherry-pick that commit first. This PR is one commit on top of it: 3 files, +322, nothing removed.

Symptom. Since #3673, store.fetch() on an injected Store resolves to the protocol's own .fetch() requirement, which is what the call site names. The conforming RemoteStore.fetch() is a separate node and nothing joins the two, so every edge walk through an injected dependency (query, explain, the graph view) stops at the protocol.

// Core/Store.swift
protocol Store { func fetch() async throws -> [Item] }
// Services/RemoteStore.swift
struct RemoteStore: Store {
    func fetch() async throws -> [Item] { try decode() }
    func decode() throws -> [Item] { [] }
}
// App/ItemModel.swift
final class ItemModel {
    private let store: Store
    func load() async throws -> [Item] { try await store.fetch() }
}

On v8: ItemModel.load() --calls--> Store.fetch() [INFERRED], and RemoteStore.decode() is unreachable from load().

Root cause. csharp_dispatch.py linked an interface requirement to its implementation for .cs files only. No pass did it for Swift; dispatches_to appeared nowhere else.

Fix.

  • graphify/swift_dispatch.py (new, 46 lines): the .swift gate over resolve_interface_dispatch.
  • graphify/extract.py (+10): registers swift_protocol_dispatch right after csharp_interface_dispatch.
  • tests/test_swift_protocol_dispatch.py (new): 17 cases.

The edge is per method, not per call site, so one edge reconnects every caller of the requirement. It is additive: the calls edge to the requirement stays. Confidence is INFERRED 0.9, as in #3005: the target is forced once there is a single conformer, but the source text never names it.

Before and after, rendered by graphify's own viewer. The CleanupStore → Cleaner → DeletionService neighbourhood of roomy, cut from each build's graph.json and drawn with graphify cluster-only, same node positions on both sides. On v8 the three Cleaner requirements have no edge to DeletionService's methods; on this branch the three dashed (INFERRED) dispatches_to edges join them. The self-loop on DeletionService.merge() in both panels is a separate, pre-existing resolution bug (a qualified call to a method with the caller's name resolves to the caller), reported separately.

roomy before and after

Measured, resolver registration on and off, same checkout:

corpus nodes edges dispatches_to conformer method reachable from the caller
3 files: protocol, extension RemoteRepository: Repository, @MainActor consumer 18 → 18 25 → 27 0 → 2 no → yes
SwiftUI app: @StateObject store, actor cache, enum state 36 → 36 58 → 59 0 → 1 no → yes
GAURAV-1313/roomy, 298 Swift files, 4 protocols injected as any P, graphify update --no-cluster 2,910 → 2,910 6,221 → 6,226 0 → 5 5 callers, e.g. CleanupStore.run() → DeletionService.*

On roomy, graphify explain "DeletionService.swift::merge" gains the line --> .merge() [dispatches_to] [INFERRED] …/DeletionService.swift:L15.

One note from the roomy run, and a question. Two of its four protocols (Cleaner, LibraryChangeSource) really have two conformers each: the app type and a test fake in RoomyTests. The fakes are final class X: P with P declared in another file, so the per-file classifier emits them as inherits (the limit below), the guard counts one conformer, and the edges land. The other two protocols have struct fakes, which are counted, and get no edge, which is the guard as written. Once the classifier is fixed, all four have 2+ conformers and this app gets zero edges unless a conformer declared in a test target is treated differently. I'd rather have your call on that than decide it in code.

Type of change

  • Bug fix
  • New feature
  • Documentation
  • Tests or CI
  • Refactor
  • Security fix

Verification & Invariants

Invariant: an edge is drawn only when the corpus forces the target. The protocol has exactly one implements conformer, that conformer owns exactly one method with the requirement's name, and both the protocol and the conformer are declared in .swift files. Anything else leaves the graph exactly as extracted: a protocol with 0 or 2+ conformers, a conformer with 0 or 2+ same-named methods, a protocol-extension default nobody overrides (folded into the protocol's own node, so the conformer owns no candidate), a builtin protocol (View, Codable: sourceless stubs that never pass the declared-in guard), and a same-named Kotlin class that binds to the protocol by name.

  • Read the CONTRIBUTING.md guide.
  • Reproduced the issue and identified the invariant.
  • Made the smallest fix necessary. The mechanism is not re-implemented; the gate is 46 lines plus a 10-line registration.
  • Added a regression test (if bug fix) or isolated boundary test. 17 cases: cross-file positive, reachability through the injected dependency, the call to the requirement is kept, edge shape, extension-declared conformance, same-file class conformer, two conformers → nothing, no matching member → nothing, protocol-extension default → nothing, overriding a default → links, builtin protocol skipped while a static requirement links, subclassing out of scope, protocol inheritance not walked, Kotlin same-name conformer → nothing, a C# corpus untouched by this pass, registration order. 9 fail on the base without this commit (every positive case); 8 are negative controls that pass on both.
  • Kept the PR description synchronized with the final implementation.
  • Documented any limitations / unsupported cases explicitly:
    • Swift spells a superclass and a protocol identically in a class's inheritance list, and _swift_classify_base only knows the protocols declared in the file it is extracting, so final class C: P with P in another file is emitted as inherits and this pass does not see it. Pinned by test_class_conformer_of_a_protocol_in_another_file_is_a_known_limit. Struct/enum/actor conformers, same-file classes and extension C: P are covered. Fixing the classifier is a separate change; it is also a wrong inherits edge on its own.
    • Protocol inheritance is not walked transitively, as in C#. Subclassing a class is an inherits edge and a different bet, so it is out of scope.
    • Property requirements are not dispatched; the pass keys on method edges, as the C# one does.

How was this tested?

uv run pytest tests/test_swift_protocol_dispatch.py -q
  base (refactor commit only): 9 failed, 8 passed
  this branch:                 17 passed
uv run pytest tests/test_swift_protocol_dispatch.py tests/test_csharp_interface_dispatch.py \
  tests/test_language_resolvers.py tests/test_pascal_resolution.py tests/test_swift_*.py \
  tests/test_architecture_doc.py -q
  116 passed
uv run pytest tests/ -q
  6152 passed, 102 skipped, 24 failed: the 24 are tests/test_{erlang,r,solidity,vbnet}_extractor.py,
  whose grammars are optional extras not installed here; a clean v8 checkout fails the identical 24
uv run ruff check .
  All checks passed
uv run pyright graphify/swift_dispatch.py tests/test_swift_protocol_dispatch.py
  0 errors
uv run pyright graphify/extract.py
  119 errors, the same 119 as v8

# the 3-file repro above, `graphify update . --no-cluster` then `graphify explain "Store.swift::fetch"`
v8:           13 nodes, 19 edges
                <-- .load() [calls] [INFERRED] App/ItemModel.swift:L4
                (nothing reaches Services/RemoteStore.swift)
this branch:  13 nodes, 20 edges
                --> .fetch() [dispatches_to] [INFERRED] Services/RemoteStore.swift:L1
                <-- .load() [calls] [INFERRED] App/ItemModel.swift:L4

Diff: 3 files, +322 / −0. One commit on top of the refactor, both rebased on v8 at 0b60d47.

Graphify-specific checklist

  • I updated generated skill artifacts (uv run python -m tools.skillgen --bless) when changing their source fragments. No fragment changed.
  • I confirmed that AST/structural extraction remains deterministic (no ambient state dependencies like ENV variables). The pass reads the edge list in order and dedups on node ids; no filesystem, environment or network input.
  • I reviewed changes for security implications (no unsafe interpolation into shell/Python). No shell, subprocess or interpolation.
  • I confirmed no API keys or local-only graph data are included.
  • (If applicable) I disclosed AI authorship in my commit messages. Claude Code assisted with this change; the commit message says so.

Move the single-implementer dispatch mechanism from csharp_dispatch.py
into interface_dispatch.py with the file-suffix gate as a keyword
parameter. csharp_dispatch.py keeps its public names
(resolve_csharp_interface_dispatch, _method_label, DISPATCH_RELATION)
and becomes the `.cs` gate over the core. No behaviour change: the 15
C# dispatch tests pass untouched, and the extractor registration is
not modified.

Swift protocols have the same shape (Graphify-Labs#3673 resolves a call through an
injected protocol to the requirement, and the conformer's method sits
unreachable from it). With the core shared, that language can add a
gate instead of a second copy of the algorithm.

AI disclosure: Claude Code assisted with this change.
A call through an injected `Store` resolves to `Store.fetch()` — the
protocol requirement (Graphify-Labs#3673) — and the conforming `RemoteStore.fetch()`
is a separate node with nothing joining the two, so every directed walk
through an injected dependency stops at the protocol. Link the two with
the member-level `dispatches_to` edge C# already gets (Graphify-Labs#3003), under the
same single-conformer / single-owner guard: a protocol with two
conformers, a conformer with two same-named methods, or a default
implementation nobody overrides emits nothing.

The mechanism lives in graphify.interface_dispatch, lifted out of the
C# pass in the preceding refactor; swift_dispatch.py is the `.swift`
gate over it, registered right after the C# pass. Both ends of a pair
must be declared in a Swift file, so a Kotlin class naming the same
supertype never receives a Swift edge.

Known limit, pinned by test: a `class C: P` whose protocol is declared
in another file is classified `inherits` by the per-file classifier and
is not dispatched; struct/enum/actor conformers and `extension C: P`
are.

AI disclosure: Claude Code assisted with this change.
Copilot AI balanced review requested due to automatic review settings October 3, 2026 13:35

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

@github-actions

github-actions Bot commented Oct 3, 2026

Copy link
Copy Markdown

Thanks for the pull request, @GAURAV-1313. A maintainer will review it soon.

Want to talk it through while it is in review? Come join us on our Discord server. For longer-form discussion there is also GitHub Discussions.

A couple of things that speed up review: make sure the test suite passes on Python 3.10 and 3.13, and that the change keeps extraction deterministic.

@graphify-labs graphify-labs Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Graphify reviewed this change.

Looks safe to merge — no coupling regressions and no blocking issues, checked against the code graph (not a self-assessment).

Formal verification. PR-changed functions: 0/1 verified (0 proven, 0 may-equivalent, 0 distinguished) · 1 not verified (1 vacuous).

Not verified on this run: resolve\_csharp\_interface\_dispatch (vacuous: never exercised).


Graphify review — findings

Adds Swift protocol dispatch, so a call through an injected protocol now continues from the requirement to the single conformer's method via an INFERRED dispatches_to edge. Calls to built-in protocol conformances are skipped, while static requirements and overrides of default implementations are linked. The single-implementer/single-owner algorithm moves into resolve_interface_dispatch and is gated by file suffix, so resolve_csharp_interface_dispatch and the new resolve_swift_protocol_dispatch only link pairs whose two ends are declared in their own language.

No blocking issues surfaced. 4 lower-confidence candidates did not survive cross-model review.

Analysis details — impact, health, verification

Impact & health

Graphify review

Impact — 2294 functions depend on the 300 functions this change touches.

Health — this change adds coupling hotspots:

  • new: extract() — 749 callers, 50 callees
  • new: _rebuild_code() — 147 callers, 56 callees
  • new: extract_js() — 87 callers, 4 callees
  • new: extract_xaml() — 19 callers, 17 callees
  • new: main() — 98 callers, 3 callees
  • new: dispatch_command() — 2 callers, 126 callees
  • new: _get_extractor() — 27 callers, 6 callees
  • new: collect_files() — 19 callers, 6 callees
  • …and 35 more — each is listed as a finding

Verification — 2294 functions in the blast radius were not formally verified this run (proofs are advisory here).

Gate & verification

graphify gate

PASS — objectively clean (no health regressions, tests not run — proofs not run this pass (advisory)). Grounded, not self-assessed.

Advisory (not blocking):

  • verification_scope: 2114 function(s) in the blast radius were not formally verified this run

Test selection

Test selection

138 of 319 test file(s) selected (43%) via static blast radius.

  • tests/test_astro_extraction.py — impact
  • tests/test_astro_import_ids.py — impact
  • tests/test_blade_extractor.py — impact
  • tests/test_build.py — impact
  • tests/test_builtin_global_type_refs.py — impact
  • tests/test_case_sensitive_resolution.py — impact
  • tests/test_cjs_module_extension.py — impact
  • tests/test_cobol_extractor.py — impact
  • tests/test_cpp_method_declarations.py — impact
  • tests/test_cpp_nested_and_cli.py — impact
  • tests/test_cpp_objc_cross_file_calls.py — impact
  • tests/test_cross_extension_reexport_self_cycle.py — impact
  • tests/test_cross_language_call_resolution.py — impact
  • tests/test_cross_repo_external_call_guards.py — impact
  • tests/test_cross_repo_member_calls.py — impact
  • tests/test_csharp_call_site_generic_args.py — impact
  • tests/test_csharp_enum_members.py — impact
  • tests/test_csharp_field_generic_args.py — impact
  • tests/test_csharp_generic_callsites.py — impact
  • tests/test_csharp_interface_dispatch.py — impact
  • tests/test_csharp_member_calls.py — impact
  • tests/test_csharp_member_nodes.py — impact
  • tests/test_csharp_object_creation.py — impact
  • tests/test_csharp_partial_classes.py — impact
  • tests/test_csharp_tuple_type_refs.py — impact
  • tests/test_csharp_type_resolution.py — impact
  • tests/test_definition_file_portability.py — impact
  • tests/test_detect.py — impact
  • tests/test_dotnet.py — impact
  • tests/test_duplicate_annotation_edges.py — impact
  • tests/test_elixir_import_resolution.py — impact
  • tests/test_erlang_extractor.py — impact
  • tests/test_extract.py — impact
  • tests/test_extract_cache_location.py — impact
  • tests/test_extract_php_closures.py — impact
  • tests/test_file_label_disambiguation.py — impact
  • tests/test_file_node_id_spec.py — impact
  • tests/test_forwarding_review_findings.py — impact
  • tests/test_go_builtin_call_targets.py — impact
  • tests/test_go_import_repoint.py — impact
  • tests/test_go_interface_methods.py — impact
  • tests/test_go_qualified_resolution.py — impact
  • tests/test_import_extension_resolution.py — impact
  • tests/test_import_self_loops.py — impact
  • tests/test_imported_export_forwarding.py — impact
  • tests/test_incremental.py — impact
  • tests/test_indirect_call_arrow_single_param_shadow.py — impact
  • tests/test_indirect_call_block_scoped_shadow.py — impact
  • tests/test_indirect_call_catch_binding_shadow.py — impact
  • tests/test_indirect_call_external_import_shadow.py — impact
  • … and 88 more

Selection is safe under the controlled-regression assumption; always-run tests + a periodic full run are the backstops. Advisory — it never changes the check verdict.

Formal verification

Could not verify: Could not verify resolve\_csharp\_interface\_dispatch.

The verifier did not have enough to check resolve\_csharp\_interface\_dispatch, so it is saying so rather than guessing. No false assurance is the whole point.

Guarantee: No guarantee either way, this is an honest abstention, not a pass.

Note: Reason: no capturable inputs from the test suite; property tier: non-vacuity: domain too small (only 1 distinct inputs exercised, need 3) — 'no divergence' would be near-vacuous

· 43 more finding(s) on lines outside this diff (see the check run).

@safishamsi

Copy link
Copy Markdown
Member

Shipped in v0.9.75 (live on PyPI as graphifyy==0.9.75). Landed on v8 via an authorship-preserving cherry-pick, so your original commit authorship is kept. Thanks @GAURAV-1313 for Swift protocol-requirement dispatch 🙏

Closing as shipped.

@GAURAV-1313

GAURAV-1313 commented Oct 4, 2026 via email

Copy link
Copy Markdown
Contributor Author

livingforelvis added a commit to livingforelvis/graphify that referenced this pull request Nov 20, 2026
…aphify-Labs#5319)

A call through an interface-typed field (`this.worker.run()` where
`worker` is a `Worker`) lands on the interface's method node, and nothing
joins it to `EmailWorker.run()`, so a directed walk stops at the
interface. C# (Graphify-Labs#3003), Swift (Graphify-Labs#4035) and Go (Graphify-Labs#4934) already close this
gap with `dispatches_to`; no pass was registered for `.java`.

The Java extractor already emits `implements` and the interface's
`method` edges, so graphify.java_dispatch is a thin `.java` gate over
resolve_interface_dispatch, registered after the Go pass. Same rules as
the other languages: additive INFERRED edges at 0.85 / 0.75 / 0.65 by
implementer count, both ends declared in `.java`. Each Java overload is
its own node, so the shared pairing links overloads by signature, then
arity. No extractor change, so no AST cache schema bump (as for Swift).

Known limits, pinned by tests: `extends` (abstract classes) is not
read, interface hierarchies are not walked, an unoverridden `default`
method gets no edge, a lone same-named method pairs without a signature
check, and a fully qualified `implements a.Worker` with no import binds
to a sourceless stub and gets no edge (the imported form links).

Two C# tests asserted that a Java corpus gains no dispatch edge; they now
call the C# pass directly, and the mixed-corpus test expects each pair
within its own language.

Co-Authored-By: Claude <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: Swift: a call through an injected protocol dead-ends at the requirement, so the conformer's method is unreachable

3 participants