Skip to content

perf(indexer): hash definitions in Rust on py-tree-sitter's own trees - #3475

Merged
vitali87 merged 8 commits into
mainfrom
claude/cgr-rust-porting-mrwohh
Oct 27, 2026
Merged

vitali87 merged 8 commits into
mainfrom
claude/cgr-rust-porting-mrwohh

Conversation

@vitali87

@vitali87 vitali87 commented Oct 26, 2026 •

Copy link
Copy Markdown
Owner

Summary

Demo

cgr start --update-graph on rich, then the stored hashes and the duplicates report: main vs this branch

The GIF, recorded with VHS, indexes rich (213 Python files, no embeddings) from scratch on a main worktree, then on this branch. After each index it prints a hash of every anchor_hash and ast_fingerprint the graph holds, and a hash of the cgr duplicates report built on them:

  • main (7231f71): sync in 11.96 s; 3,892 anchor hashes and fingerprints, sha256 e15f33bc…; duplicates report sha256 8f94bf66….
  • This branch (073d57c): sync in 11.65 s; the same 3,892 values and the same two hashes, so the graph and the duplicates report are unchanged.

Timed without recording, in the same two worktrees (identical packages), over 5 alternating runs each, the branch was faster in every pair: sync median 12.52 s → 12.01 s (−4%), wall 16.32 s → 15.48 s. On rich the two hashes are about 5.7% of a run, so about 5% is all that porting them can save there. On code-graph-rag's own tree, where they are 9.4%, the run went from 222.5 s to 206.0 s.

The GIF is stored on the claude/cgr-rust-porting-mrwohh-evidence branch and is not part of this PR's diff.

How it works

A py-tree-sitter Node object holds the C tree node inside it. The Rust tree-sitter crate 0.26.8 contains the same C code for walking a tree as the py-tree-sitter 0.26.0 that cgr pins: node.c, tree.c, tree_cursor.c, subtree.h and language.c are byte-identical. So TreeBridge (rust/cgr_graph_rs/src/trees/) copies the node out of the Python object and walks the real tree in place.

Guards, because Rust reads memory py-tree-sitter owns:

  • On construction, the bridge refuses any py-tree-sitter version other than the one it was checked against, and any build whose object sizes don't match the expected layout.
  • On every call, before following any pointer, it checks that the object is exactly a tree_sitter.Node, that its tree is exactly a tree_sitter.Tree, and that both point at the same underlying tree.
  • Before first use, codebase_rag/parsers/native_trees.py parses a sample source and compares every node, and both fingerprints of every node, as Rust and Python read them. Any difference turns the bridge off for the process.
  • Anything it can't read exactly (a test double, a tree parsed from a callback, odd arguments) raises NotBorrowed, and that call runs the Python version.

The classification rules (which node types count as punctuation, identifiers and so on) are passed from constants/ into Rust as a TreeRules TypedDict when the bridge is built, so the two versions can't drift apart on them.

Results

Python Rust
anchor_hash, per definition 148–169 µs 17–24 µs
compute_ast_fingerprint, per definition 214–237 µs 38–43 µs
Indexing code-graph-rag (no embeddings, one run each) 222.5 s 206.0 s (1.08x)
Indexing rich (no embeddings, median of 5) 12.52 s 12.01 s (1.04x)

Both savings match what the profiles predicted for these two walks: 7.4% measured against 7.8% on code-graph-rag, and 4% against about 5% on rich. They were only about 9% of the run, so the larger wins are in the follow-up issues.

Correctness:

  • Node-by-node: every named node of 3,309 files in 14 languages (about 3.0 million nodes) was fingerprinted both ways. There were no differences.
  • Whole graph: indexing code-graph-rag with the bridge on and off gave byte-identical graphs (214,479 nodes and edges, including 35,527 anchor hashes and 32,509 fingerprints).
  • rich: the nodes were identical. The edges differed only in the resolution label of a few CALLS edges, and two runs with the bridge off already differ in that label.

Type of Change

  • Bug fix
  • New feature
  • Performance improvement
  • Refactoring (no functional changes)
  • Documentation
  • CI/CD or tooling
  • Dependencies

Related Issues

Related to #3146, #3473, #3474 (the next steps the revised plan orders) and #3472 (a torch-free embedder, measured separately).

Test Plan

  • Unit tests pass (uv run pytest -n auto -m "not integration", with the extras CI installs): 23,842 passed, 4 failed. The 4 need toolchains this environment lacks: the .NET SDK (two C# oracle guards) and the Go go/types helper, which could not download its modules (two Go oracle tests). All four fail the same way with the bridge switched off. After the crate version bump, the packaging tests (39) and the licence check pass.
  • New tests added:
    • codebase_rag/tests/test_native_trees.py compares Rust and Python on every named node of a sample in each language and of cgr's own parser sources. It also pins every fallback, and fails if the extension carries the bridge but the bridge is off.
    • TestVersionPair in the same file holds pyproject.toml's tree-sitter== pin, and Cargo.toml's and Cargo.lock's tree-sitter crate, to the pair the bridge was checked with (TreeBridge.PY_TREE_SITTER, TreeBridge.TREE_SITTER_CRATE). Bumping either pin alone, as a Dependabot pull request would, fails that pin's test with a message naming the checked version and pointing to AGENTS.md. I checked this by moving both pins and watching both tests fail, then pass again once restored.
    • The Rust unit tests in src/trees/tests.rs pin the Python versions' exact values.
    • The new test file is added to the Rust CI job.
  • Integration tests pass (make test-integration, requires Docker). Not run: no Docker here.
  • Manual testing:
    • the node-by-node comparison across 14 languages, and the bridge-on/off graph comparisons on rich and on code-graph-rag described above;
    • cargo test --release (56 passed);
    • cargo clippy --features python: nothing new; the two existing warnings in lib.rs remain.

Checklist

  • PR title follows Conventional Commits format
  • A breaking change has ! in the title and its release notes in changes/breaking/<PR number>.md: not a breaking change.
  • All pre-commit checks pass (make pre-commit)
  • No hardcoded strings in non-config/non-constants files
  • No # type: ignore, cast(), Any, or object type hints
  • New comments and docstrings explain why, not what

For the maintainer

  • Crate version: cgr-graph-rs goes from 0.1.0 to 0.1.1, as the "Crate version bumped with its code" check requires for any change to the library. The bridge only adds API, so the requirement stays below 0.2 and its floor rises to 0.1.1. uv.lock was regenerated with uv 0.13.5, the version CI resolves; only the crate's version line changed. An older 0.1.0 wheel has no TreeBridge, and the Python versions run there.
  • Fuzz image Rust: .clusterfuzzlite/Dockerfile goes from rustc 1.85.0 to 1.97.0, the toolchain this branch was built and tested with. The fuzz build compiles the crate from this checkout, and its new dependencies need at least 1.90 (tree-sitter-language 0.1.9, which the tree-sitter crate pulls in; sha2 0.11 needs 1.88). I checked that the crate builds on 1.90.0 and 1.97.0 and fails on 1.85.0 exactly as the fuzz job did.
  • Upgrades: a future py-tree-sitter upgrade must be checked against the tree-sitter crate, and the two bumped together, as AGENTS.md ("Bumping tree-sitter") describes step by step. A lone bump fails TestVersionPair, and the bridge switches itself off, so the slowdown can't go unnoticed.
  • .gitignore: AGENTS.md and CLAUDE.md are no longer ignored, so every agent gets the same instructions from the repository; PROJECT.md stays ignored. In a checkout that already has its own untracked CLAUDE.md, pulling this stops with "untracked working tree files would be overwritten"; move those notes to the user-level ~/.claude/CLAUDE.md first. .dockerignore still keeps all of these out of the image.

Summary by CodeRabbit

  • New Features
    • Definition hashes and clone-detection fingerprints can now be computed using native acceleration on already-parsed syntax trees.
  • Reliability
    • Python-based processing remains available when native acceleration is unavailable or produces results that differ from the reference behavior.
  • Documentation
    • Updated architecture and performance documentation to describe native tree processing, compatibility checks, and fallback behavior.

@greptile-apps

greptile-apps Bot commented Oct 26, 2026 •

Copy link
Copy Markdown
Contributor

TREX TREX is testing this pull request...

  • Plan what to test
  • Set up the environment and test the changed flows
  • Post test results

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 26, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-26T13:42:13.595533Z 044e579 PR opened
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@coderabbitai

coderabbitai Bot commented Oct 26, 2026 •

Copy link
Copy Markdown

Review in Change Stack →

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review

No actionable comments were generated in the recent review.

Recent review info
Run configuration
Commits

Reviewing files that changed from the base of the PR and between 073d57c and 5dde5fc.

Files selected for processing: 10
  • .dockerignore
  • .github/copilot-instructions.md
  • .gitignore
  • AGENTS.md
  • CLAUDE.md
  • GEMINI.md
  • codebase_rag/tests/test_native_trees.py
  • docs/reports/INDEXER_RUST_PLAN.md
  • rust/cgr_graph_rs/Cargo.toml
  • rust/cgr_graph_rs/src/trees/python.rs
Files with no reviewable changes: 1
  • .gitignore

Included review availability: This review used your included allowance. Your plan provides up to 8 included reviews per hour; 7 remain after this review.

Walkthrough

The Rust extension now computes definition anchor hashes and AST fingerprints from existing py-tree-sitter trees. Python checks bridge compatibility and parity, then uses Python implementations when the bridge is unavailable or cannot read a node.

Changes: Native tree walks

Layer / File(s) Summary
Rust tree-walk algorithms
rust/cgr_graph_rs/Cargo.toml, rust/cgr_graph_rs/src/trees/*, rust/cgr_graph_rs/THIRD_PARTY_LICENSES.md, rust/cgr_graph_rs/README.md
Adds configurable Rust anchor hashing and AST fingerprinting over tree-sitter nodes. Rust tests cover the algorithms. Cargo dependencies, license entries, and extension documentation are updated.
Python tree bridge
rust/cgr_graph_rs/src/lib.rs, rust/cgr_graph_rs/src/trees/python.rs
Registers the Python-facing bridge. Construction checks the py-tree-sitter version and object layouts. Each call checks node and tree types, pointers, and tree identity.
Python dispatch and compatibility probe
codebase_rag/constants/embedded_graph.py, codebase_rag/exceptions.py, codebase_rag/logs.py, codebase_rag/parsers/native_trees.py, codebase_rag/parsers/anchor_hash.py, codebase_rag/parsers/ast_fingerprint.py, codebase_rag/types_defs.py
Adds bridge rules, initialization, and probe comparisons for tree descriptions, anchor hashes, and fingerprints. Public hash and fingerprint functions use the bridge when available and fall back to Python implementations when unavailable or when NotBorrowed is raised.
Parity and release integration
codebase_rag/tests/test_native_trees.py, .github/workflows/ci.yml, docs/architecture/embedded-graph.md, docs/reports/INDEXER_RUST_PLAN.md, pyproject.toml, rust/cgr_graph_rs/pyproject.toml, codebase_rag/tests/test_rust_extension_packaging.py
Adds parity, fallback, and compatibility tests and includes the new test file in CI. Updates documentation, the extension version, dependency minimum, and published artifact expectations.

Repository guidance

Layer / File(s) Summary
Contributor and agent instructions
.dockerignore, .github/copilot-instructions.md, .gitignore, AGENTS.md, CLAUDE.md, GEMINI.md
Adds shared agent guidance and tree-sitter pin update procedures. Changes ignore rules for agent instruction files.

Priority: Low

Estimated code review effort: 4 (Complex) | ~60 minutes

Change: Refactor

Sequence Diagram(s)

sequenceDiagram
  participant PythonCaller
  participant NativeTrees
  participant TreeBridge
  participant RustTrees
  participant PythonTwin
  PythonCaller->>NativeTrees: request anchor hash or AST fingerprint
  NativeTrees->>TreeBridge: construct bridge with Python rules
  TreeBridge->>RustTrees: compare tree layout, anchor hash, and fingerprint
  NativeTrees-->>PythonCaller: report bridge unavailable after probe failure or mismatch
  PythonCaller->>TreeBridge: request hash or fingerprint
  TreeBridge->>RustTrees: walk borrowed tree node
  TreeBridge-->>PythonCaller: raise NotBorrowed when node cannot be read
  PythonCaller->>PythonTwin: compute result when bridge is unavailable or node is unreadable
Loading

Possibly related issues

Possibly related PRs

  • vitali87/code-graph-rag#3329: This PR changes the implementation that computes definition anchor_hash values used to repair gloss mentions after renames or moves.

Suggested reviewers: claude

Merge Risk: Minimal · up to 5dde5

No actionable issue is established from the available evidence. The change appears mergeable after normal checks.

Pre-merge checks: Passed 4
Check name Status Explanation
Title check Passed The title clearly and concisely describes the primary change: moving definition hashing to Rust while using py-tree-sitter trees. It also follows Conventional Commits format.
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
Description check Passed The description follows the repository template and covers every required section. It gives a clear summary of the two fingerprints moved to Rust, the py-tree-sitter bridge, and the pin pairing. It in…
Full details: Description check

Explanation

The description follows the repository template and covers every required section. It gives a clear summary of the two fingerprints moved to Rust, the py-tree-sitter bridge, and the pin pairing. It includes a demo GIF with hashes, marks the Type of Change, lists related issues, and gives a detailed test plan. The checklist is complete, and the maintainer notes cover the crate version bump, toolchain change, and .gitignore impact. One gap: the Integration tests item is unchecked because Docker was unavailable, and the description says so. The Test Plan does not run the integration suite, which is a stated limitation and not a missing section.

Finishing Touches
📝 Generate docstrings
  • Commit to this branch
  • Create a new PR
🧪 Generate unit tests (beta)
  • Commit to this branch
  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@greptile-apps

greptile-apps Bot commented Oct 26, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerView in GreptileConfidence Score: 5/5

[Medium impact] The PR appears safe to merge; no blocking defects were found.

Summary

Moves definition hashes and clone fingerprints to Rust while keeping the Python implementations as fallbacks.

  • The indexer computes definition hashes in Rust on its existing syntax trees.
  • The Rust indexer plan now ranks follow-up work using fresh profiles.

vitali87 explicitly acknowledged that the crate release is deferred and existing wheels continue using Python. The description also acknowledges the release check.

Diagram

%%{init: {'theme': 'neutral'}}%%
flowchart TD
  A[Definition node] --> B{Bridge passes setup and probe?}
  B -->|No| P[Python hash walk]
  B -->|Yes| C{Bridge can read this node?}
  C -->|No| P
  C -->|Yes| R[Rust walk of existing tree]
  P --> O[Hash or fingerprint]
  R --> O
Loading

Reviews (1) · Last reviewed commit: "refactor: keep the tree bridge's names a..." · Reviewed by Greptile

@vitali87
vitali87 force-pushed the claude/cgr-rust-porting-mrwohh branch 2 times, most recently from bc366e6 to dcb5346 Compare October 26, 2026 13:59
@vitali87 vitali87 changed the title feat: hash definitions in Rust on py-tree-sitter's own trees, and re-measure the indexer Rust plan perf(indexer): hash definitions in Rust on py-tree-sitter's own trees Oct 26, 2026
@vitali87 vitali87 added the performance Performance improvements label Oct 26, 2026 — with Claude
@vitali87
vitali87 force-pushed the claude/cgr-rust-porting-mrwohh branch from dcb5346 to 073d57c Compare October 26, 2026 14:19
@sonarqubecloud

Copy link
Copy Markdown

@vitali87
vitali87 merged commit d27f021 into main Oct 27, 2026
60 of 61 checks passed
@vitali87
vitali87 deleted the claude/cgr-rust-porting-mrwohh branch October 27, 2026 14:04
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

performance Performance improvements

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

1 participant