Skip to content

fix(extract): keep file and declaration IDs distinct (#4854) - #4857

Closed
Deepjyoti-Sarmah wants to merge 4 commits into
Graphify-Labs:v8from
Deepjyoti-Sarmah:fix/4854-file-decl-id-collision
Closed

Deepjyoti-Sarmah wants to merge 4 commits into
Graphify-Labs:v8from
Deepjyoti-Sarmah:fix/4854-file-decl-id-collision

Conversation

@Deepjyoti-Sarmah

Copy link
Copy Markdown
Contributor

What does this PR do?

Fixes #4854. A file and a declaration inside it no longer share an id.

The file id is the extensionless stem, a declaration id is make_id(stem, name), and the parse-time file id is make_id(path). When a declaration's normalized name equals the file extension, both recipes land on one string, and add_node silently keeps the first:

a.js   class Js

before
  file id     make_id("a.js")      -> a_js
  class id    make_id("a", "Js")   -> a_js      same string
  add_node(class)                  -> a_js in seen_ids, return
  add_edge(file, class, contains)  -> a_js -> a_js
  flags on class_nid               -> file becomes _callable_class
  method id   make_id(a_js, run)   -> a_js_run   owned by the file

after
  registry.resolve(a_js, "Js", "type")
    a_js is reserved by the file
    -> a_js_b692bab43393
  decl_node adds the class under the salted id
    -> a_js -> a_js_b692bab43393 contains
    -> a_js_b692bab43393 -> a_js_b692bab43393_run method

Two invariants are enforced:

unique    an id is assigned only after an availability check against the
          file id, the taken node ids, and the ids assigned to declarations
stable    the same declaration resolves to its assigned id on a re-walk
          (reopened classes, cfg twins), and unaffected files keep their ids
referenced a reference to the declaration uses the declared id, not a
          per-file id derived from the referring file

The registry keys ownership by the id the declaration would have used, so Foo and _Foo, or Base in two namespaces, stay distinct. A lookup by name only answers when one declaration in the file spells it.

Cross-file references needed a second change. ensure_named_node is per file, so a reference in b.ts to Ts in a.ts was minted from b.ts's stem, which is b.ts's own file id:

 b.ts   import { Ts } from "./a";  @Ts class Other {}

 before
-  Other --references--> b.ts        (the referring file)
   no edge to the class

 after
+  Other --references--> Ts (a.ts)
   corpus map: (resolved path, normalized name) -> declared id
   import fact selects the module, path-keyed, so two modules may declare Ts

Evidence

The test commit is red on the base tree. The implementation commits flip it green, one concern at a time:

commit new test file
1517f89e tests only, base code 61 failed, 9 passed
bcea646b registry and mint sites 2 failed, 68 passed (Other -> b.ts remains)
6755a5a7 corpus map 1 failed, 69 passed (schema pin)
9290d9fc schema 30 70 passed, 1 skipped

The cases that failed on the experiment branch and now pass:

class Js {} + export const $b692bab43393 = 1     before: const dropped
                                                after:  both nodes, distinct ids

a.ts export class Ts
b.ts @Ts class Other                            before: Other -> references -> b.ts
                                                after:  Other -> references -> Ts (a.ts)

a1.ts, a2.ts both export Ts
b.ts imports a1 and @Ts                         after:  binds a1's Ts, not a2's

Full suite, no env var:

.venv/bin/python -m pytest -q -p no:randomly
9036 passed, 18 skipped, 1 xfailed, 2398 warnings in 556.48s

.venv/bin/python -m pytest -q tests/test_file_id_collision_4854.py
70 passed, 1 skipped   (twice in a row, cold and warm)

The 71 parametrized cases cover JS, TS, Python, Java, PHP, Ruby, C++, C headers, Rust, Go, C#, Swift, Kotlin, Scala, and Julia. One skip: C++ namespace declarations are not modeled by the extractor, confirmed by the control name.

Type of change

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

Verification & Invariants

The invariant: a node id is unique in the corpus, a declaration's id is stable across runs, and every reference to that declaration uses it. The tests assert behaviour (labels, source files, edges, build labels), not the helper.

  • Read the CONTRIBUTING.md guide.
  • Reproduced the issue and identified the invariant.
  • Made the smallest fix necessary.
  • Added a regression test (bug fix).
  • Kept the PR description synchronized with the final implementation.
  • Documented the limitations below.

How was this tested?

.venv/bin/python -m pytest -q tests/test_file_id_collision_4854.py
  70 passed, 1 skipped

.venv/bin/python -m pytest -q tests/test_extract.py tests/test_build.py \
    tests/test_cache.py tests/test_dedup.py tests/test_ext_tagged_id_clash.py \
    tests/test_file_node_id_spec.py
  624 passed, 1 skipped, 1 xfailed

.venv/bin/python -m pytest -q -p no:randomly
  9036 passed, 18 skipped, 1 xfailed in 556.48s

The targeted extraction, build, cache, dedup, and existing id-collision tests ran after the fix. The full suite ran on the final tree with no environment variables set.

Merge Danger

Door: two-way. A revert restores the previous ids for the colliding declarations only; unaffected files keep the same ids before and after. The one persisted change is the AST cache schema, and reverting the code makes the schema-30 entries miss and re-extract, which is safe.

Blast Radius: narrow, but corpus-wide in code paths. The behaviour change applies to every language that mints declaration ids through the engine, plus Rust, Go, and Julia. It only fires when a declaration name normalizes to the file extension (Js in .js, Ts in .ts, Java in .java, and so on), so ordinary files produce byte-identical ids. build() keeps the file and the declaration for each fixture; no self-contains edges remain.

Schema: _AST_CACHE_SCHEMA is 30 (base 29). Cached per-file results under 29 carry the dropped declaration, so they are ignored and re-extracted. An existing graph.json built before this change keeps the missing class until a full rebuild: graphify update only re-extracts changed files, so delete graphify-out/ or pass a fresh --out once after upgrading.

Limitations

  • Cross-file references: decorator and inheritance are covered. new Ts() and TS type annotations do not emit a cross-file reference edge in this extractor today, so no test claims them.
  • Standalone extractors: rust, go, and julia use the registry at their choke points. Apex, Bash, Dart, DM, Elixir, Erlang, Fortran, Markdown, Objective-C, OCaml, Pascal/Pascal Forms, PowerShell, R, Robot, Solidity, SQL, VB.NET, Verilog, Zig, and the YAML/JSON/Terraform config extractors still mint from the file stem and are not covered here. The zoo does not test them.
  • C++ namespace declarations are not modeled, which is why the zoo skips that kind.

Graphify-specific checklist

  • I updated generated skill artifacts (uv run python -m tools.skillgen --bless) when changing their source fragments. (N/A: no fragments touched.)
  • I confirmed that AST/structural extraction remains deterministic (no ambient state dependencies like ENV variables). The registry is per-file and ordered by the walk; no env switch.
  • I reviewed changes for security implications (no unsafe interpolation into shell/Python).
  • I confirmed no API keys or local-only graph data are included.
  • (If applicable) I disclosed AI authorship in my commit messages. (No trailer in the commit messages.)

The matrix covers JS, TS, Python, Java, PHP, Ruby, C++, C headers, Rust,
Go, C#, Swift, Kotlin, Scala, and Julia. Each case asserts the file and the
declaration both survive with distinct ids, no self-contains edge, and the
expected containment/ownership edge.

The reference cases go beyond the old cross_file_use fixture, which only
checked the import edge while the decorator reference still pointed at the
file node:

- intra-file decorator and cross-file decorator (including two modules that
  export the same name, where the imported module must win)
- cross-file inheritance
- a legal identifier equal to the salted id cannot steal it
- bundle.min.js keeps its class and method
- Rust struct keeps its node
- prototype methods attach to the salted class
- empty-normalizing names stay skipped (Graphify-Labs#1899)
- fresh and cache-hit extraction agree
- the AST schema bump documents Graphify-Labs#4854

The zoo skips a kind only when the control name shows the extractor does not
model that kind at all, so a newly added declaration kind that mints from the
file stem fails here instead of silently dropping a node.

Refs Graphify-Labs#4854
A declaration whose normal id equals its file node's id took the file's
identity: add_node dropped it, the file carried its callable flags, and a
self-contains edge appeared (Graphify-Labs#4854). The cause is that file ids are the
path stem and symbol ids are stem + name, so `class Js` in `a.js` and the
file both normalize to `a_js`.

`DeclIdRegistry` assigns ids per file with an availability check:

- the file id is reserved;
- a declaration whose id is taken by the file, or by another declaration's
  salted id, gets `sha1(name)[:12]` appended;
- if that candidate is already in the node set or assigned to another
  declaration, a deterministic counter (2, 3, ...) appends until free;
- the same declaration re-resolves to its assigned id, so reopened classes
  and cfg twins stay on one node;
- a plain duplicate id owned by a real declaration (a prototype owner, a
  redeclared name) reuses that id instead of minting a second node.

Mint sites: the generic class/type and function sites, the JS/TS extra walk
(function, property, const, namespace), the C++ alias, and the prototypes /
exported objects. `ensure_named_node` resolves a declared name from the
registry and never returns the file's own id for a reference.

Standalone extractors with their own file-stem minting use the same registry
at their choke points: rust.py `file_item_nid`, go.py `symbol_nid` /
`type_symbol_nid`, and julia.py top-level declarations. C#/Python keep their
existing `_underscore_salted_nid` result and the new check runs on top of it.

Refs Graphify-Labs#4854
`ensure_named_node` is per file, so a reference in b.ts to `Ts` declared in
a.ts was minted under an id derived from b.ts, and `@Ts class Other` ended up
pointing at b.ts's own file node (Graphify-Labs#4854).

The symbol-resolution pass now builds a corpus map of declarations keyed by
(resolved source path, normalized name) from the actual nodes, then uses the
JS/TS import facts to retarget a sourceless reference stub in the importer to
the declaration in the imported module. Keying by path makes the binding exact
when two modules export the same name; the old unique-label rewire could not
choose.

The pass is limited to JS/TS importers and `references` edges so it cannot
disturb CommonJS require bindings or the Python alias handling (Python
aliases are resolved by their own pass).

Refs Graphify-Labs#4854
Per-file AST results cached under schema 29 carry the dropped declaration
and the file-id-shaped reference targets, so they must re-extract (Graphify-Labs#4854).

Bump `_AST_CACHE_SCHEMA` to 30 and document the rebuild requirement: a graph
built before this change keeps the missing class until a full rebuild, because
an incremental update only re-extracts changed files.

Refs Graphify-Labs#4854
@github-actions

Copy link
Copy Markdown

Thanks for the pull request, @Deepjyoti-Sarmah. 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.

@github-actions github-actions Bot added the contributor Pull request from a returning community contributor label Oct 29, 2026

@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.

Worth a look — the grounded gate found no coupling regressions or blocking issues, but 4 advisory finding(s) below merit a look before merge.

Not checked: tests were not run; formal verification proved 0 of 8 changed function(s) (3 sampled, not proven, 5 not verified).

Formal verification. PR-changed functions: 3/8 verified (0 proven, 3 may-equivalent, 0 distinguished) · 5 not verified (3 vacuous, 2 unsupported).

Not verified on this run: \_cpp\_extra\_walk (vacuous: never exercised), \_extract\_generic (unsupported), \_js\_extra\_walk (vacuous: never exercised), \_ts\_extra\_walk (vacuous: never exercised), \_apply\_symbol\_resolution\_facts (unsupported).


Graphify review — findings

Fixes declarations being silently dropped when their id collides with their file node's id: the extractors now salt the declaration id through a DeclIdRegistry availability check, so the file and the declaration stay distinct nodes. The C++ alias and Julia paths are where the ids that declarations get and the ids that edges and references point at have to line up. Bumps _AST_CACHE_SCHEMA to 30 so cached extractions re-run, but an existing graph keeps the dropped class until a full rebuild, since incremental updates only re-extract changed files.

Worth a look

  • C++ alias node no longer emitted when decl_node_fn is omitted — graphify/extractors/engine.py:5095 · Escalate · high
    • NOT verified (no proof, no reproducing execution) — needs human review
  • C++ alias edge decision uses the pre-resolution id, which can orphan the alias node — graphify/extractors/engine.py:5095 · Escalate · medium
    • NOT verified (no proof, no reproducing execution) — needs human review
  • DeclIdRegistry collapses distinct declarations that normalize to the same id — graphify/ids.py:113 · Escalate · medium
    • NOT verified (no proof, no reproducing execution) — needs human review
  • Julia reference ids bypass the new DeclIdRegistry, so they can diverge from declaration ids — graphify/extractors/julia.py:68 · Escalate · medium
    • NOT verified (no proof, no reproducing execution) — needs human review

Review partial — this diff was larger than one review pass covers, so later files were not reviewed; some findings may be missing.

Analysis details — impact, health, verification

Impact & health

Graphify review

Impact — 5665 functions depend on the 753 functions this change touches.

Health — this change adds coupling hotspots:

  • worse: extract() — 1057 callers, 62 callees
  • worse: _extract_generic() — 20 callers, 49 callees
  • worse: build() — 85 callers, 6 callees
  • worse: extract_rust() — 38 callers, 10 callees
  • worse: extract_go() — 19 callers, 11 callees
  • worse: extract_julia() — 22 callers, 9 callees
  • worse: walk() — 1 callers, 79 callees
  • worse: _apply_symbol_resolution_facts() — 5 callers, 12 callees
  • …and 3 more — each is listed as a finding

Verification — 5665 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: 3349 function(s) in the blast radius were not formally verified this run

Test selection

Test selection

193 of 470 test file(s) selected (41%) via static blast radius.

  • tests/test_alias_folding.py — impact
  • tests/test_analyze.py — impact
  • tests/test_astro_extraction.py — impact
  • tests/test_astro_import_ids.py — impact
  • tests/test_atomic_writes.py — impact
  • tests/test_benchmark.py — impact
  • tests/test_benchmark_raw_graph.py — impact
  • tests/test_benchmark_real_query.py — impact
  • tests/test_binary_media_words.py — impact
  • tests/test_build.py — impact
  • tests/test_build_located_semantic_identity.py — impact
  • tests/test_build_merge_dedup_scope.py — impact
  • tests/test_build_merge_hyperedges_and_prune.py — impact
  • tests/test_build_merge_shrink_guard.py — impact
  • tests/test_c_include_resolution.py — impact
  • tests/test_cache.py — impact
  • tests/test_cache_long_paths.py — impact
  • tests/test_cache_stale_import_target.py — impact
  • tests/test_carried_hyperedge_remap.py — impact
  • tests/test_charmap_encoding.py — impact
  • tests/test_chunking.py — impact
  • tests/test_cjs_module_extension.py — impact
  • tests/test_cli_export.py — impact
  • tests/test_cluster.py — impact
  • tests/test_community_labels_skill.py — impact
  • tests/test_compact_graph_json.py — impact
  • tests/test_confidence.py — impact
  • tests/test_corrupt_graph_json.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_csharp_object_creation.py — impact
  • tests/test_csharp_partial_classes.py — impact
  • tests/test_csharp_type_resolution.py — impact
  • tests/test_dart.py — impact
  • tests/test_dedup.py — impact
  • tests/test_dedup_remaps_hyperedges.py — impact
  • tests/test_dedup_shrink_refuses_force_write.py — impact
  • tests/test_dedup_survivor_richness.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_ejs_extractor.py — impact
  • tests/test_evidence_binding.py — impact
  • tests/test_export.py — impact
  • tests/test_export_control_characters.py — impact
  • tests/test_ext_tagged_id_clash.py — impact
  • tests/test_external_stub_endpoints.py — impact
  • tests/test_extract.py — impact
  • … and 143 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.

Docs that may be stale (advisory)

…and 10 more.

Formal verification

Could not verify: Could not verify \_cpp\_extra\_walk.

The verifier did not have enough to check \_cpp\_extra\_walk, 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: not verifiable: all 264 sampled inputs raised on both versions — the function never executed, so 'no divergence' would be vacuous (mostly AttributeError — names the real obstacle, not a sampling gap)

Could not verify: Could not verify \_extract\_generic.

The verifier did not have enough to check \_extract\_generic, 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: parameter `config` is annotated `LanguageConfig` — outside the synthesizable primitive/collection set

Could not verify: Could not verify \_js\_extra\_walk.

The verifier did not have enough to check \_js\_extra\_walk, 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: not verifiable: all 264 sampled inputs raised on both versions — the function never executed, so 'no divergence' would be vacuous (mostly AttributeError — names the real obstacle, not a sampling gap)

Could not verify: Could not verify \_ts\_extra\_walk.

The verifier did not have enough to check \_ts\_extra\_walk, 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: not verifiable: all 264 sampled inputs raised on both versions — the function never executed, so 'no divergence' would be vacuous (mostly AttributeError — names the real obstacle, not a sampling gap)

No difference found (not proven): No behavior difference found in extract\_go (not a proof).

The verifier ran both versions of extract\_go on many inputs and saw identical behavior every time. Strong evidence the change is safe, but evidence, not a proof.

Guarantee: Empirical: differential testing (both versions run on many generated inputs). A divergence on an untested input remains possible, so this is 'no counterexample found', not 'proven equivalent'.

Note: An input the sampler did not try could still differ.

No difference found (not proven): No behavior difference found in extract\_julia (not a proof).

The verifier ran both versions of extract\_julia on many inputs and saw identical behavior every time. Strong evidence the change is safe, but evidence, not a proof.

Guarantee: Empirical: differential testing (both versions run on many generated inputs). A divergence on an untested input remains possible, so this is 'no counterexample found', not 'proven equivalent'.

Note: An input the sampler did not try could still differ.

Could not verify: Could not verify \_apply\_symbol\_resolution\_facts.

The verifier did not have enough to check \_apply\_symbol\_resolution\_facts, 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: parameter `facts` is annotated `_SymbolResolutionFacts` — outside the synthesizable primitive/collection set

No difference found (not proven): No behavior difference found in extract\_rust (not a proof).

The verifier ran both versions of extract\_rust on many inputs and saw identical behavior every time. Strong evidence the change is safe, but evidence, not a proof.

Guarantee: Empirical: differential testing (both versions run on many generated inputs). A divergence on an untested input remains possible, so this is 'no counterexample found', not 'proven equivalent'.

Note: An input the sampler did not try could still differ.

· 1 grounded finding(s) anchored inline below; 10 more finding(s) on lines outside this diff (see the check run).



@pytest.mark.parametrize("filename,body,control", ZOO, ids=[f"{i}-{z[0]}" for i, z in enumerate(ZOO)])
def test_zoo_declaration_kinds_keep_their_node(tmp_path, filename, body, control):

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Health regression — test_zoo_declaration_kinds_keep_their_node()

fans out to 6 callees (efferent coupling).

Grounded coupling-delta finding (deterministic), not an LLM guess.

@safishamsi

Copy link
Copy Markdown
Member

Landed in v0.9.98, now on PyPI (pip install graphifyy==0.9.98). File and per-declaration ids are kept distinct, so a top-level declaration matching its file name is no longer dropped. Thanks for the fix, @Deepjyoti-Sarmah.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

contributor Pull request from a returning community contributor

Projects

None yet

Development

Successfully merging this pull request may close these issues.

JS file/class ID collision drops class Js and emits self-contains edges (0.9.87)

2 participants