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

feat(AsyncRetriever): Allow for streams using AsyncRetriever and DatetimeBasedCursor to perform checkpointing #226

Open
wants to merge 1 commit into
base: main
Choose a base branch
from

Conversation

brianjlai
Copy link
Contributor

@brianjlai brianjlai commented Jan 17, 2025

What

Add the ability for streams that define an AsyncRetriever and a DatetimeBasedCursor to perform periodic checkpointing when the date time window of a stream slice is synced successfully.

This is needed to unblock source-amazon-seller-partner which supports incremental async jobs.

How

It's worth noting that this PR goes a bit in the opposite direction where we want to deprecate the existing DatetimeBasedCursor because now its more closely integrated into the AsyncRetriever stream slicing mechanism. However, due to the short time frame to deliver Amazon Seller Partner, trying to inject the ConcurrentCursor into the low-code AsyncJobPartitionRouter felt like the more difficult path.

The tradeoff in the short term here is that our Async + Incremental streams will run synchronously (worth noting that this was already the existing behavior based on how we construct the concurrent_declarative_source.py) So we incur a little bit of tech debt in exchange for simplicity to implement

Summary by CodeRabbit

  • New Features

    • Enhanced async retriever functionality with improved cursor management
    • Added support for more flexible stream state handling in async data processing
    • Introduced new cursor-related methods for better stream slice management
  • Improvements

    • Updated stream processing logic to handle different retriever types
    • Improved state tracking and record processing in async retrievers
  • Technical Enhancements

    • Added new methods for cursor and record tracking
    • Expanded support for datetime-based cursors in partition routing

@brianjlai brianjlai requested a review from maxi297 January 17, 2025 08:17
@github-actions github-actions bot added the enhancement New feature or request label Jan 17, 2025
Copy link
Contributor

coderabbitai bot commented Jan 17, 2025

📝 Walkthrough

Walkthrough

The pull request introduces enhancements to the Airbyte CDK's declarative source components, focusing on improving async retriever and partition router functionality. The changes primarily involve updating cursor management, adding support for AsyncRetriever, and introducing new methods for handling stream states and slices across multiple files in the declarative sources module.

Changes

File Change Summary
airbyte_cdk/sources/declarative/declarative_stream.py - Added AsyncRetriever import
- Modified get_cursor method to support both SimpleRetriever and AsyncRetriever
airbyte_cdk/sources/declarative/partition_routers/async_job_partition_router.py - Added imports for DatetimeBasedCursor and DeclarativeCursor
- Enhanced cursor management in __post_init__
- Added new cursor property method
airbyte_cdk/sources/declarative/retrievers/async_retriever.py - Added DeclarativeCursor import
- Updated state property with setter
- Added cursor property
- Modified read_records method
- Introduced _get_most_recent_record method

Sequence Diagram

sequenceDiagram
    participant AsyncRetriever
    participant StreamSlicer
    participant Cursor
    
    AsyncRetriever->>StreamSlicer: Get stream slice
    StreamSlicer-->>AsyncRetriever: Return stream slice
    AsyncRetriever->>Cursor: Observe cursor state
    AsyncRetriever->>AsyncRetriever: Process records
    AsyncRetriever->>Cursor: Update cursor state
Loading

Possibly related PRs

Suggested labels

async, cursor-management, source-refactoring

Suggested reviewers

  • maxi297
  • tolik0

Hey there! 👋 I noticed these changes look quite interesting. Would you like me to elaborate on any specific aspect of the modifications? The cursor management enhancements seem particularly intriguing. Wdyt? 🤔

Finishing Touches

  • 📝 Generate Docstrings (Beta)

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 generate docstrings to generate docstrings for this PR. (Beta)
  • @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

🧹 Nitpick comments (4)
airbyte_cdk/sources/declarative/partition_routers/async_job_partition_router.py (2)

40-43: Consider adding type hints for better code clarity

The type hint for self.stream_slicer in the condition would make the code more maintainable. What do you think about this change?

-        if isinstance(self.stream_slicer, DatetimeBasedCursor):
+        if isinstance(self.stream_slicer, DatetimeBasedCursor):  # type: StreamSlicer

45-47: Add docstring to the cursor property

Would you consider adding a docstring to explain the purpose and return type of this property? Something like:

    @property
    def cursor(self) -> Optional[DeclarativeCursor]:
+        """
+        Returns the cursor associated with this partition router if it exists.
+        
+        Returns:
+            Optional[DeclarativeCursor]: The cursor used for checkpointing, or None if not available.
+        """
        return self._cursor
airbyte_cdk/sources/declarative/retrievers/async_retriever.py (2)

88-113: Consider extracting cursor-related logic to improve readability

The read_records method has grown complex with the addition of cursor management. Would you consider extracting the cursor-related logic into a separate method for better maintainability? Something like:

+    def _handle_cursor_updates(
+        self,
+        stream_data: Optional[StreamData],
+        stream_slice: StreamSlice,
+        most_recent_record: Optional[Record],
+    ) -> Optional[Record]:
+        """Handle cursor updates for a single record."""
+        if self.cursor and stream_data:
+            self.cursor.observe(stream_slice, stream_data)
+            return self._get_most_recent_record(most_recent_record, stream_data, stream_slice)
+        return most_recent_record

     def read_records(
         self,
         records_schema: Mapping[str, Any],
         stream_slice: Optional[StreamSlice] = None,
     ) -> Iterable[StreamData]:
         _slice = stream_slice or StreamSlice(partition={}, cursor_slice={})
         stream_state: StreamState = self.state
         partition: AsyncPartition = self._validate_and_get_stream_slice_partition(stream_slice)
         records: Iterable[Mapping[str, Any]] = self.stream_slicer.fetch_records(partition)
         most_recent_record_from_slice = None
         
         for stream_data in self.record_selector.filter_and_transform(
             all_data=records,
             stream_state=stream_state,
             records_schema=records_schema,
             stream_slice=_slice,
         ):
-            if self.cursor and stream_data:
-                self.cursor.observe(_slice, stream_data)
-
-            most_recent_record_from_slice = self._get_most_recent_record(
-                most_recent_record_from_slice, stream_data, _slice
-            )
+            most_recent_record_from_slice = self._handle_cursor_updates(
+                stream_data, _slice, most_recent_record_from_slice
+            )
             yield stream_data

115-131: Add early return for optimization

In _get_most_recent_record, we could optimize the logic with an early return. What do you think about this change?

     def _get_most_recent_record(
         self,
         current_most_recent: Optional[Record],
         current_record: Optional[Record],
         stream_slice: StreamSlice,
     ) -> Optional[Record]:
+        if not self.cursor or not current_record:
+            return None
+        if not current_most_recent:
+            return current_record
+        return (
+            current_most_recent
+            if self.cursor.is_greater_than_or_equal(current_most_recent, current_record)
+            else current_record
+        )
-        if self.cursor and current_record:
-            if not current_most_recent:
-                return current_record
-            else:
-                return (
-                    current_most_recent
-                    if self.cursor.is_greater_than_or_equal(current_most_recent, current_record)
-                    else current_record
-                )
-        else:
-            return None
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between b5ed82c and 45aa98d.

📒 Files selected for processing (3)
  • airbyte_cdk/sources/declarative/declarative_stream.py (3 hunks)
  • airbyte_cdk/sources/declarative/partition_routers/async_job_partition_router.py (2 hunks)
  • airbyte_cdk/sources/declarative/retrievers/async_retriever.py (3 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (8)
  • GitHub Check: Check: 'source-pokeapi' (skip=false)
  • GitHub Check: Check: 'source-the-guardian-api' (skip=false)
  • GitHub Check: Check: 'source-shopify' (skip=false)
  • GitHub Check: Check: 'source-hardcoded-records' (skip=false)
  • GitHub Check: Pytest (All, Python 3.11, Ubuntu)
  • GitHub Check: Pytest (Fast)
  • GitHub Check: Pytest (All, Python 3.10, Ubuntu)
  • GitHub Check: Analyze (python)
🔇 Additional comments (1)
airbyte_cdk/sources/declarative/declarative_stream.py (1)

193-196: LGTM! Clean implementation of AsyncRetriever support.

The extension of get_cursor to support AsyncRetriever is well-implemented and aligns with the PR objectives.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant