Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
fix(ingestion): warn when a language query fails to compile (#2166) (#2177)
Rishabh Mishra6d797774df25
diff --git a/packages/core/src/repowise/core/ingestion/parser.py b/packages/core/src/repowise/core/ingestion/parser.pyindex a17212448..d08810e22 100644--- a/packages/core/src/repowise/core/ingestion/parser.py+++ b/packages/core/src/repowise/core/ingestion/parser.py@@ -743,20 +743,15 @@ def _cpp_export_macro_parent(node: Node, parent_names: dict[int, str]) -> str |@cache-def _load_compiled_query(lang: str, grammar_tag: str | None = None) -> object | None:- """Process-wide cache of compiled tree-sitter Query objects.+def _compile_query(lang: str, grammar_tag: str | None = None) -> tuple[object | None, str | None]:+ """Compile and return (Query, None) or (None, error_str).- Compiling `.scm` queries is non-trivial; in process-pool parsing each worker- would otherwise recompile per file. ``grammar_tag`` may differ from- ``lang`` when a language reuses another's grammar at a different- variant — e.g. ``.tsx`` files reuse ``typescript.scm`` but must bind- to the JSX-aware ``tsx`` grammar so React components don't drown in- ERROR nodes.+ Cached process-wide so preflight and parsing workers never recompile the same query."""grammar = grammar_tag or langlanguage = _get_language(grammar)if language is None:- return None+ return None, None# The spec names the query file, so a language can reuse another's# queries wholesale (svelte -> typescript.scm). Every other spec declares@@ -766,7 +761,7 @@ def _load_compiled_query(lang: str, grammar_tag: str | None = None) -> object |scm_path = QUERIES_DIR / scm_nameif not scm_path.exists():log.debug("No .scm query file found", language=lang, path=str(scm_path))- return None+ return None, Nonescm_text = scm_path.read_text(encoding="utf-8")# Grammar-variant-specific additions (e.g. JSX node captures that are@@ -779,10 +774,26 @@ def _load_compiled_query(lang: str, grammar_tag: str | None = None) -> object |try:from tree_sitter import Query # type: ignore[attr-defined]- return Query(language, scm_text)+ return Query(language, scm_text), Noneexcept Exception as exc:- log.warning("Failed to compile query", language=lang, error=str(exc))- return None+ return None, str(exc)+++@cache+def _load_compiled_query(lang: str, grammar_tag: str | None = None) -> object | None:+ """Process-wide cache of compiled tree-sitter Query objects.++ Compiling `.scm` queries is non-trivial; in process-pool parsing each worker+ would otherwise recompile per file. ``grammar_tag`` may differ from+ ``lang`` when a language reuses another's grammar at a different+ variant — e.g. ``.tsx`` files reuse ``typescript.scm`` but must bind+ to the JSX-aware ``tsx`` grammar so React components don't drown in+ ERROR nodes.+ """+ query, err = _compile_query(lang, grammar_tag)+ if err is not None:+ log.warning("Failed to compile query", language=lang, error=err)+ return query# Languages that intentionally have no AST parser. Derived from the@@ -897,6 +908,34 @@ def missing_grammar_languages(language_tags: Iterable[str]) -> list[str]:return sorted(missing)+def failed_query_languages(language_tags: Iterable[str]) -> list[tuple[str, str]]:+ """Of *language_tags*, those whose tree-sitter queries fail to compile.++ Scoped to what traversal discovered in the repo. Only checks languages with+ a registered LanguageConfig and query file. Best-effort and bounded.+ """+ failed: list[tuple[str, str]] = []+ seen: set[str] = set()++ for tag in language_tags:+ if tag in seen or tag not in LANGUAGE_CONFIGS:+ continue+ seen.add(tag)++ _, err = _compile_query(tag)+ if err is not None:+ failed.append((tag, err))+ continue++ # Check grammar variants if applicable (e.g. tsx for typescript)+ if tag == "typescript":+ _, tsx_err = _compile_query("typescript", grammar_tag="tsx")+ if tsx_err is not None:+ failed.append((tag, f"tsx variant: {tsx_err}"))++ return sorted(failed, key=lambda x: x[0])++def _get_language(tag: str) -> Language | None:global _LANGUAGE_REGISTRYif not _LANGUAGE_REGISTRY:diff --git a/packages/core/src/repowise/core/pipeline/phases/ingestion.py b/packages/core/src/repowise/core/pipeline/phases/ingestion.pyindex 2e825c6c6..f734dd587 100644--- a/packages/core/src/repowise/core/pipeline/phases/ingestion.py+++ b/packages/core/src/repowise/core/pipeline/phases/ingestion.py@@ -54,6 +54,37 @@ def _report_missing_grammars(stats: Any, progress: ProgressCallback | None) -> N)+def _report_query_compilation_failures(stats: Any, progress: ProgressCallback | None) -> None:+ """Name any languages whose tree-sitter queries failed to compile.++ Scoped to what traversal found. A query compilation failure (e.g. tree-sitter+ ABI mismatch or invalid query syntax) leaves files with zero symbols.+ Reporting it prominently tells the user why symbols are missing. Best-effort:+ a reporting failure must not stop an index.+ """+ if progress is None or stats is None:+ return+ try:+ lang_counts = getattr(stats, "lang_counts", None)+ if not lang_counts:+ return+ from repowise.core.ingestion.parser import failed_query_languages++ failed = failed_query_languages(lang_counts)+ if not failed:+ return+ for lang, err in failed:+ count = lang_counts.get(lang, 0)+ emit_warning(+ progress,+ f"Failed to compile tree-sitter queries for {lang} ({count:,} files): {err}. "+ f"Symbols for {lang} will not be extracted.",+ )+ except Exception:+ logger.debug("query_preflight_failed", exc_info=True)+ return++async def _timed_step(label: str,fn: Any,@@ -468,6 +499,7 @@ async def _run_ingestion(# carry no symbols, which is not something to find out from an empty# symbol list weeks later._report_missing_grammars(getattr(traverser, "stats", None), progress)+ _report_query_compilation_failures(getattr(traverser, "stats", None), progress)if progress:progress.on_phase_start("parse", len(file_infos))diff --git a/tests/unit/ingestion/test_query_preflight.py b/tests/unit/ingestion/test_query_preflight.pynew file mode 100644index 000000000..1868a3bca--- /dev/null+++ b/tests/unit/ingestion/test_query_preflight.py@@ -0,0 +1,183 @@+"""Query compilation failures should be warned loudly in preflight, not silently report 0 symbols.++When a tree-sitter query fails to compile (e.g. tree-sitter ABI/version mismatch,+invalid query syntax), ASTParser produces 0 symbols. The user needs an actionable+warning explaining why symbols are missing.+"""++from __future__ import annotations++from typing import ClassVar++import pytest++from repowise.core.ingestion.parser import (+ _compile_query,+ _load_compiled_query,+ failed_query_languages,+)+++def test_a_language_with_valid_query_is_not_reported() -> None:+ """Python's query compiles cleanly; it must not be reported as failed."""+ _compile_query.cache_clear()+ assert failed_query_languages(["python"]) == []+++def test_non_ast_languages_are_not_reported() -> None:+ """Non-code/data formats without AST configs are skipped."""+ _compile_query.cache_clear()+ assert failed_query_languages(["markdown", "json", "unknown", "text"]) == []+++def test_a_failing_query_compilation_is_reported(monkeypatch: pytest.MonkeyPatch) -> None:+ """If tree_sitter.Query raises an exception, failed_query_languages captures it."""+ import tree_sitter++ _compile_query.cache_clear()++ def _broken_query(language: object, source: str) -> object:+ raise ValueError("Invalid node type: fake_node")++ monkeypatch.setattr(tree_sitter, "Query", _broken_query)+ try:+ results = failed_query_languages(["python"])+ assert len(results) == 1+ lang, err = results[0]+ assert lang == "python"+ assert "Invalid node type: fake_node" in err+ finally:+ _compile_query.cache_clear()+++def test_failed_query_languages_deduplicates_and_sorts(monkeypatch: pytest.MonkeyPatch) -> None:+ """Duplicate tags are deduplicated and output is sorted by tag."""+ import tree_sitter++ _compile_query.cache_clear()++ def _broken_query(language: object, source: str) -> object:+ raise ValueError("Query syntax error")++ monkeypatch.setattr(tree_sitter, "Query", _broken_query)+ try:+ results = failed_query_languages(["python", "python"])+ assert len(results) == 1+ assert results[0][0] == "python"+ finally:+ _compile_query.cache_clear()+++def test_query_compilation_failure_is_reported_through_progress_channel(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """Preflight emits a user-facing warning containing file count and error message."""+ import tree_sitter++ from repowise.core.pipeline.phases.ingestion import _report_query_compilation_failures++ _compile_query.cache_clear()++ def _broken_query(language: object, source: str) -> object:+ raise ValueError("tree-sitter query compile error")++ monkeypatch.setattr(tree_sitter, "Query", _broken_query)++ class _Stats:+ lang_counts: ClassVar[dict] = {"python": 42}++ class _Progress:+ def __init__(self) -> None:+ self.messages: list[tuple[str, str]] = []++ def on_message(self, level: str, text: str) -> None:+ self.messages.append((level, text))++ progress = _Progress()+ try:+ _report_query_compilation_failures(_Stats(), progress)+ assert len(progress.messages) == 1+ level, text = progress.messages[0]+ assert level == "warning"+ assert "Failed to compile tree-sitter queries for python" in text+ assert "42 files" in text+ assert "tree-sitter query compile error" in text+ assert "Symbols for python will not be extracted" in text+ finally:+ _compile_query.cache_clear()+++def test_nothing_is_said_when_all_queries_compile_fine() -> None:+ """No warnings are emitted if all queries compile successfully."""+ from repowise.core.pipeline.phases.ingestion import _report_query_compilation_failures++ _compile_query.cache_clear()++ class _Stats:+ lang_counts: ClassVar[dict] = {"python": 10}++ class _Progress:+ def __init__(self) -> None:+ self.messages: list[tuple[str, str]] = []++ def on_message(self, level: str, text: str) -> None:+ self.messages.append((level, text))++ progress = _Progress()+ _report_query_compilation_failures(_Stats(), progress)++ assert progress.messages == []+++def test_query_preflight_never_breaks_an_index() -> None:+ """Best-effort: a reporting failure must not stop an indexing pipeline."""+ from repowise.core.pipeline.phases.ingestion import _report_query_compilation_failures++ class _Exploding:+ @property+ def lang_counts(self):+ raise RuntimeError("boom")++ class _Progress:+ def on_message(self, level: str, text: str) -> None:+ pass++ _report_query_compilation_failures(None, _Progress())+ _report_query_compilation_failures(_Exploding(), _Progress())+++def test_load_compiled_query_caches_compilation_and_warning(monkeypatch: pytest.MonkeyPatch) -> None:+ """_load_compiled_query must be cached process-wide to avoid duplicate warnings per file."""+ import tree_sitter++ from repowise.core.ingestion import parser++ _compile_query.cache_clear()+ _load_compiled_query.cache_clear()++ warning_calls: list[dict] = []++ def _broken_query(language: object, source: str) -> object:+ raise ValueError("Simulated compile failure")++ monkeypatch.setattr(tree_sitter, "Query", _broken_query)+ monkeypatch.setattr(+ parser.log, "warning", lambda msg, **kwargs: warning_calls.append({"msg": msg, **kwargs})+ )++ try:+ # First call: triggers compilation, returns None, logs warning+ res1 = _load_compiled_query("python")+ assert res1 is None+ assert len(warning_calls) == 1+ assert warning_calls[0]["msg"] == "Failed to compile query"+ assert warning_calls[0]["language"] == "python"++ # Second call: must be cached, return None without emitting duplicate warning+ res2 = _load_compiled_query("python")+ assert res2 is None+ assert len(warning_calls) == 1+ finally:+ _compile_query.cache_clear()+ _load_compiled_query.cache_clear()+