Skip to content

Conversation

@d-chambers
Copy link
Contributor

@d-chambers d-chambers commented Aug 23, 2025

Description

This PR fixes issue #508 by making the logic for reading the index_map file more robust to corrupt files.

Checklist

I have (if applicable):

  • referenced the GitHub issue this PR closes.
  • documented the new feature with docstrings or appropriate doc page.
  • included a test. See testing guidelines.
  • your name has been added to the contributors page (docs/contributors.md).
  • added the "ready_for_review" tag once the PR is ready to be reviewed.

Summary by CodeRabbit

  • New Features

    • None.
  • Bug Fixes

    • Prevent crashes when an index cache is corrupted by ignoring and removing the bad cache so indexing continues.
    • Preserve existing behavior for valid caches.
  • Tests

    • Added tests to verify corrupted index caches are detected and cleaned up.
    • Fixed a test name typo for clarity.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Aug 23, 2025

Walkthrough

Hardened cache loading in dascore/io/indexer.py: _get_index_map initializes an empty dict, attempts to load a JSON cache inside try/except, deletes the cache file on OSError or json.JSONDecodeError, and returns {} when unreadable or missing. Tests add a corrupted-cache fixture and a validation test; a test name typo is fixed.

Changes

Cohort / File(s) Summary
Indexer cache handling
dascore/io/indexer.py
_get_index_map initializes out = {}, wraps json.load in try/except, deletes corrupted cache on OSError/json.JSONDecodeError, and returns {} when cache is missing or unreadable; no public API changes.
Tests: corrupted cache fixture & typo fix
tests/test_io/test_indexer.py
Adds directory_indexer_bad_cache fixture that writes invalid JSON to a cache file; adds test_corrupt_cache to assert corrupted cache is removed and indexing proceeds; renames test_new_version_warngstest_new_version_warnings.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  participant C as Caller
  participant DI as DirectoryIndexer
  participant FS as Filesystem
  participant JS as JSON

  C->>DI: _get_index_map(path)
  DI->>FS: check if cache file exists
  alt cache exists
    DI->>FS: open cache file
    DI->>JS: json.load(file)
    alt load succeeds
      JS-->>DI: index_map (dict)
      DI-->>C: return index_map
    else OSError / JSONDecodeError
      JS--x DI: error
      DI->>FS: delete corrupted cache file
      DI-->>C: return {}
    end
  else no cache
    DI-->>C: return {}
  end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Poem

I nibbled on bytes in a carrot-shaped cache,
Found a sour crumb—oh dear, a JSON crash!
Snip-snap, I tidied the file away,
Fresh fields of dicts for a brand-new day.
Thump-thump, tests cheer with fluffy delight. 🥕✨

Tip

🔌 Remote MCP (Model Context Protocol) integration is now available!

Pro plan users can now connect to remote MCP servers from the Integrations page. Connect with popular remote MCPs such as Notion and Linear to add more context to your reviews and chats.


📜 Recent review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 04050f8 and bdcbcdf.

📒 Files selected for processing (1)
  • dascore/io/indexer.py (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • dascore/io/indexer.py
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (15)
  • GitHub Check: test_code_min_deps (macos-latest, 3.12)
  • GitHub Check: test_code_min_deps (windows-latest, 3.12)
  • GitHub Check: test_code (ubuntu-latest, 3.11)
  • GitHub Check: test_code_min_deps (macos-latest, 3.13)
  • GitHub Check: test_code_min_deps (windows-latest, 3.13)
  • GitHub Check: test_code_min_deps (ubuntu-latest, 3.13)
  • GitHub Check: test_code_min_deps (ubuntu-latest, 3.12)
  • GitHub Check: test_code (ubuntu-latest, 3.10)
  • GitHub Check: test_code (windows-latest, 3.11)
  • GitHub Check: test_code (macos-latest, 3.11)
  • GitHub Check: test_code (windows-latest, 3.10)
  • GitHub Check: test_code (macos-latest, 3.12)
  • GitHub Check: test_code (windows-latest, 3.12)
  • GitHub Check: test_code (ubuntu-latest, 3.12)
  • GitHub Check: test_code (macos-latest, 3.10)
✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch fix_508

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
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR/Issue comments)

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

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@codecov
Copy link

codecov bot commented Aug 23, 2025

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 99.87%. Comparing base (72c7878) to head (bdcbcdf).
⚠️ Report is 1 commits behind head on master.

Additional details and impacted files
@@            Coverage Diff             @@
##           master     #517      +/-   ##
==========================================
+ Coverage   99.85%   99.87%   +0.02%     
==========================================
  Files         118      118              
  Lines        9724     9732       +8     
==========================================
+ Hits         9710     9720      +10     
+ Misses         14       12       -2     
Flag Coverage Δ
unittests 99.87% <100.00%> (+0.02%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

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)
tests/test_io/test_indexer.py (2)

78-91: Nit: fix docstring typos and use write_text for clarity.

Minor cleanups: “bd” → “bad”, add apostrophe in “doesn’t”, and prefer Path.write_text with explicit encoding.

-    def directory_indexer_bad_cache(self, tmp_path_factory):
-        """Create a subclass of indexer which has a bd index_map file."""
+    def directory_indexer_bad_cache(self, tmp_path_factory):
+        """Create a subclass of indexer with a bad index_map file."""
         path = tmp_path_factory.mktemp("corrupt_cache_test")
         cache_path = path / "corrupt_cache.json"
-
-        with cache_path.open("wt") as fi:
-            fi.write("{'bad': 'json'")
+        cache_path.write_text("{'bad': 'json'", encoding="utf-8")
 
         class SubIndexer(DirectoryIndexer):
             index_map_path = cache_path
 
         return SubIndexer

123-134: Great targeted test; consider asserting functional fallback as well.

This validates the corrupted cache is removed. As an optional enhancement, also assert that a subsequent update writes a new, valid cache (non-empty dict) to fully exercise the recovery path.

         assert directory_indexer_bad_cache.index_map_path.exists()
-        directory_indexer_bad_cache(path)
+        inst = directory_indexer_bad_cache(path)
         assert not directory_indexer_bad_cache.index_map_path.exists()
+        # Optional: trigger a write and ensure a valid cache is created.
+        inst.update()
+        assert directory_indexer_bad_cache.index_map_path.exists()
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 72c7878 and 04050f8.

📒 Files selected for processing (2)
  • dascore/io/indexer.py (1 hunks)
  • tests/test_io/test_indexer.py (3 hunks)
🧰 Additional context used
🧬 Code graph analysis (1)
tests/test_io/test_indexer.py (1)
dascore/io/indexer.py (1)
  • DirectoryIndexer (94-342)
🔇 Additional comments (1)
tests/test_io/test_indexer.py (1)

272-278: Rename fix looks good.

The corrected test name improves readability and discoverability.

Comment on lines 40 to 49
out = {}
if path.exists():
with path.open("r") as fi:
out = json.load(fi)
else:
out = {}
try:
with path.open("r") as fi:
out = json.load(fi)
# On rare occasions, the file can become corrupt; just delete so it
# gets regenerated. See #508.
except (OSError, json.JSONDecodeError):
os.remove(path)
return out
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Make cache-file recovery more robust (race-safe delete, type check, and explicit encoding).

Good defensive change. Two small hardening tweaks:

  • Wrap the delete in a suppress block (or use Path.unlink with missing_ok=True); concurrent readers/writers can race and raise FileNotFoundError/PermissionError.
  • Validate that the decoded JSON is a dict; if it’s a different valid JSON type (e.g., a list), downstream code assumes dict and may break.
  • Use an explicit UTF-8 encoding for portability.

Apply this diff:

-    if path.exists():
-        try:
-            with path.open("r") as fi:
-                out = json.load(fi)
-        # On rare occasions, the file can become corrupt; just delete so it
-        # gets regenerated. See #508.
-        except (OSError, json.JSONDecodeError):
-            os.remove(path)
+    if path.exists():
+        try:
+            with path.open("r", encoding="utf-8") as fi:
+                loaded = json.load(fi)
+            # Ensure expected structure.
+            if isinstance(loaded, dict):
+                out = loaded
+            else:
+                # Unexpected but valid JSON; clear so it can be regenerated.
+                from contextlib import suppress
+                with suppress(FileNotFoundError, PermissionError):
+                    path.unlink(missing_ok=True)
+        # On rare occasions, the file can become corrupt; just delete so it
+        # gets regenerated. See #508.
+        except (OSError, json.JSONDecodeError, UnicodeDecodeError):
+            from contextlib import suppress
+            with suppress(FileNotFoundError, PermissionError):
+                path.unlink(missing_ok=True)
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
out = {}
if path.exists():
with path.open("r") as fi:
out = json.load(fi)
else:
out = {}
try:
with path.open("r") as fi:
out = json.load(fi)
# On rare occasions, the file can become corrupt; just delete so it
# gets regenerated. See #508.
except (OSError, json.JSONDecodeError):
os.remove(path)
return out
out = {}
if path.exists():
try:
with path.open("r", encoding="utf-8") as fi:
loaded = json.load(fi)
# Ensure expected structure.
if isinstance(loaded, dict):
out = loaded
else:
# Unexpected but valid JSON; clear so it can be regenerated.
from contextlib import suppress
with suppress(FileNotFoundError, PermissionError):
path.unlink(missing_ok=True)
# On rare occasions, the file can become corrupt; just delete so it
# gets regenerated. See #508.
except (OSError, json.JSONDecodeError, UnicodeDecodeError):
from contextlib import suppress
with suppress(FileNotFoundError, PermissionError):
path.unlink(missing_ok=True)
return out
🤖 Prompt for AI Agents
In dascore/io/indexer.py around lines 40 to 49, make cache-file recovery
race-safe and more defensive: when opening the file use path.open("r",
encoding="utf-8") to explicitly decode as UTF-8; after json.load(fi) validate
that the result is a dict and if not replace with an empty dict; and when
removing the corrupt file wrap the remove/unlink in a suppress block (or use
path.unlink(missing_ok=True)) to ignore FileNotFoundError and PermissionError
from concurrent access so deletion won’t raise.

@d-chambers d-chambers merged commit a89ff7b into master Aug 23, 2025
20 checks passed
@d-chambers d-chambers deleted the fix_508 branch August 23, 2025 12:36
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.

2 participants