Skip to content

HOTFIX: graceful fallback when tree-sitter-typescript not installed#281

Merged
DevanshuNEU merged 2 commits into
OpenCodeIntel:mainfrom
DevanshuNEU:fix/graceful-ts-parser-import
Mar 6, 2026
Merged

HOTFIX: graceful fallback when tree-sitter-typescript not installed#281
DevanshuNEU merged 2 commits into
OpenCodeIntel:mainfrom
DevanshuNEU:fix/graceful-ts-parser-import

Conversation

@DevanshuNEU

@DevanshuNEU DevanshuNEU commented Mar 6, 2026

Copy link
Copy Markdown
Collaborator

PRODUCTION DOWN

Backend crashes on startup because import tree_sitter_typescript fails if the package isn't installed. Since dependency_analyzer.py is imported at app init via dependencies.py, this takes down the entire API.

Fix

try:
    import tree_sitter_typescript as tstypescript
    _HAS_TS_PARSER = True
except ImportError:
    _HAS_TS_PARSER = False

Falls back to JS parser (old behavior) if TS parser unavailable. App starts regardless. Logs a warning so we know when fallback is active.

Impact

  • When TS parser IS installed: uses proper TS/TSX grammars (better parsing)
  • When TS parser NOT installed: falls back to JS parser (still works, just has_error on complex TS)
  • App NEVER crashes from missing parser package

1 file, +19 -6 lines. All 28 dependency analyzer tests pass.

Summary by CodeRabbit

  • Bug Fixes

    • Improved robustness: the dependency analyzer now falls back to JavaScript parsing when the TypeScript parser is unavailable and logs a warning, preventing failures in environments without the TS parser.
  • Tests

    • Added tests covering parser-availability behavior and confirming import detection still works when falling back.
  • Chores

    • Initialization now reports parser availability in startup logs.

…duction fix)

The backend crashes on startup if tree-sitter-typescript is not installed
because dependency_analyzer.py is imported at app init via dependencies.py.

Fix: try/except around the import, fall back to JS parser (old behavior)
if the TS parser package isn't available. App starts regardless.

When tree-sitter-typescript IS installed, uses the proper TS/TSX parsers.
When it's NOT installed, logs a warning and uses JS parser as fallback.

This prevents Railway deploy failures from taking down the entire API.
@vercel

vercel Bot commented Mar 6, 2026

Copy link
Copy Markdown

@DevanshuNEU is attempting to deploy a commit to the Dev's projects Team on Vercel.

A member of the Team first needs to authorize it.

@coderabbitai

coderabbitai Bot commented Mar 6, 2026

Copy link
Copy Markdown
📝 Walkthrough

Walkthrough

The change adds a guarded import for the TypeScript parser and a runtime flag (has_ts_parser) in DependencyAnalyzer; when the TS parser is missing, the analyzer falls back to the JavaScript parser for TS/TSX files and logs a warning. Tests were added to assert the flag and fallback behavior.

Changes

Cohort / File(s) Summary
Parser Initialization with Fallback
backend/services/dependency_analyzer.py
Add guarded import _HAS_TS_PARSER; expose has_ts_parser on DependencyAnalyzer; initialize js_lang and conditionally set ts_lang/tsx_lang to TS parsers or fallback to js_lang; update parsers mapping and log TS parser availability/warning.
Tests for TS parser behavior
backend/tests/test_dependency_analyzer.py
Add tests: test_has_ts_parser_flag asserts has_ts_parser is True; test_fallback_when_ts_parser_missing patches _HAS_TS_PARSER False, asserts has_ts_parser is False and that dependency extraction for a .ts file falls back to JS parser and still finds imports.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant DependencyAnalyzer as DA
    participant JSParser as JS (tree-sitter-javascript)
    participant TSParser as TS (tree-sitter-typescript)

    rect rgba(200,200,255,0.5)
    Client->>DA: analyze_file_dependencies(file.ts)
    DA->>DA: check _HAS_TS_PARSER / has_ts_parser
    alt has_ts_parser == true
        DA->>TSParser: use TS parser to parse file.ts
        TSParser-->>DA: AST (imports)
    else has_ts_parser == false
        DA->>JSParser: fallback to JS parser to parse file.ts
        JSParser-->>DA: AST (imports)
    end
    DA-->>Client: return dependency list
    end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

Poem

🐰 A parser guard upon my back I wear,
If TypeScript hides, JavaScript will care,
I hop through imports, fallback in tow,
Finding paths where TS winds cannot go. ✨

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 60.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'HOTFIX: graceful fallback when tree-sitter-typescript not installed' directly and clearly summarizes the main change: implementing a graceful fallback mechanism when the tree-sitter-typescript package is unavailable, preventing app crashes on startup.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

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 and usage tips.

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

Actionable comments posted: 1

🧹 Nitpick comments (2)
backend/services/dependency_analyzer.py (2)

31-42: Surface fallback mode to callers, not just startup logs.

When _HAS_TS_PARSER is false, .ts and .tsx files are still reported as typescript / tsx even though they were parsed with the JS grammar. Since backend/dependencies.py:21-27 instantiates this singleton eagerly, downstream consumers have no structured way to detect that those dependency graphs are best-effort. Exposing a has_ts_parser / parser_mode flag on the analyzer and in analysis results would make this degradation explicit.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@backend/services/dependency_analyzer.py` around lines 31 - 42, The analyzer
currently hides that TypeScript files may be parsed with the JS grammar
(controlled by _HAS_TS_PARSER) — add a clear attribute on the DependencyAnalyzer
(e.g., self.has_ts_parser or self.parser_mode = 'ts'|'js-fallback') set where
self.parsers is initialized and logged, and propagate that flag into all
analysis results/return objects so downstream consumers (including the
eagerly-instantiated singleton in backend/dependencies.py) can detect
best-effort TS parsing; update the DependencyAnalyzer constructor to set the
flag based on _HAS_TS_PARSER and ensure analysis methods include it in their
returned result dict/objects.

26-34: Add a regression test for the missing-parser path.

This hotfix changes startup behavior, but the referenced tests do not appear to exercise it: backend/tests/test_dependency_analyzer.py:84-105 only checks parser presence/object identity, and backend/tests/test_dependency_analyzer.py:142-166 cover the “TS parser installed” path. Please add a test that forces the tree_sitter_typescript import to fail, asserts initialization does not raise, and verifies the warning/fallback behavior.

If helpful, I can draft the monkeypatch-based test case.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@backend/services/dependency_analyzer.py` around lines 26 - 34, Add a
regression test that simulates the missing tree-sitter-typescript import and
verifies fallback behavior: use monkeypatch to make the tree_sitter_typescript
import fail (or set backend.services.dependency_analyzer._HAS_TS_PARSER = False)
before importing or reloading backend.services.dependency_analyzer, then assert
import/initialization does not raise, assert logger.warning was called with a
message about falling back, and assert that ts_lang and tsx_lang reference the
same object as js_lang (i.e. ts_lang == js_lang and tsx_lang == js_lang).
Reference symbols: _HAS_TS_PARSER, js_lang, ts_lang, tsx_lang, and
logger.warning in backend.services.dependency_analyzer.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@backend/services/dependency_analyzer.py`:
- Around line 12-16: The import block that sets _HAS_TS_PARSER should only
swallow ModuleNotFoundError for the specific package name to avoid hiding
runtime import errors: change the except ImportError to except
ModuleNotFoundError and ensure it only applies to the attempted import of
tree_sitter_typescript (symbol: tree_sitter_typescript) so real initialization
errors still surface; update the initialization logic that sets _HAS_TS_PARSER
accordingly. Also add a unit test covering the fallback path used when
_HAS_TS_PARSER is False (the JS fallback path referenced in the file) and update
or add a test case for test_ts_parser_is_not_js to assert behavior when the
TypeScript parser package is missing. Ensure tests explicitly simulate
ModuleNotFoundError for tree_sitter_typescript rather than generic ImportError.

---

Nitpick comments:
In `@backend/services/dependency_analyzer.py`:
- Around line 31-42: The analyzer currently hides that TypeScript files may be
parsed with the JS grammar (controlled by _HAS_TS_PARSER) — add a clear
attribute on the DependencyAnalyzer (e.g., self.has_ts_parser or
self.parser_mode = 'ts'|'js-fallback') set where self.parsers is initialized and
logged, and propagate that flag into all analysis results/return objects so
downstream consumers (including the eagerly-instantiated singleton in
backend/dependencies.py) can detect best-effort TS parsing; update the
DependencyAnalyzer constructor to set the flag based on _HAS_TS_PARSER and
ensure analysis methods include it in their returned result dict/objects.
- Around line 26-34: Add a regression test that simulates the missing
tree-sitter-typescript import and verifies fallback behavior: use monkeypatch to
make the tree_sitter_typescript import fail (or set
backend.services.dependency_analyzer._HAS_TS_PARSER = False) before importing or
reloading backend.services.dependency_analyzer, then assert
import/initialization does not raise, assert logger.warning was called with a
message about falling back, and assert that ts_lang and tsx_lang reference the
same object as js_lang (i.e. ts_lang == js_lang and tsx_lang == js_lang).
Reference symbols: _HAS_TS_PARSER, js_lang, ts_lang, tsx_lang, and
logger.warning in backend.services.dependency_analyzer.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 7d82bbe0-8ccd-4de2-8454-4b37916fe095

📥 Commits

Reviewing files that changed from the base of the PR and between 36a235a and 71d517e.

📒 Files selected for processing (1)
  • backend/services/dependency_analyzer.py

Comment thread backend/services/dependency_analyzer.py
- except ImportError -> except ModuleNotFoundError (won't swallow
  real init errors from an installed-but-broken package)
- Added self.has_ts_parser attribute for downstream consumers
- Added test_fallback_when_ts_parser_missing: monkeypatches
  _HAS_TS_PARSER=False, verifies init succeeds, flag is False,
  and JS fallback still parses TS imports correctly
@vercel

vercel Bot commented Mar 6, 2026

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

1 Skipped Deployment
Project Deployment Actions Updated (UTC)
opencodeintel Ignored Ignored Preview Mar 6, 2026 8:54pm

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

Actionable comments posted: 2

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@backend/tests/test_dependency_analyzer.py`:
- Around line 106-107: The test hard-codes the expectation that
analyzer.has_ts_parser is True which fails when tree_sitter_typescript is
absent; update the test_has_ts_parser_flag assertion to compare
analyzer.has_ts_parser against the runtime-determined flag (e.g., use the actual
module/utility or fixture value that indicates TypeScript parser availability)
instead of asserting True so the test reflects the environment's parser
availability.
- Around line 106-121: Add missing type hints to the two test functions:
annotate test_has_ts_parser_flag(self, analyzer) as taking the appropriate
fixture types and returning None, and annotate
test_fallback_when_ts_parser_missing(self, monkeypatch, tmp_path) with
monkeypatch: pytest.MonkeyPatch, tmp_path: pathlib.Path (or Path) and -> None;
update the signature names in the file for test_has_ts_parser_flag and
test_fallback_when_ts_parser_missing to include these parameter types and a ->
None return, and add any needed imports (pytest.MonkeyPatch and Path) at the top
of the test file so the type annotations resolve, leaving all logic
(DependencyAnalyzer, _HAS_TS_PARSER monkeypatching, analyze_file_dependencies)
unchanged.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 7383f1d2-e4b7-46ff-ac93-7efee76a0123

📥 Commits

Reviewing files that changed from the base of the PR and between 71d517e and 603cfcf.

📒 Files selected for processing (2)
  • backend/services/dependency_analyzer.py
  • backend/tests/test_dependency_analyzer.py
🚧 Files skipped from review as they are similar to previous changes (1)
  • backend/services/dependency_analyzer.py

Comment thread backend/tests/test_dependency_analyzer.py
Comment thread backend/tests/test_dependency_analyzer.py
@DevanshuNEU DevanshuNEU merged commit 4f93099 into OpenCodeIntel:main Mar 6, 2026
7 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant