Skip to content

feat(ibis): override query cache #1138

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

Merged
merged 8 commits into from
Apr 9, 2025

Conversation

douenergy
Copy link
Contributor

@douenergy douenergy commented Apr 8, 2025

  • Add creation timestamp as part of the query cache file name
  • When cache hit occurs, also return the cache creation timestamp
  • Add an override parameter so that when cache is enabled, you can still force a query to the data source and then cache the result
  • By default, the override parameter is set to false

Summary by CodeRabbit

  • New Features

    • Introduced an option to bypass cached query results using an override parameter, providing greater control over data freshness.
    • Enhanced responses with additional headers that indicate cache creation timestamps and when an override is applied.
    • Improved overall cache management to ensure more consistent retrieval of up-to-date query results.
  • Tests

    • Added validations to ensure the new cache override functionality and response metadata work as expected.
    • Expanded testing coverage for cache behavior, particularly focusing on scenarios involving cache overrides.

Copy link

coderabbitai bot commented Apr 8, 2025

Walkthrough

The changes enhance the caching functionality for query processing. A new method is introduced to extract timestamps from cache files, and the cache file naming logic is updated to handle missing files by incorporating a Unix timestamp. Additionally, a new parameter is added to both v2 and v3 query endpoints to allow overriding the cache. This new flag alters the control flow to include or bypass cached data and updates response headers accordingly. Tests have been expanded to validate both the cache override and the proper assignment of header values.

Changes

File(s) Change Summary
ibis-server/app/query_cache/__init__.py Added get_cache_file_timestamp method in QueryCacheManager to retrieve cache file timestamps; updated _get_cache_file_name to return `str
ibis-server/app/routers/v2/connector.py
ibis-server/app/routers/v3/connector.py
Added a new override_cache parameter (default False) to query functions; modified logic to conditionally return cached results and add relevant headers (X-Cache-Create-At, X-Cache-Override, X-Cache-Override-At).
ibis-server/tests/routers/v2/connector/test_postgres.py
ibis-server/tests/routers/v3/connector/postgres/test_query.py
ibis-server/tests/routers/v3/connector/postgres/test_fallback_v2.py
Introduced new tests and assertions for the cache override functionality; verified header values and timestamps in responses.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant Router as QueryRouter (v2/v3)
    participant CacheManager

    Client->>Router: Sends query request (with override_cache flag)
    Router->>CacheManager: Retrieve cache file info (using get_cache_file_timestamp/_get_cache_file_name)
    alt Cache exists and override_cache is False
        CacheManager-->>Router: Returns cache file timestamp/filename
        Router->>Client: Return cached response with header X-Cache-Create-At
    else override_cache is True
        Router->>CacheManager: (Proceed with override logic)
        Router->>Client: Return fresh response with headers X-Cache-Override & X-Cache-Override-At
    end
Loading

Possibly related PRs

Suggested labels

dependencies

Suggested reviewers

  • goldmedal

Poem

I'm a little rabbit, hopping through the code,
With caches tamed and logic tuned, on a merry mode.
Override flags twinkle like stars in the night,
New timestamps shine, making everything right.
Hoppin' with CodeRabbit Inc.—coding delight! 🐇✨

✨ Finishing Touches
  • 📝 Generate Docstrings

🪧 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 generate docstrings to generate docstrings for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai plan to trigger planning for file edits and PR creation.
  • @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.

@github-actions github-actions bot added ibis python Pull requests that update Python code labels Apr 8, 2025
@douenergy douenergy marked this pull request as draft April 8, 2025 02:02
Copy link

@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: 2

🧹 Nitpick comments (1)
ibis-server/app/query_cache/__init__.py (1)

80-93: Consider consolidating duplicate file listing logic.

There's duplication between get_cache_file_timestamp and _get_cache_file_name - both iterate through all files looking for those that start with the cache key. This could be extracted into a helper method for better maintainability.

+ def _find_cache_file(self, cache_key: str):
+     """Find a cache file that starts with the given cache key."""
+     op = self._get_dal_operator()
+     for file in op.list("/"):
+         if file.path.startswith(cache_key):
+             return file.path
+     return None

def get_cache_file_timestamp(self, data_source: str, sql: str, info) -> int:
    cache_key = self._generate_cache_key(data_source, sql, info)
-   op = self._get_dal_operator()
-   for file in op.list("/"):
-       if file.path.startswith(cache_key):
+   file_path = self._find_cache_file(cache_key)
+   if file_path:
        # xxxxxxxxxxxxxx-1744016574.cache
        # we only care about the timestamp part
-       timestamp = int(file.path.split("-")[-1].split(".")[0])
+       timestamp = int(file_path.split("-")[-1].split(".")[0])
        return timestamp

    return None

def _get_cache_file_name(self, cache_key: str) -> str | None:
-   op = self._get_dal_operator()
-   for file in op.list("/"):
-       if file.path.startswith(cache_key):
-           return file.path
+   existing_file = self._find_cache_file(cache_key)
+   if existing_file:
+       return existing_file

    # If no cache file found, create a new one
    # ...rest of method unchanged
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between f0f8c00 and 169000a.

📒 Files selected for processing (5)
  • ibis-server/app/query_cache/__init__.py (3 hunks)
  • ibis-server/app/routers/v2/connector.py (2 hunks)
  • ibis-server/app/routers/v3/connector.py (3 hunks)
  • ibis-server/tests/routers/v2/connector/test_postgres.py (2 hunks)
  • ibis-server/tests/routers/v3/connector/postgres/test_query.py (1 hunks)
🧰 Additional context used
🧬 Code Definitions (1)
ibis-server/app/routers/v2/connector.py (4)
ibis-server/app/util.py (1)
  • to_json (23-27)
ibis-server/app/query_cache/__init__.py (1)
  • get_cache_file_timestamp (56-66)
ibis-server/app/routers/v3/connector.py (1)
  • query (36-111)
ibis-server/app/model/connector.py (5)
  • query (56-57)
  • query (72-73)
  • query (112-115)
  • query (143-181)
  • query (197-203)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: ci
🔇 Additional comments (15)
ibis-server/tests/routers/v3/connector/postgres/test_query.py (1)

166-166: Good addition of cache timestamp verification.

This assertion validates that the cache creation timestamp header is present and contains a value greater than April 7, 2025, aligning with the new cache timestamp functionality.

ibis-server/tests/routers/v2/connector/test_postgres.py (2)

195-195: Good addition of cache timestamp verification.

This assertion validates that the cache creation timestamp header is present and contains a value greater than April 7, 2025, aligning with the cache timestamp functionality.


204-231: Well-structured test for the cache override functionality.

This test case properly validates the cache override feature by:

  1. First making a request with caching enabled to populate the cache
  2. Then making a second request with both cache enabled and override enabled
  3. Verifying the appropriate headers are present in the response

The test ensures that the X-Cache-Override header is properly set to "true" and that the X-Cache-Override-At timestamp is valid.

ibis-server/app/routers/v2/connector.py (6)

46-46: Good addition of the override_cache parameter.

The override_cache parameter with default value of False maintains backward compatibility while adding the new functionality to bypass the cache when needed.


88-89: Simplified cache retrieval call.

This change removes unnecessary string conversion of data_source, making the code cleaner.


92-92: Enhanced cache condition logic.

The condition now correctly checks both cache_hit and override_cache, ensuring the cache is used only when appropriate.


96-100: Good addition of cache creation timestamp header.

The X-Cache-Create-At header provides valuable information about when the cache was created, enhancing client-side decision making.


104-112: Appropriate response handling for non-cached results.

The code now properly structures the response for non-cached results and adds the cache creation timestamp header if there was a cache hit, ensuring consistent header presence in both code paths.


119-125: Well-implemented cache override headers.

The addition of X-cache-override and X-cache-override-at headers provides clear indication to clients when the cache has been bypassed and when the new cache was created.

ibis-server/app/routers/v3/connector.py (4)

41-41: Good addition of the override_cache parameter.

The override_cache parameter with default value of False maintains backward compatibility while adding the new functionality to bypass the cache when needed.


72-74: Simplified cache retrieval call.

This change removes unnecessary string conversion of data_source, making the code cleaner.


81-85: Good addition of cache creation timestamp header.

The X-Cache-Create-At header provides valuable information about when the cache was created, enhancing client-side decision making.


106-106: Proper parameter forwarding to v2 connector.

Correctly passes the override_cache parameter to the v2 connector's query method when falling back, ensuring consistent behavior across API versions.

ibis-server/app/query_cache/__init__.py (2)

2-2: Added time module import to support timestamp functionality.

The import is necessary for the new timestamp features added to the cache file naming and retrieval.


91-92: LGTM: The timestamp generation aligns with PR objectives.

The implementation correctly adds a Unix timestamp to the cache file name, which supports the PR objective of tracking when the cache was generated.

@douenergy douenergy marked this pull request as ready for review April 8, 2025 10:27
Copy link

@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

🧹 Nitpick comments (3)
ibis-server/tests/routers/v2/connector/test_postgres.py (1)

204-233: Good coverage for the cache override scenario.

The logic correctly ensures the second request overrides the existing cache and updates related headers. As a minor refinement, you might also confirm that the second response’s data matches the newly fetched result rather than the cached data, to fully validate the override.

ibis-server/app/routers/v3/connector.py (1)

41-41: Clarify documentation for the override_cache parameter.

Consider explicitly documenting in the function docstring or type hint usage the behavior of override_cache—that it ignores (and then refreshes) any existing cache to fetch fresh data from the source.

ibis-server/app/query_cache/__init__.py (1)

93-103: Deleting old cache files before creating new ones.

Removing previous cache files helps keep the cache directory clean and ensures only the latest file remains. However, if concurrency is possible, multiple requests could inadvertently remove each other’s cache. A more robust eviction strategy might be needed based on usage patterns and concurrency requirements.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 169000a and 2decaf4.

📒 Files selected for processing (6)
  • ibis-server/app/query_cache/__init__.py (4 hunks)
  • ibis-server/app/routers/v2/connector.py (2 hunks)
  • ibis-server/app/routers/v3/connector.py (3 hunks)
  • ibis-server/tests/routers/v2/connector/test_postgres.py (2 hunks)
  • ibis-server/tests/routers/v3/connector/postgres/test_fallback_v2.py (2 hunks)
  • ibis-server/tests/routers/v3/connector/postgres/test_query.py (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • ibis-server/app/routers/v2/connector.py
  • ibis-server/tests/routers/v3/connector/postgres/test_query.py
🧰 Additional context used
🧬 Code Definitions (3)
ibis-server/tests/routers/v3/connector/postgres/test_fallback_v2.py (4)
ibis-server/tests/routers/v3/connector/postgres/test_query.py (2)
  • test_query_with_cache_override (174-199)
  • manifest_str (96-97)
ibis-server/tests/routers/v2/connector/test_postgres.py (2)
  • test_query_with_cache_override (204-232)
  • manifest_str (106-107)
ibis-server/tests/conftest.py (1)
  • client (18-23)
ibis-server/tests/routers/v3/connector/postgres/test_model_substitute.py (1)
  • manifest_str (27-28)
ibis-server/tests/routers/v2/connector/test_postgres.py (3)
ibis-server/tests/routers/v2/connector/test_mssql.py (1)
  • manifest_str (72-73)
ibis-server/tests/routers/v2/test_relationship_valid.py (2)
  • manifest_str (61-62)
  • postgres (66-69)
ibis-server/tests/routers/v2/connector/test_local_file.py (1)
  • connection_info (85-89)
ibis-server/app/routers/v3/connector.py (3)
ibis-server/app/query_cache/__init__.py (1)
  • get_cache_file_timestamp (56-70)
ibis-server/app/routers/v2/connector.py (1)
  • query (41-140)
ibis-server/app/model/connector.py (5)
  • query (56-57)
  • query (72-73)
  • query (112-115)
  • query (143-181)
  • query (197-203)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: ci
🔇 Additional comments (9)
ibis-server/tests/routers/v2/connector/test_postgres.py (1)

195-195: Be cautious with hard-coded epoch checks.

This assertion relies on the system clock being beyond April 7, 2025. If your test runs in an environment where the date/time is behind that epoch, it may spuriously fail. Consider using relative time checks or mocking the time to ensure consistent test outcomes.

ibis-server/tests/routers/v3/connector/postgres/test_fallback_v2.py (2)

74-74: Revisit fixed timestamp comparison.

Validating the cache creation time against a fixed timestamp (April 7, 2025) might fail in environments where the local system time is older. Consider using a dynamic or mocked time strategy to avoid edge cases in CI or production tests.


83-109: Comprehensive override logic test.

This test properly verifies creation of the cache on the first request and the override step on the second request. It appears thorough, and the header checks confirm the override timestamp is strictly greater than the creation timestamp.

ibis-server/app/routers/v3/connector.py (2)

77-125: Validate concurrency handling for cache override.

Using match (cache_enable, cache_hit, override_cache) is a clean structure. However, concurrent overrides might lead to unexpected states (e.g., partial re-writes). Ensure your underlying filesystem logic or concurrency controls (locks, etc.) suitably handle multiple simultaneous overrides.


136-136: Fallback parameter forwarding looks correct.

Forwarding override_cache to v2 ensures consistent behavior across connector versions.

ibis-server/app/query_cache/__init__.py (4)

2-2: Import of time is appropriate.

No issues found; this is necessary for generating timestamps.


41-41: Potential concurrency race condition on cache file updates.

Switching to _set_cache_file_name ensures one file per query. However, if multiple clients set the cache for the same query simultaneously, they may step on one another. Consider verifying concurrency behavior or using atomic writes.


56-71: Timestamp extraction gracefully handles errors.

Catching IndexError and ValueError avoids crashes if the file name format is unexpected. This defensive approach is sound; no further concerns.


85-91: _get_cache_file_name logic effectively detects existing files.

This updated method first checks for an existing matching cache file and reuses it if found. It then creates a new cache file name if necessary. Overall approach is fine for single-writer scenarios.

Copy link
Contributor

@goldmedal goldmedal left a comment

Choose a reason for hiding this comment

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

Thanks @douenergy. It looks great 👍

@goldmedal goldmedal merged commit c1d19e8 into Canner:main Apr 9, 2025
4 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
ibis python Pull requests that update Python code
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants