Skip to content

feat: semantic code impact analysis and change propagation engine - #1298

Open
kashviporwal-byte wants to merge 2 commits into
CodeGraphContext:mainfrom
kashviporwal-byte:feat/impact-analysis
Open

kashviporwal-byte wants to merge 2 commits into
CodeGraphContext:mainfrom
kashviporwal-byte:feat/impact-analysis

Conversation

@kashviporwal-byte

Copy link
Copy Markdown
Contributor

Resolves #1164

Overview

This PR implements the Semantic Code Impact Analysis & Change Propagation Engine. It enables developers to predict the blast radius of modifying a code symbol or file before merging changes, reducing the risk of regressions and speeding up code review.

It leverages the repository knowledge graph to traverse upstream dependencies (like callers, subclasses, decorator modifications, and injected classes), calculates a custom risk score, and displays propagation paths and testing recommendations.


Detailed Changes

1. Backend Engine & Graph Traversal (src/codegraphcontext/)

  • Tool Registration (tool_definitions.py): Defined the analyze_impact tool accepting arguments: target (required), target_type, repo_path, and depth.
  • API Handler (tools/handlers/analysis_handlers.py & server.py): Connected the tool call through the FastAPI REST server /api/tools/call.
  • Cypher Traversal Engine (tools/code_finder.py): Implemented the core logic for the change propagation analyzer:
    • Target Auto-Detection: Dynamically resolves if the input target is a file path or a code symbol (Function, Class, Module, etc.). When a file is specified, it matches all symbols defined inside it.
    • Upstream Change Propagation: Executes a database-agnostic Cypher query traversing CALLS, INHERITS, IMPLEMENTS, INJECTS, DECORATED_BY, and IMPORTS relationships backward up to a configurable depth.
    • Multi-Database Compatibility: Utilizes standard Cypher list comprehensions for path projection (nodes(p) and relationships(p) mapping), making it fully compatible with Neo4j, FalkorDB, and KuzuDB.
    • Git Churn Integration: Spawns a local git process (git rev-list --count) to retrieve file modification counts, integrating historical churn into the risk calculations.
    • Rule-Based Explanation Generator: Automatically builds precise test scoping suggestions based on the dependency types found.

2. Risk Scoring System

Computes a normalized risk score out of 10.0 based on:

  1. Depth Score (clamped to 5.0): Distance of the propagation path.
  2. Blast Radius File Score (clamped to 5.0): Count of distinct files affected.
  3. Criticality Score (clamped to 5.0): In-degree centrality (incoming links to target).
  4. Historical Churn Score (clamped to 5.0): How often the target files are modified in git history.

3. Visual Dependency Explorer (website/)

  • CodeGraphViewer UI Panel (CodeGraphViewer.tsx):
    • Added a Semantic Impact Explorer button (Zap icon) to the sidebar panel header.
    • Added a hybrid client-side/API resolver: queries the local python API if connected, and falls back to an in-memory BFS search on the client-side if offline or running in a static web build.
    • Rendered a rich dashboard: circular radial gauge color-coded by risk severity level (Green/Teal for Low, Orange for Medium, Red for High), breakdown metric cards, a blast radius list, and explanation cards.
    • Integrated visual force-graph highlighting: dims non-affected nodes/edges and applies color-coding directly to the 2D/3D force graph representations (Red for Target, Orange for Direct Impact, Yellow for Indirect Impact).

Verification & Testing

Automated Tests

Created unit test suite tests/unit/tools/test_impact_analysis.py covering target symbol resolution, file-level containment queries, risk scoring heuristics, empty states, and local Git command fallbacks.
Run commands:

$env:PYTHONPATH="src"; python -m pytest tests/unit/tools/test_impact_analysis.py

Status: All 3 tests passed successfully.

Manual Verification

  • Verified backend /tools/call endpoint returns exact propagation paths.
  • Verified that selecting a node in the graph explorer successfully highlights dependencies, updates the sidebar dashboard, and dims unrelated nodes in both 2D and 3D visual modes.

Checklist

  • My code follows the style guidelines of this project
  • I have performed a self-review of my own code
  • I have commented my code, particularly in hard-to-understand areas
  • I have added unit tests that prove my fix is effective or that my feature works
  • New and existing unit tests pass locally with my changes

@vercel

vercel Bot commented Jun 21, 2026

Copy link
Copy Markdown

@kashviporwal-byte is attempting to deploy a commit to the shashankss1205's projects Team on Vercel.

A member of the Team first needs to authorize it.

@Shashankss1205

Copy link
Copy Markdown
Collaborator

👋 Thanks for contributing to CodeGraphContext! Since this PR was opened, main has moved forward significantly (we just shipped v0.5.2 and merged ~50 PRs), so this one now has merge conflicts. Could you please rebase onto the latest main and resolve the conflicts? Once it is conflict-free and CI is green, we will review and merge it. Really appreciate your work — thank you! 🙏

@Shashankss1205

Copy link
Copy Markdown
Collaborator

Triage update: change-impact analysis is a compelling direction (and pairs naturally with the cgc diff request in #1312). The branch conflicts with main's current query layer; @kashviporwal-byte please rebase, and make sure the new engine has unit tests against at least the Kùzu backend (our embedded default on several platforms) — backend-portable Cypher has bitten us before. 🙏

Resolves CodeGraphViewer.tsx conflicts with the dual-engine AI explorer
(CodeGraphContext#1588): both sides added a sidebar mode, so isImpactMode and isAIMode
are chained in the ternary rather than replacing each other.

Also updates the _FakeDBManager stub for get_driver(graph_name).

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

@Shashankss1205 Shashankss1205 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

I've resolved the conflicts and pushed the merge to your branch, so this is up to date with main now — but I can't merge it yet, because analyze_impact fails on every call against KùzuDB. The unit tests don't catch this: _FakeSession returns canned rows without validating against a real schema.

Blocker 1 — File nodes have no uid.
code_finder.py:1585 does RETURN f.uid as uid for File, but File is the one node label keyed by path, not uid:

("File", "path STRING, name STRING, relative_path STRING, package_name STRING, is_dependency BOOLEAN, PRIMARY KEY (path)")

(database_embedded_kuzu.py:173 — compare Function/Class/Variable on lines 177-179, which do have uid.) This query runs unconditionally before the symbol lookup, so:

RuntimeError: Binder exception: Cannot find property uid for f.

Blocker 2 — the propagation query uses a construct KùzuDB doesn't support.
Patching past blocker 1 locally, code_finder.py:1661 then fails:

RuntimeError: Binder exception: Variable n is not in scope.

from

RETURN [n in nodes(p) | {uid: n.uid, name: n.name, path: n.path, labels: labels(n)}] as path_nodes

Path-list comprehensions over nodes(p)/relationships(p) are a Neo4j-ism. This is the same class of problem as #1512.

Note blocker 2 also affects the criticality_query at line 1719 (target.uid) once a File ends up in target_uids.

What I'd suggest:

  • Give File a synthetic identity in the query (RETURN f.path as uid) and handle it consistently in target_uids — the generic MATCH (target) WHERE target.uid IN ... will hit the same missing-property error whenever a File is a target.
  • Rewrite the propagation query without path comprehensions, or gate the whole feature on backend and provide a Kùzu-compatible variant. report_generator.py and java_toolkit.py are good references for queries that work across backends.
  • Add at least one test that runs against a real embedded Kùzu database rather than _FakeSessiontests/unit/core/test_database_kuzu_kotlin_metadata.py shows the pattern.

The design and the UI side are good, and the merge conflict with #1588's AI explorer is already sorted out for you. It's specifically the backend query compatibility that needs another pass. Happy to help if you get stuck — just reply here.

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

Labels

None yet

Projects

Status: Backlog tasks

Development

Successfully merging this pull request may close these issues.

feat: semantic code impact analysis and change propagation engine

2 participants