Skip to content

Conversation

@maxi297
Copy link
Contributor

@maxi297 maxi297 commented Dec 6, 2024

Following the release of source-jira concurrent, we have seen some database table is locked issue on a connection.

History

source-jira:3.4.0
We have seen sqlite3.OperationalError: database table is locked here for the first time after enabling concurrency for source-jira. We had already seen similar issues (database is locked but I can't see references for database table is locked). This error was happening consistently for this sync.

source-jira:3.4.0-dev.1e489a955b
Trying to wrap the write in a failsafe manner, we were now seeing sqlite3.OperationalError: database table is locked: responses on reads.

class SkipFailureSQLiteDict(requests_cache.backends.sqlite.SQLiteDict):
    def _write(self, key: str, value: str) -> None:
        try:
            super()._write(key, value)  # type: ignore  # lib is not typed
        except Exception as exception:
            logger.warning(exception)

source-jira:3.4.0-dev.ba45526fa4
As part of this release, we've also wrapped the read. This caused the app to logs warnings likes WARN Error while retrieving item from cache: database table is locked: responses but did not crash because of that

source-jira:3.4.0-dev.657e80a526
At that point, we fix part of the memory issue. There were a lot of errors database table is locked but the connector was running longer because it would not consume the memory so fast

source-jira:3.4.0-dev.272b13a278
Blindly adding mode fast_save and wal to True. At this point, we don't see the error anymore.

Proposed solution

The sync that was generating the issues is now running and since there is >30 hours or I/O before it is done, it is annoying to just cancel it. I would have liked to test without fast_save because it seems to have some important drawback on consistency based on this, this and If the application running SQLite crashes, the data will be safe, but the database [might become corrupted](https://www.sqlite.org/howtocorrupt.html#cfgerr) if the operating system crashes or the computer loses power before that data has been written to the disk surface. in this description. In the last statement, I don't know what SQLite crashes means but my reasoning is the if one thread crashes, there are a couple of possible things that can happen:

  • sqlite is not corrupted so other threads can run
  • sqlite is corrupted but the other threads are resilient to it
  • sqlite is corrupted and it makes other threads crash as well so we restart the syncs

I'm fine with this level of risk.

If we still see some issues with database being locked, we can add the SkipFailureSQLiteDict implementation that was used to fix the customer's connection which would just ignore caching errors entirely.

Summary by CodeRabbit

  • New Features

    • Improved handling of SQLite cache for HTTP requests.
    • Enhanced error logging and handling for various response actions.
  • Refactor

    • Streamlined logic for determining SQLite path in the HTTP client.
    • Updated method for handling session requests.

These changes enhance the efficiency and reliability of the HTTP client, providing a smoother user experience.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Dec 6, 2024

Warning

Rate limit exceeded

@maxi297 has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 8 minutes and 21 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between 8faf59e and 82e7d97.

📝 Walkthrough
📝 Walkthrough
📝 Walkthrough

Walkthrough

The changes in this pull request focus on the HttpClient class within the airbyte_cdk/sources/streams/http/http_client.py file. Key modifications include a refactor of the _request_session method to streamline SQLite path handling and an update to the CachedLimiterSession instantiation to use Write-Ahead Logging mode. Additionally, the _handle_error_resolution method has been enhanced with improved error logging for various response actions, particularly regarding rate limiting. These adjustments aim to enhance cache handling and error management within the HTTP client.

Changes

File Path Change Summary
airbyte_cdk/sources/streams/http/http_client.py Refactored _request_session method for SQLite path handling; updated instantiation of CachedLimiterSession to use WAL mode; enhanced _handle_error_resolution method with improved logging and error handling for response actions.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant HttpClient
    participant Cache

    Client->>HttpClient: Make HTTP Request
    HttpClient->>Cache: Check SQLite Cache
    alt Cache Hit
        Cache-->>HttpClient: Return Cached Response
        HttpClient-->>Client: Return Response
    else Cache Miss
        HttpClient->>HttpClient: Create New Session
        HttpClient->>HttpClient: Send Request
        HttpClient->>HttpClient: Handle Response
        alt Error Occurs
            HttpClient->>HttpClient: Log Error
        else Success
            HttpClient->>Cache: Store Response in Cache
            HttpClient-->>Client: Return Response
        end
    end
Loading

What do you think about this diagram? Does it capture the flow accurately?


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:

‼️ IMPORTANT
Auto-reply has been disabled for this repository in the CodeRabbit settings. The CodeRabbit bot will not respond to your replies unless it is explicitly tagged.

  • 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: 0

🧹 Outside diff range and nitpick comments (1)
airbyte_cdk/sources/streams/http/http_client.py (1)

141-150: LGTM! The WAL mode implementation looks solid! 🎉

Great solution using WAL mode to prevent database locks! The implementation is clean and the comment explains the purpose well. Would you consider adding a brief comment about any potential limitations or side effects of WAL mode for future maintainers? For instance, WAL files cleanup strategy, concurrent access patterns, etc. wdyt?

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 59505ff and 09e855d.

📒 Files selected for processing (1)
  • airbyte_cdk/sources/streams/http/http_client.py (1 hunks)
🔇 Additional comments (2)
airbyte_cdk/sources/streams/http/http_client.py (2)

148-150: Verify other SQLite usage patterns in the codebase 🔍

The WAL mode implementation looks good! Should we verify that there aren't any other SQLite instances in the codebase that might need similar treatment?

✅ Verification successful

SQLite WAL mode implementation looks good! 👍

From the search results, I can see that SQLite usage is well-contained within the HTTP client caching mechanism. The WAL mode is consistently applied in the only place where SQLite is directly used (airbyte_cdk/sources/streams/http/http_client.py). The other mentions are just in dependency specifications and changelog entries.

The implementation follows good practices:

  • Uses WAL mode for preventing "database locked" errors
  • Keeps SQLite usage isolated to the caching mechanism
  • Maintains consistent naming pattern for cache files
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for other SQLite usage patterns
echo "Searching for SQLite related imports..."
rg "import.*sqlite" --type python

echo "Searching for SQLite configuration or initialization..."
rg "sqlite|SQLite" --type python -g "!test_*"

Length of output: 355


Script:

#!/bin/bash
# Let's try searching without specifying file type
echo "Searching for SQLite related imports..."
rg "import.*sqlite"

echo "\nSearching for SQLite configuration or initialization..."
rg "sqlite|SQLite" -g "!test_*"

echo "\nLooking for specific SQLite files..."
fd -e db -e sqlite -e sqlite3

Length of output: 6825


Line range hint 452-461: Consider tracking the temporary rate limit status printing as technical debt 📝

The current implementation using print() with flush=True works but might cause issues in the future. The TODO comment explains why this approach was chosen, but should we create a tracking issue to ensure we revisit this when the concurrent message repository is ready? I can help create one if you'd like!

Let's check if there are any existing issues tracking this:

@maxi297 maxi297 changed the title Reduce occurences of database table is locked errors fix(concurrent): Reduce occurrences of database table is locked errors Dec 6, 2024
@github-actions github-actions bot added the bug Something isn't working label Dec 6, 2024
Copy link
Contributor

@brianjlai brianjlai left a comment

Choose a reason for hiding this comment

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

thanks for the very detailed explanation.

I agree with your assessment on risk. Given this is just running on a container, if for some reasons it does get corrupted or there's an unexpected shut down, the worst that can happen is we need to start a new attempt. Doesn't seem like there are long term repercussion or data loss

@maxi297 maxi297 merged commit 6ab54c0 into main Dec 9, 2024
20 of 21 checks passed
@maxi297 maxi297 deleted the maxi297/reduce-database-table-is-locked-errors branch December 9, 2024 17:06
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants