Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: chunk initial symlinks on re-ingest #882

Merged
merged 2 commits into from
Nov 14, 2024
Merged

Conversation

dreulavelle
Copy link
Member

@dreulavelle dreulavelle commented Nov 14, 2024

Pull Request Check List

Resolves: #issue-number-here

  • Added tests for changed code.
  • Updated documentation for changed code.

Description:

Summary by CodeRabbit

  • New Features

    • Enhanced database initialization process with chunked processing for improved responsiveness.
    • Partial commits implemented to reduce error impact during initialization.
  • Bug Fixes

    • Improved error handling and logging during the initialization phase.

Copy link
Contributor

coderabbitai bot commented Nov 14, 2024

Walkthrough

The changes in the pull request modify the Program class in src/program/program.py to implement a chunked processing approach for initializing the database from symlinks. Instead of processing all items in a single batch, items are now filtered into Movie and Show instances and processed in chunks of 100. This allows for partial commits to the database after each chunk, improving responsiveness and error handling during initialization. Logging messages have been adjusted to reflect this new processing method, while the overall control flow remains largely unchanged.

Changes

File Change Summary
src/program/program.py - Replaced single batch processing with chunked processing for items.
- Items are now processed in chunks of 100, with partial commits to the database.
- Improved error handling and logging for chunk processing.

Poem

In the land of code where rabbits play,
Chunks of data hop along the way.
With each small batch, we save the day,
Committing joyfully, come what may!
Hooray for progress, let’s cheer and sway! 🐇✨


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 2b0af33 and c0994f9.

📒 Files selected for processing (1)
  • src/program/program.py (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/program/program.py

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ 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.
    • Generate unit testing code for this file.
    • 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. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • 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 src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

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

Documentation and Community

  • 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.

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

🧹 Outside diff range and nitpick comments (6)
src/program/program.py (6)

400-402: Consider memory optimization for large libraries

Converting the entire generator to a list using items_list = [item for item in items] could consume significant memory for large libraries. Consider processing the generator in chunks directly.

-items_list = [item for item in items if isinstance(item, (Movie, Show))]
-total_items = len(items_list)
+items_list = []
+for item in items:
+    if isinstance(item, (Movie, Show)):
+        items_list.append(item)
+total_items = len(items_list)

407-415: Consider making chunk size configurable

The chunk size is hardcoded to 100 items. Consider making it configurable via environment variable or settings, similar to how workers are configured, to allow tuning based on system resources and library size.

-chunk_size = 100
+chunk_size = int(os.getenv("SYMLINK_CHUNK_SIZE", 100))

426-428: Improve duplicate symlink error message

The error message for duplicate symlinks could be more informative by including both the duplicate paths.

-errors.append(f"Duplicate symlink directory found for {item.log_string}")
+errors.append(f"Duplicate symlink directory found for {item.log_string} with IMDB ID: {item.imdb_id}")

434-438: Add retry mechanism for failed enhancements

Consider implementing a retry mechanism for items that fail enhancement, as temporary network issues could cause failures.

+from tenacity import retry, stop_after_attempt, wait_exponential

+@retry(stop=stop_after_attempt(3), wait=wait_exponential(multiplier=1, min=4, max=10))
 def _enhance_item(self, item: MediaItem) -> MediaItem | None:
     try:
         enhanced_item = next(self.services[TraktIndexer].run(item, log_msg=False))
         return enhanced_item
     except StopIteration:
         return None

Line range hint 454-465: Enhance error reporting with statistics

Consider adding error statistics to provide a better overview of the initialization process.

 if errors:
     logger.error("Errors encountered during initialization")
+    error_stats = {
+        "duplicate_symlinks": len([e for e in errors if "Duplicate symlink" in e]),
+        "duplicate_db": len([e for e in errors if "Duplicate item found in database" in e]),
+        "enhancement_failures": len([e for e in errors if "Failed to enhance" in e]),
+        "invalid_directories": len([e for e in errors if "not a valid directory" in e])
+    }
+    logger.error(f"Error statistics: {error_stats}")
     for error in errors:
         logger.error(error)

Line range hint 400-465: Add tests for chunked processing implementation

As mentioned in the PR description, tests are missing for these changes. Consider adding the following test cases:

  1. Test chunked processing with various chunk sizes
  2. Test duplicate handling
  3. Test error scenarios
  4. Test progress reporting

Would you like me to help create these test cases?

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 0a2c5a9 and 2b0af33.

📒 Files selected for processing (1)
  • src/program/program.py (2 hunks)

Comment on lines 451 to 454
# Commit after each chunk
session.commit()

progress.update(task, log="Finished Indexing Symlinks!")
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

Consider adding transaction rollback on errors

While committing after each chunk is good, consider adding explicit transaction rollback on errors to ensure data consistency.

-# Commit after each chunk
-session.commit()
+try:
+    # Commit after each chunk
+    session.commit()
+except Exception as e:
+    session.rollback()
+    logger.error(f"Failed to commit chunk: {e}")
+    errors.append(f"Failed to commit chunk: {e}")

Committable suggestion skipped: line range outside the PR's diff.

@dreulavelle
Copy link
Member Author

I cant test the rollback part as I dont have a way to force it to break 🤔

But I tested this on my 30k item library and it finished within 1 minute. 🥳

@dreulavelle dreulavelle merged commit 21cd393 into main Nov 14, 2024
2 checks passed
@dreulavelle dreulavelle deleted the fix/chunk_symlink_db branch November 14, 2024 22:12
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