diff --git a/openspec/changes/archive/2026-11-12-4662-faster-ast-graph/.openspec.yaml b/openspec/changes/archive/2026-11-12-4662-faster-ast-graph/.openspec.yaml new file mode 100644 index 0000000000..55ab199b3d --- /dev/null +++ b/openspec/changes/archive/2026-11-12-4662-faster-ast-graph/.openspec.yaml @@ -0,0 +1,2 @@ +schema: spec-driven +created: 2026-11-12 diff --git a/openspec/changes/archive/2026-11-12-4662-faster-ast-graph/design.md b/openspec/changes/archive/2026-11-12-4662-faster-ast-graph/design.md new file mode 100644 index 0000000000..60c9abb552 --- /dev/null +++ b/openspec/changes/archive/2026-11-12-4662-faster-ast-graph/design.md @@ -0,0 +1,15 @@ +# Design + +## Decisions +- **A substring test before the regex.** `_is_call_in_body` returns `target_name in body and re.search(...)`. The call pattern is `\b\s*\(` with the name escaped, so each match holds the name as written, and a body without the name cannot match. The result is the same for every name, and the regex runs on 191 of about 3 million pairs over this repository. Most names are Markdown headings with spaces or punctuation, such as `Directory Structure`. +- **One walk that skips ignored folders.** `_walk_files` lists each folder one time with `os.scandir`. It asks the ignore index about each subfolder (`is_dir=True`) and does not go into a subfolder that git ignores. `is_ignored_by_git` also reports `.git` as ignored. Then `_collect_target_files` chooses the files by extension from that one list, and checks each candidate with `_is_excluded` as before. +- **The order of `Path.rglob`.** `--max-files` keeps the first files in the order of the walk, so the order chooses which files the graph holds. `Path.rglob` in CPython 3.14 gives the files of each subfolder of a folder in turn, then goes into the last subfolder first. The new walk keeps a stack of subfolder lists to give the same order. A folder that it does not go into held only ignored files, so the other files keep their order. +- **A folder that cannot be listed.** `Path.rglob` went past a folder that it could not list. The new walk does the same and writes a debug log line. +- **The dry-run test.** The test checks that the command makes no external request under `--dry-run`. A small folder (`--dir src/devops_cli/ai/ast`) is sufficient for that check. + +## Rejected alternatives +- **One compiled pattern for each name (`functools.lru_cache`).** The issue proposes it. It gives the same result, but on the same data the link step took 4.8 s, against 0.25 s with the substring test. A module cache would also grow in the MCP server, which runs for a long time. +- **One set of call tokens for each body (`\b(\w+)\s*\(`).** It is exact only for a name that is all word characters. Over this repository, 1,550 of the 1,618 names have spaces or punctuation, so most names would still need the regex. +- **`os.walk` with pruned `dirnames`.** It gives a pre-order walk. Over this repository it found the same 4,783 Markdown files, but in a different order. Then `--max-files 100` chose other files, and the graph had 1,017 nodes and 4 edges in place of 1,889 nodes and 6 edges. +- **A walk in name order.** The output would not change between hosts, but it would choose other files under `--max-files`, and the issue asks for the same graph. A change of the file choice is a different change. +- **`git ls-files --cached --others --exclude-standard`.** It lists the files in one process, but the command also runs on a folder that is not a git repository, and the tests of the graph run with no git. diff --git a/openspec/changes/archive/2026-11-12-4662-faster-ast-graph/proposal.md b/openspec/changes/archive/2026-11-12-4662-faster-ast-graph/proposal.md new file mode 100644 index 0000000000..2751a9fd5c --- /dev/null +++ b/openspec/changes/archive/2026-11-12-4662-faster-ast-graph/proposal.md @@ -0,0 +1,38 @@ +# Proposal: #4662 + +## Why +`devops ai ast graph` was slow, and its dry-run test took 15.06 s in CI (#4662). Two parts of the build caused this: + +- The link step ran `re.search` with a new pattern for each pair of a symbol body and a name. There were about 3 million pairs over this repository. The pattern changed at each call, so each call missed the `re` cache and compiled the pattern again. +- The file walk ran `Path.rglob` one time for each of the 32 extensions and 2 container file names. Each walk went into `.venv`, `.git` and the other folders that git ignores, and dropped their files only after it found them. + +The dry-run test ran the command on the whole repository, but it checks only the exit code. + +## What Changes +- The link step searches a body for the call pattern of a name only when the body holds that name. The pattern holds the name as written, so a body without the name cannot match. Only 191 of the pairs over this repository get to the regex. +- The file walk lists the tree one time with `os.scandir` and does not go into `.git` or a folder that git ignores. It keeps the order of `Path.rglob`, so `--max-files` chooses the same files. The graph of this repository has the same files, nodes and edges as before. +- The dry-run test of `ai ast graph` builds the graph of `src/devops_cli/ai/ast` with `--dir`, not of the whole repository. +- A spec delta adds the walk rule to `ast-support`: the command does not list an ignored folder. The change is observable as time and as the folders that the command reads. + +The change fits one pull request. + +## Capabilities +- `ast-support`: ADDED requirement "The code graph walk skips each ignored folder". + +## Impact +- `src/devops_cli/ai/ast/graph.py`: the walk and the call test. +- `tests/ai/ast/test_treesitter_engine.py`: two new tests. +- `tests/commands/test_ai_local_dry_run.py`: the dry-run case runs on a small folder. +- No new dependency. The output of the command does not change. + +## Feasibility +Confirmed on this repository with CPython 3.14.10, in one process, the old `graph.py` from `origin/main` beside the new one: + +- The old and the new build give the same hash of files, nodes and edges: 100 files, 1,889 nodes and 6 edges. +- At load average 10, the old build took 159 s and the new build took 8.8 s. The old file walk took 10.8 s and the new one took 4.8 s. +- In the link step, the substring test sends 191 pairs to the regex, and the step takes 0.25 s. One compiled pattern for each name (`functools.lru_cache`) took 4.8 s on the same data. +- The source of `glob._GlobberBase.recursive_selector` in CPython 3.14 gives the order of `Path.rglob`: the files of each subfolder of a folder, then the last subfolder first. The new walk gives the same order. The project requires Python 3.14 or later. +- The ignore index of `devops_cli.core.gitignore` stops at the first ignored folder of a path, so a file under an ignored folder is always ignored. A walk that does not go into an ignored folder finds the same files. + +## Existing Tool Considered +The standard library: `os.scandir` for the walk and `re` for the call test, with the ignore index that the project already has. `os.walk` gives a pre-order walk, which chooses different files under `--max-files`. `git ls-files` would start a process, and the command also runs on a folder that is not a git repository. No code is deleted except the per-extension `rglob` loops. Cost to build: about 40,000 tokens and 1 hour. diff --git a/openspec/changes/archive/2026-11-12-4662-faster-ast-graph/specs/ast-support/spec.md b/openspec/changes/archive/2026-11-12-4662-faster-ast-graph/specs/ast-support/spec.md new file mode 100644 index 0000000000..6693cc0917 --- /dev/null +++ b/openspec/changes/archive/2026-11-12-4662-faster-ast-graph/specs/ast-support/spec.md @@ -0,0 +1,8 @@ +## ADDED Requirements + +### Requirement: The code graph walk skips each ignored folder +`devops ai ast graph` SHALL list the files of its folder in one walk. The walk SHALL NOT list `.git`, a folder that git ignores, or a folder in one of them. + +#### Scenario: A folder that .gitignore names +- **WHEN** the graph is built for a folder that holds `.git`, a `.gitignore` that names `vendor/`, a Python file in `vendor/pkg/` and a Python file at the top +- **THEN** the walk lists only the top folder, and the graph indexes only the file at the top diff --git a/openspec/changes/archive/2026-11-12-4662-faster-ast-graph/tasks.md b/openspec/changes/archive/2026-11-12-4662-faster-ast-graph/tasks.md new file mode 100644 index 0000000000..2aecb0dd52 --- /dev/null +++ b/openspec/changes/archive/2026-11-12-4662-faster-ast-graph/tasks.md @@ -0,0 +1,21 @@ +# Tasks + +## 1. Walk the tree once and skip ignored folders (behavior) + +- [x] 1.1 Write a failing test: the build lists no ignored folder and no `.git`, and indexes only the file outside them + - Verification: `$ uv run devops ci test tests/ai/ast/test_treesitter_engine.py` +- [x] 1.2 Replace the `rglob` loop for each extension with one `os.scandir` walk that keeps the order of `Path.rglob` and does not go into an ignored folder + - Verification: `$ uv run devops ci test tests/ai/ast/test_treesitter_engine.py` + +## 2. Search a body only for the names that it holds (refactor that keeps behavior) + +- [x] 2.1 Add a test: a body that holds the name of a function, but does not call it, links nothing +- [x] 2.2 Test that the body holds the name before the call regex runs + - Verification: `$ uv run devops ci test tests/ai/ast/test_treesitter_engine.py` + +## 3. Run the dry-run case on a small folder (test-only edit) + +- [x] 3.1 Give the dry-run case of `ai ast graph` the option `--dir src/devops_cli/ai/ast` + - Verification: `$ uv run devops ci test tests/commands/test_ai_local_dry_run.py` + +- Pending a person: review the diff in tuicr (tuicr -r origin/main..HEAD). diff --git a/openspec/specs/ast-support/spec.md b/openspec/specs/ast-support/spec.md index a052ce9518..696ce14268 100644 --- a/openspec/specs/ast-support/spec.md +++ b/openspec/specs/ast-support/spec.md @@ -25,3 +25,10 @@ The system SHALL parse Dockerfiles and extract symbols for build stages and FROM #### Scenario: Dockerfile emits stage and FROM image symbols - **WHEN** the AST engine parses a Dockerfile with FROM instructions - **THEN** it emits symbols for each stage alias and base image specification + +### Requirement: The code graph walk skips each ignored folder +`devops ai ast graph` SHALL list the files of its folder in one walk. The walk SHALL NOT list `.git`, a folder that git ignores, or a folder in one of them. + +#### Scenario: A folder that .gitignore names +- **WHEN** the graph is built for a folder that holds `.git`, a `.gitignore` that names `vendor/`, a Python file in `vendor/pkg/` and a Python file at the top +- **THEN** the walk lists only the top folder, and the graph indexes only the file at the top diff --git a/src/devops_cli/ai/ast/graph.py b/src/devops_cli/ai/ast/graph.py index d0167d4336..73fdaba8e5 100644 --- a/src/devops_cli/ai/ast/graph.py +++ b/src/devops_cli/ai/ast/graph.py @@ -2,6 +2,8 @@ from __future__ import annotations +import logging +import os import re from pathlib import Path @@ -9,28 +11,67 @@ from devops_cli.ai.ast.models import CodeGraph, CodeGraphEdge, PolyglotFileMap, PolyglotSymbol from devops_cli.core.repo import find_worktree_root, is_ignored_by_git +logger = logging.getLogger(__name__) + def _is_excluded(path: Path, repo_root: Path) -> bool: """Whether `path` is left out of the graph: a symlink, or ignored by `repo_root`'s rules.""" return path.is_symlink() or is_ignored_by_git(repo_root, path) -def _collect_target_files(root_dir: Path, max_files: int) -> list[Path]: +def _list_folder(folder: Path, repo_root: Path) -> tuple[list[Path], list[Path]]: + """Return the files of `folder` and its subfolders that git does not ignore, as listed.""" files: list[Path] = [] + subfolders: list[Path] = [] + try: + with os.scandir(folder) as entries: + for entry in entries: + path = folder / entry.name + if not entry.is_dir(follow_symlinks=False): + files.append(path) + elif not is_ignored_by_git(repo_root, path, is_dir=True): + subfolders.append(path) + except OSError as exc: + # `Path.rglob` also went past a folder that it could not list. + logger.debug("Cannot list %s for the code graph: %s", folder, exc) + return files, subfolders + + +def _walk_files(root_dir: Path, repo_root: Path) -> list[Path]: + """List the files under `root_dir` once, and skip each folder that git ignores, whole. + + A walk per extension also went into `.venv` and the other ignored folders, which took + most of a build. The order is the order of `Path.rglob`, so `max_files` keeps the same + files: each subfolder of a folder gives its files in turn, then the walk goes into the + last subfolder first. + """ + files, subfolders = _list_folder(root_dir, repo_root) + pending = [subfolders] + while pending: + for folder in pending.pop(): + folder_files, folder_subfolders = _list_folder(folder, repo_root) + files.extend(folder_files) + pending.append(folder_subfolders) + return files + + +def _collect_target_files(root_dir: Path, max_files: int) -> list[Path]: repo_root = find_worktree_root(root_dir) - for ext in sorted(EXT_TO_LANG.keys()): - for candidate in root_dir.rglob(f"*{ext}"): - if not _is_excluded(candidate, repo_root): - files.append(candidate) - if len(files) >= max_files: - return files - for pattern in ("Dockerfile*", "Containerfile*"): - for candidate in root_dir.rglob(pattern): - if candidate.is_file() and not _is_excluded(candidate, repo_root): - if candidate not in files: - files.append(candidate) + walked = _walk_files(root_dir, repo_root) + candidates = [path for ext in sorted(EXT_TO_LANG) for path in walked if path.name.endswith(ext)] + candidates.extend( + path + for path in walked + if path.name.startswith(("Dockerfile", "Containerfile")) + and path.is_file() + and path not in candidates + ) + files: list[Path] = [] + for candidate in candidates: + if not _is_excluded(candidate, repo_root): + files.append(candidate) if len(files) >= max_files: - return files + break return files @@ -53,7 +94,10 @@ def _extract_symbol_body(sym: PolyglotSymbol, file_lines: list[str]) -> str: def _is_call_in_body(target_name: str, body: str) -> bool: - return bool(re.search(rf"\b{re.escape(target_name)}\s*\(", body)) + # The call pattern holds the name as written, so a body without the name cannot match it. + # The substring test skips the regex for almost every pair; one compile per pair missed + # the `re` cache and took most of a build. + return target_name in body and bool(re.search(rf"\b{re.escape(target_name)}\s*\(", body)) def _link_call_edges( diff --git a/tests/ai/ast/test_treesitter_engine.py b/tests/ai/ast/test_treesitter_engine.py index f68f1d3b2a..beb113848a 100644 --- a/tests/ai/ast/test_treesitter_engine.py +++ b/tests/ai/ast/test_treesitter_engine.py @@ -2,7 +2,9 @@ from __future__ import annotations +import os from pathlib import Path +from typing import Any import pytest from tree_sitter import QueryError @@ -322,6 +324,40 @@ def test_code_graph_links_a_call_and_skips_a_file_it_cannot_read(tmp_path: Path) ) +def test_code_graph_links_no_name_that_a_body_holds_but_does_not_call(tmp_path: Path) -> None: + """Verify a body that holds the name of another function, but does not call it, links + nothing: only a body that holds the name is searched for the call (#4662).""" + source = tmp_path / "calc.py" + source.write_text("def add(x, y):\n return x + y\n\n\ndef total(x):\n return [add, x]\n") + + assert CodeGraphBuilder(root_dir=tmp_path).build().edges == [] + + +def test_code_graph_lists_no_ignored_folder( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """Verify the code graph walk lists no folder that git ignores, nor `.git`: a walk into a + virtual environment took most of a build of this repository (#4662).""" + repo = tmp_path / "repo" + (repo / ".git").mkdir(parents=True) + (repo / ".gitignore").write_text("vendor/\n", encoding="utf-8") + (repo / "vendor" / "pkg").mkdir(parents=True) + (repo / "vendor" / "pkg" / "lib.py").write_text("def lib():\n return 1\n") + (repo / "app.py").write_text("def app():\n return 2\n") + listed: list[Path] = [] + real_scandir = os.scandir + + def recording_scandir(path: str = ".") -> Any: + listed.append(Path(path)) + return real_scandir(path) + + monkeypatch.setattr(os, "scandir", recording_scandir) + + files = CodeGraphBuilder(root_dir=repo).build().files + + assert ([Path(file).name for file in files], sorted(set(listed))) == (["app.py"], [repo]) + + def test_repomap_multilingual(tmp_path: Path) -> None: """Verify repomap with multilingual=True indexes polyglot files.""" (tmp_path / "main.py").write_text("def py_main(): pass\n") diff --git a/tests/commands/test_ai_local_dry_run.py b/tests/commands/test_ai_local_dry_run.py index c787196666..ce1f27d53f 100644 --- a/tests/commands/test_ai_local_dry_run.py +++ b/tests/commands/test_ai_local_dry_run.py @@ -53,7 +53,11 @@ LOCAL_AI_COMMANDS: list[tuple[str, Any, list[str]]] = [ ("ai", ai_main, ["--dry-run", "ai", "--help"]), - ("ai ast graph", ast_graph_cmd, ["--dry-run", "ai", "ast", "graph"]), + ( + "ai ast graph", + ast_graph_cmd, + ["--dry-run", "ai", "ast", "graph", "--dir", "src/devops_cli/ai/ast"], + ), ("ai ast parse", ast_parse_cmd, ["--dry-run", "ai", "ast", "parse", "src/devops_cli/main.py"]), ("ai audit-library-usage", audit_library_usage_cmd, ["--dry-run", "ai", "audit-library-usage"]), ("ai bundle-models", bundle_models, ["--dry-run", "ai", "bundle-models"]),