Repository navigation
[Data] Add streaming sources to Ray Data - #55467
soffer-anyscale wants to merge 45 commits into
Conversation
Signed-off-by: soffer-anyscale <[email protected]>
There was a problem hiding this comment.
Summary of Changes
Hello @soffer-anyscale, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!
I've implemented significant enhancements to Ray Data by introducing comprehensive support for unbounded streaming data sources. This includes new APIs and underlying infrastructure to ingest data continuously from popular streaming platforms like Apache Kafka, Amazon Kinesis, and Apache Flink, enabling Ray Data to handle real-time data ingestion scenarios.
Highlights
- Core Streaming Abstraction: I've introduced a new
StreamingDatasourceabstract base class, along withStreamingPositionandStreamingMetrics, to provide a standardized and extensible framework for building streaming data connectors within Ray Data. - Apache Kafka Integration: I've added
ray.data.read_kafka, allowing users to easily read data from Kafka topics. This supports various trigger mechanisms, including one-time reads, continuous streaming, fixed-interval micro-batching, and cron-scheduled processing. - Amazon Kinesis Integration: I've implemented
ray.data.read_kinesisto enable seamless data ingestion from Amazon Kinesis Data Streams, offering the same flexible trigger options as Kafka. - Apache Flink Integration: I've provided
ray.data.read_flinkto connect Ray Data with Apache Flink, supporting diverse Flink sources such as REST APIs, SQL queries, checkpoints, and tables, all configurable with various streaming triggers. - Flexible Streaming Triggers: I've introduced a
StreamingTriggermechanism that allows users to define how data is consumed from streaming sources, supporting "once", "continuous", "fixed_interval" (e.g., "30s", "5m"), and "cron" expressions. - New Physical Operator for Unbounded Data: I've added
UnboundedQueueStreamingDataOperatorto the Ray Data execution engine, specifically designed to manage and process continuous streams of data efficiently. - Dependency Management: I've updated the
data-test-requirements.txtto include necessary libraries likekafka-python,boto3,croniter, andpyflinkto support these new streaming capabilities.
Using Gemini Code Assist
The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.
Invoking Gemini
You can request assistance from Gemini at any point in your pull request via creating an issue comment (i.e. comment on the pull request page) using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands.
| Feature | Command | Description |
|---|---|---|
| Code Review | /gemini review |
Performs a code review for the current pull request in its current state. |
| Pull Request Summary | /gemini summary |
Provides a summary of the current pull request in its current state. |
| Comment | @gemini-code-assist | Responds in comments when explicitly tagged, both in issue comments and review comments. |
| Help | /gemini help |
Displays a list of available commands. |
Customization
To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.
Limitations & Feedback
Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments or fill out our survey to provide feedback.
You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.
Footnotes
-
Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution. ↩
There was a problem hiding this comment.
Pull Request Overview
This PR adds streaming data sources to Ray Data, enabling ingestion from unbounded streaming sources like Kafka, Kinesis, and Flink. The implementation introduces a new StreamingDatasource base class and comprehensive streaming infrastructure with trigger-based processing patterns.
Key Changes:
- Introduces
StreamingDatasourceabstract base class for all streaming sources - Adds three concrete streaming implementations:
KafkaDatasource,KinesisDatasource, andFlinkDatasource - Implements streaming trigger system with support for continuous, fixed-interval, and cron-based processing
- Creates new streaming logical and physical operators to handle unbounded data sources
Reviewed Changes
Copilot reviewed 14 out of 14 changed files in this pull request and generated 9 comments.
Show a summary per file
| File | Description |
|---|---|
| python/requirements/ml/data-test-requirements.txt | Adds test dependencies for streaming datasources (kafka-python, boto3, croniter, pyflink) |
| python/ray/data/tests/test_kafka_datasource.py | Comprehensive test suite for Kafka datasource functionality with mocking |
| python/ray/data/read_api.py | Adds three new public APIs: read_kafka(), read_kinesis(), and read_flink() |
| python/ray/data/datasource/streaming_datasource.py | Core streaming datasource infrastructure and abstract base class |
| python/ray/data/datasource/init.py | Exports streaming datasource classes and utilities |
| python/ray/data/_internal/planner/planner.py | Integrates streaming operators into the execution planner |
| python/ray/data/_internal/planner/plan_streaming_op.py | Planning logic for streaming operators |
| python/ray/data/_internal/logical/operators/streaming_data_operator.py | Logical streaming operators and trigger configuration |
| python/ray/data/_internal/execution/operators/unbounded_queue_streaming_data.py | Physical operator for executing streaming tasks |
| python/ray/data/_internal/datasource/video_datasource.py | Minor boolean comparison fix |
| python/ray/data/_internal/datasource/kinesis_datasource.py | Kinesis streaming datasource implementation |
| python/ray/data/_internal/datasource/kafka_datasource.py | Kafka streaming datasource implementation |
| python/ray/data/_internal/datasource/flink_datasource.py | Flink streaming datasource implementation |
| python/ray/data/init.py | Exports new streaming read functions |
There was a problem hiding this comment.
Code Review
This PR introduces streaming data sources for Kafka, Kinesis, and Flink, which is a great addition to Ray Data. The overall structure with StreamingDatasource abstraction and the UnboundedQueueStreamingDataOperator for handling streaming execution is well-designed. However, there are several critical issues that need to be addressed. The Flink datasource appears to be a mock implementation, which should be clarified or completed. All new datasources use a global dictionary for position tracking, which is not safe for distributed execution and will lead to incorrect behavior. There are also issues with handling start/end positions in Kafka and Kinesis sources. I've left detailed comments on these points.
Signed-off-by: soffer-anyscale <[email protected]>
Signed-off-by: soffer-anyscale <[email protected]>
Signed-off-by: soffer-anyscale <[email protected]>
Signed-off-by: soffer-anyscale <[email protected]>
Signed-off-by: soffer-anyscale <[email protected]>
Signed-off-by: soffer-anyscale <[email protected]>
|
This pull request has been automatically marked as stale because it has not had You can always ask for help on our discussion forum or Ray's public slack channel. If you'd like to keep this open, just leave any comment, and the stale label will be removed. |
…monitoring - Fix import path issues in kafka, kinesis, and flink datasources - Remove duplicate UnboundedDataOperator class definition - Add comprehensive input validation to all datasource constructors - Enhance error handling and exception management - Improve backpressure logic with fallback mechanisms - Add proper Ray Data integration patterns and schema support - Implement comprehensive logging and performance monitoring - Fix API consistency issues and naming patterns - Add security validation for ray_remote_args Signed-off-by: soffer-anyscale <[email protected]>
…ema mismatch - Remove duplicate _validate_ray_remote_args method in UnboundedDataOperator - Fix _StreamingTaskWrapper attribute access by passing operator reference - Add job_name to Flink schema to match test expectations - Ensure all methods properly access operator attributes through reference Signed-off-by: soffer-anyscale <[email protected]>
…comprehensive docs - Fix critical bugs: methods misplaced, duplicate definitions, architecture violations - Replace mock code with real kafka-python, boto3, and requests integrations - Add 307+ inline comments explaining logic and microbatch streaming pattern - Fix planner integration to properly convert logical to physical operators - Improve tests: fix assertions, add validation tests (29 total tests) - Implement Kinesis Enhanced Fan-Out, Kafka incremental yielding, Flink REST API - All code follows Ray Data standards and patterns Signed-off-by: soffer-anyscale <[email protected]>
- Fix undefined shard_id variable bug in kinesis_datasource.py (lines 418, 436) - Apply black formatter to all streaming datasource files - Fix quote style (single to double quotes) per Ray standards - Improve line wrapping and indentation - Add proper blank lines per PEP 8 - Format test files for consistency All changes improve code quality and Ray coding standards compliance. Signed-off-by: soffer-anyscale <[email protected]>
- Remove unused auth variable in flink_datasource.py - Rename processing_time field to use_processing_time to avoid method name conflict Signed-off-by: soffer-anyscale <[email protected]>
Register test_kafka.py, test_kinesis.py, and test_flink.py in BUILD file so they can be run automatically by CI. Signed-off-by: soffer-anyscale <[email protected]>
Bug 1: StreamingTrigger field name mismatch - Fixed 'processing_time' to 'use_processing_time' in with_watermark() and with_checkpoint_location() - This caused TypeError from unexpected keyword argument Bug 2: Schema mismatch causing PyArrow failures - Kafka and Kinesis were deserializing JSON (returning dicts/lists) but schema declared pa.string() - Changed to keep data as strings without JSON parsing - Users can parse JSON themselves using map_batches if needed - Removed unused json imports Signed-off-by: soffer-anyscale <[email protected]>
The auto_offset_reset parameter was incorrectly defaulting to start_offset, which could be a numeric string. KafkaConsumer only accepts 'earliest' or 'latest' for this parameter. This fix ensures auto_offset_reset always receives a valid value while numeric offsets continue to work via seek(). Signed-off-by: soffer-anyscale <[email protected]>
Break long lines to comply with Python line length standards: - Multi-line conditional expressions - Multi-line calculations with inline comments - Multi-line logger calls - Multi-line conditionals These changes improve code readability and comply with ruff formatting standards (E501). Signed-off-by: soffer-anyscale <[email protected]>
Signed-off-by: soffer-anyscale <[email protected]>
| table_name = flink_config["table_name"] | ||
| result = table_env.execute_sql( | ||
| f"SELECT * FROM {table_name} LIMIT {max_records_per_task}" | ||
| ) |
There was a problem hiding this comment.
Bug: SQL Injection: Unsafe User Input in Queries
The table_name from user-provided flink_config is directly interpolated into a SQL query using an f-string without sanitization or parameterization. This creates a SQL injection vulnerability where a malicious user could provide a table name like "users; DROP TABLE users; --" to execute arbitrary SQL commands against the Flink table environment.
|
@soffer-anyscale hi, any updates? I'm really looking forward to the landing of this feature |
…ared utilities, reduce code duplication - Simplified UnboundDatasource public API by removing unused abstractions (UnboundMetrics, UnboundPosition, infer_schema_from_records) - Deleted duplicate internal unbound_datasource.py to eliminate confusion - Created streaming_utils.py with shared AWS and HTTP client utilities (AWSCredentials, HTTPClientConfig) - Refactored KinesisDatasource to use shared utilities (257 lines, 53% reduction) - Refactored FlinkDatasource to use shared utilities (201 lines, 56% reduction) - Updated datasource/__init__.py exports to remove deleted classes - All changes maintain backward compatibility and pass ruff linting Signed-off-by: soffer-anyscale <[email protected]>
| end_sequence=end_sequence, | ||
| enhanced_fan_out=enhanced_fan_out, | ||
| consumer_name=consumer_name, | ||
| ) |
There was a problem hiding this comment.
read_kinesis passes invalid parameters to datasource constructor
High Severity
The read_kinesis function passes kinesis_config as a parameter to KinesisDatasource, but the datasource's __init__ method expects region_name as the second required parameter, not kinesis_config. The constructor signature is __init__(self, stream_name, region_name, ...) but the call uses KinesisDatasource(stream_name=stream_name, kinesis_config=kinesis_config, ...). This will raise a TypeError at runtime, completely breaking the read_kinesis function.
Additional Locations (1)
| max_records_per_task=max_records_per_task, | ||
| start_position=start_position, | ||
| end_position=end_position, | ||
| ) |
There was a problem hiding this comment.
read_flink passes invalid parameters to datasource constructor
High Severity
The read_flink function passes source_type, flink_config, start_position, and end_position to FlinkDatasource, but the datasource's constructor expects rest_api_url and job_id as the first two required parameters. None of the parameters being passed (source_type, flink_config, etc.) exist in the datasource's __init__ signature. This will raise a TypeError at runtime, completely breaking the read_flink function.
Additional Locations (1)
| ConsumerARN=f"arn:aws:kinesis:{credentials.region_name}:{stream_name}:{consumer_name}", | ||
| ShardId=shard_id, | ||
| StartingPosition={"Type": start_sequence}, | ||
| ) |
There was a problem hiding this comment.
Kinesis Enhanced Fan-Out uses malformed Consumer ARN
Medium Severity
The Kinesis Consumer ARN is incorrectly constructed as arn:aws:kinesis:{region}:{stream_name}:{consumer_name}. The proper AWS format is arn:aws:kinesis:{region}:{account-id}:stream/{stream-name}/consumer/{consumer-name}:{creation-timestamp}. The code uses stream_name where the AWS account ID should be and omits the required path structure. This will cause subscribe_to_shard to fail with an invalid ARN error when Enhanced Fan-Out is enabled.
|
|
||
| credentials = f"{self.username}:{self.password}" | ||
| encoded = base64.b64encode(credentials.encode()).decode() | ||
| headers["Authorization"] = f"Basic {encoded}" |
There was a problem hiding this comment.
Basic auth requires unrelated auth_token field to be set
Medium Severity
The HTTPClientConfig.get_request_kwargs() method wraps the basic authentication logic inside if self.auth_token:, which means basic auth only works when auth_token is also set. Basic authentication should work with just username and password fields, without requiring auth_token. Users configuring auth_type="basic" with username/password but no auth_token will silently get no authentication headers added to their requests.
| self.trigger = StreamingTrigger( | ||
| trigger_type="fixed_interval", | ||
| interval=interval, | ||
| ) |
There was a problem hiding this comment.
StreamingTrigger loses configuration when setting default interval
Medium Severity
When a fixed_interval trigger has no interval set, the code creates a new StreamingTrigger with only trigger_type and interval fields, discarding all other configuration from the original trigger. This loses approximately 20 configuration fields including checkpoint_location, output_mode, watermark_column, max_consecutive_empty_batches, idle_timeout, autoscaling settings, and rate limiting settings. The comment states the intent is to "create a copy" but it actually creates a minimal new trigger.
| raise StopIteration("No tasks ready") | ||
|
|
||
| # Update remaining tasks - remove the completed one | ||
| self._current_read_tasks = remaining |
There was a problem hiding this comment.
Task start times not updated when tasks complete
Medium Severity
When a task completes in _get_next_inner, the code updates _current_read_tasks = remaining but does not remove the corresponding entry from _task_start_times. This causes the two lists to become desynchronized. In _check_task_timeouts, when iterating over _current_read_tasks and using index i to access _task_start_times[i], the code retrieves the wrong task's start time. This leads to incorrect timeout detection - tasks may be prematurely cancelled or not cancelled when they should be.
Additional Locations (1)
…eads - Create KafkaBoundedDatasource for trigger='once' batch reads (from master) - Create KafkaStreamingDatasource for trigger='continuous'/'interval'/'cron' streaming reads - Add KafkaAuthConfig dataclass for authentication configuration - Update read_kafka() to dispatch to appropriate datasource based on trigger - Maintain backward compatibility with existing master read_kafka batch functionality - Export KafkaAuthConfig, AWSCredentials, HTTPClientConfig, StreamingTrigger in ray.data Signed-off-by: soffer-anyscale <[email protected]>
| end_sequence=end_sequence, | ||
| enhanced_fan_out=enhanced_fan_out, | ||
| consumer_name=consumer_name, | ||
| ) |
There was a problem hiding this comment.
Kinesis API passes wrong constructor parameters
High Severity
The read_kinesis function passes kinesis_config=kinesis_config to KinesisDatasource, but this parameter doesn't exist. The KinesisDatasource.__init__ expects region_name: str as a required positional argument and aws_credentials: Optional[AWSCredentials] for credentials. This will cause a TypeError when read_kinesis is called.
| max_records_per_task=max_records_per_task, | ||
| start_position=start_position, | ||
| end_position=end_position, | ||
| ) |
There was a problem hiding this comment.
Flink API passes wrong constructor parameters
High Severity
The read_flink function passes source_type, flink_config, start_position, and end_position to FlinkDatasource, but none of these parameters exist. The FlinkDatasource.__init__ only accepts rest_api_url: str, job_id: str, max_records_per_task, http_config, and poll_interval_seconds. This will cause a TypeError when read_flink is called.
|
|
||
| credentials = f"{self.username}:{self.password}" | ||
| encoded = base64.b64encode(credentials.encode()).decode() | ||
| headers["Authorization"] = f"Basic {encoded}" |
There was a problem hiding this comment.
Basic authentication silently fails without auth_token
Medium Severity
The HTTPClientConfig.get_request_kwargs() method requires auth_token to be set before any authentication header is added, including for basic auth. For basic authentication, users typically only set username and password without an auth_token. With the current logic, if auth_type="basic" with valid username and password but no auth_token, no Authorization header is added and authentication silently fails.
| return None # Not tracked for streaming tasks | ||
|
|
||
| def cancel(self, force: bool = False) -> None: | ||
| ray.cancel(self._task_ref, force=force) |
There was a problem hiding this comment.
Task wrapper missing required _cancel method for shutdown
High Severity
The _StreamingTaskWrapper class implements cancel() but the OpTask interface and base class _cancel_active_tasks() expect a _cancel() method. When the operator is shut down, the base class calls task._cancel(force=force) on each task wrapper, which will raise AttributeError because the method doesn't exist. This prevents graceful shutdown of streaming operators.
- Fix read_kinesis() to use AWSCredentials instead of kinesis_config dict - Fix read_flink() to use HTTPClientConfig and only support rest_api source - Fix HTTPClientConfig basic auth to work without requiring auth_token - Add _cancel() method to _StreamingTaskWrapper for graceful shutdown These fixes resolve 4 high/medium severity bugs found by Cursor bot review. Signed-off-by: soffer-anyscale <[email protected]>
Resolved conflicts by keeping streaming-aware implementations: - kafka_datasource.py: Unified bounded + streaming implementation - __init__.py: Exports for streaming config classes - read_api.py: Streaming-aware read functions - context.py: Streaming context support - planner.py: Streaming operator planning - requirements_compiled.txt: Updated dependencies - loading_data.rst: Updated documentation Signed-off-by: soffer-anyscale <[email protected]>
| if enhanced_fan_out and consumer_name: | ||
| # Enhanced Fan-Out mode | ||
| response = client.subscribe_to_shard( | ||
| ConsumerARN=f"arn:aws:kinesis:{credentials.region_name}:{stream_name}:{consumer_name}", |
There was a problem hiding this comment.
Kinesis ConsumerARN constructed with invalid format
High Severity
The ConsumerARN is constructed as arn:aws:kinesis:{region}:{stream_name}:{consumer_name}, but AWS Kinesis Consumer ARNs have a different format: arn:aws:kinesis:{region}:{account-id}:stream/{stream-name}/consumer/{consumer-name}:{creation-timestamp}. The code places stream_name where the AWS account ID should be, omits the stream/ and /consumer/ prefixes, and lacks the required creation timestamp. This malformed ARN will cause subscribe_to_shard to fail with an InvalidArgumentException, making enhanced fan-out mode completely non-functional.
| shard_ids = [shard["ShardId"] for shard in response["Shards"]] | ||
|
|
||
| if parallelism > 0: | ||
| shard_ids = shard_ids[:parallelism] |
There was a problem hiding this comment.
Kinesis streaming truncates shards beyond parallelism limit
High Severity
KinesisDatasource._get_read_tasks_for_partition truncates shard_ids to shard_ids[:parallelism] when parallelism > 0, silently discarding shards beyond the parallelism limit. Since the default parallelism is 1, a Kinesis stream with multiple shards will only have its first shard read while data from all other shards is silently dropped, causing significant data loss.
| """ | ||
| topics_to_process = ( | ||
| self.topics[:parallelism] if parallelism > 0 else self.topics | ||
| ) |
There was a problem hiding this comment.
Kafka streaming truncates topics beyond parallelism limit
High Severity
KafkaStreamingDatasource._get_read_tasks_for_partition slices topics to self.topics[:parallelism], silently discarding topics beyond the parallelism limit. Since UnboundedDataOperator defaults parallelism to 1 when not specified, users with multiple topics will only read from the first topic while the rest are completely ignored without warning. This causes silent data loss for streaming workloads.
| "session_timeout_ms": 30000, | ||
| "max_poll_records": min(max_records, 500), | ||
| "value_deserializer": lambda v: v.decode("utf-8") if v else None, | ||
| "key_deserializer": lambda k: k.decode("utf-8") if k else None, |
There was a problem hiding this comment.
Kafka streaming deserializer crashes on non-UTF-8 bytes
Medium Severity
The KafkaStreamingDatasource deserializers use v.decode("utf-8") and k.decode("utf-8") without error handling. Kafka messages containing non-UTF-8 bytes (Avro, Protobuf, compressed data, or binary payloads) will raise UnicodeDecodeError and crash the reader. This contrasts with KinesisDatasource which correctly uses decode("utf-8", errors="replace") to handle invalid sequences gracefully, and KafkaBoundedDatasource which keeps data as raw bytes.
| raise StopIteration("No tasks ready") | ||
|
|
||
| # Update remaining tasks - remove the completed one | ||
| self._current_read_tasks = remaining |
There was a problem hiding this comment.
Task start times desync after normal task completion
Medium Severity
When a task completes via ray.wait, _current_read_tasks is replaced with remaining (excluding the completed task), but _task_start_times is not updated correspondingly. This causes the two lists to become desynchronized. Subsequent calls to _check_task_timeouts use index i from _current_read_tasks to look up _task_start_times[i], resulting in incorrect start times being used for timeout detection. Tasks may be incorrectly timed out or fail to time out when they should.
Additional Locations (1)
- Fix Kinesis ConsumerARN format: properly get/create consumer and retrieve correct ARN - Fix Kinesis shard truncation: remove parallelism limit, process all shards - Fix Kafka topic truncation: remove parallelism limit, process all topics - Fix Kafka deserializer: add errors='replace' to handle non-UTF-8 bytes gracefully - Fix task start times desync: sync _task_start_times when tasks complete These fixes resolve 5 high/medium severity bugs found by Cursor bot review. Signed-off-by: soffer-anyscale <[email protected]>
| # Single block result (less common, for simple datasources) | ||
| has_data = result is not None | ||
| block_ref = ray.put(result) | ||
| bundle = RefBundle(refs=[block_ref], metadata=[None]) |
There was a problem hiding this comment.
RefBundle constructor called with invalid parameters
High Severity
The RefBundle dataclass is constructed with invalid keyword arguments refs= and metadata=. The RefBundle constructor actually requires blocks (a tuple of (ObjectRef, BlockMetadata) pairs), schema, and owns_blocks as parameters. Using refs=block_refs, metadata=metadata_list will raise a TypeError at runtime because these are not valid constructor parameters and the required parameters are missing.
| session = boto3.Session(**self.credentials.to_session_kwargs()) | ||
| client = session.client("kinesis", **self.credentials.to_client_kwargs()) | ||
| response = client.list_shards(StreamName=self.stream_name) | ||
| shard_ids = [shard["ShardId"] for shard in response["Shards"]] |
There was a problem hiding this comment.
Kinesis shard discovery missing pagination handling
Medium Severity
The Kinesis shard discovery uses a single list_shards API call without handling pagination. The AWS Kinesis list_shards API returns results in pages and includes a NextToken when more shards exist. For streams with many shards (exceeding the API's page size), this code will silently miss shards, causing data loss without any error indication.
…or features - Add checkpointing support (initial_checkpoint, commit_checkpoint, two-phase commit) - Add budget per trigger (max_records_per_trigger, max_bytes_per_trigger, max_splits_per_trigger) - Implement block coalescing for well-sized blocks - Yield (block, metadata) tuples for zero-copy metadata handling - Add lag metrics support for lag-aware autoscaling - Add reader actors support where applicable - Remove duplicate code and unnecessary error handling (fail fast) - Clean up imports and move coalescer initialization outside closures Signed-off-by: soffer-anyscale <[email protected]>
|
|
||
| from ray.data._internal.output_buffer import BlockOutputBuffer, OutputBlockSizeOption | ||
| from ray.data._internal.streaming.block_coalescer import BlockCoalescer | ||
| from ray.data._internal.streaming.streaming_lag_metrics import LagMetrics |
There was a problem hiding this comment.
Wrong import path for LagMetrics causes ImportError
High Severity
The import path for LagMetrics is incorrect. The code imports from ray.data._internal.streaming.streaming_lag_metrics, but the file streaming_lag_metrics.py is created at ray.data._internal.datasource.streaming_lag_metrics. The flink_datasource.py uses the correct path while kafka_datasource.py and kinesis_datasource.py use the wrong path, causing an ImportError at runtime when these modules are loaded.
Additional Locations (1)
| partitions = consumer.partitions_for_topic(topic) | ||
| if partitions: | ||
| topic_partitions = [ | ||
| TopicPartition(topic, p) for p in partitions |
There was a problem hiding this comment.
Missing TopicPartition import in initial_checkpoint method
High Severity
The initial_checkpoint method only imports KafkaConsumer from the kafka module at line 521, but then uses TopicPartition at line 536 without importing it. This causes a NameError: name 'TopicPartition' is not defined at runtime when a consumer group is configured. Other methods like commit_checkpoint correctly import both KafkaConsumer and TopicPartition.
| try: | ||
| partition = int(partition_str) | ||
| tp = TopicPartition(topic, partition) | ||
| offsets_to_commit[tp] = offset |
There was a problem hiding this comment.
Kafka commit_checkpoint doesn't filter None offsets
Medium Severity
The commit_checkpoint method adds offsets to offsets_to_commit without checking if the offset value is None. The get_read_tasks method initializes next_checkpoint with None values when there's no prior checkpoint (line 643). If this checkpoint is later passed to commit_checkpoint, the code attempts to commit None offsets, which causes kafka-python to fail when serializing the commit request.
| logger.debug( | ||
| f"Limited shards to {max_splits_per_trigger} " | ||
| f"(from {len(shard_ids)})" | ||
| ) |
There was a problem hiding this comment.
Log message shows wrong count after list truncation
Low Severity
The debug log message reports len(shard_ids) or len(topic_partitions) after the list has already been truncated, making the message confusing. For example, it logs "Limited shards to 5 (from 5)" instead of "Limited shards to 5 (from 10)". The original count needs to be captured before the truncation.
Additional Locations (1)
| ConsumerARN=consumer_arn, | ||
| ShardId=shard_id, | ||
| StartingPosition={"Type": start_sequence}, | ||
| ) |
There was a problem hiding this comment.
Kinesis EFO mode ignores checkpoint, breaks resume
High Severity
The Enhanced Fan-Out (EFO) mode completely ignores checkpoints and always starts from start_sequence (typically "LATEST"). Although checkpoint_sequence is captured at lines 262-265, it's never used in the EFO branch. In contrast, standard polling mode (lines 384-393) correctly uses checkpoint_sequence with "AFTER_SEQUENCE_NUMBER". This causes data loss or duplication on restart when using EFO mode.
|
|
||
| # Skip metrics older than checkpoint timestamp | ||
| if start_timestamp and current_timestamp < start_timestamp: | ||
| continue |
There was a problem hiding this comment.
Flink checkpoint skip condition never triggers
Medium Severity
The checkpoint skip logic compares current_timestamp (current wall clock time via time.time()) against start_timestamp (past checkpoint time). The condition current_timestamp < start_timestamp checks if now < past, which is always false. This means the "Skip metrics older than checkpoint timestamp" logic is dead code that never executes, defeating the purpose of checkpointing for deduplication.
- Add create_block_coalescer() helper to centralize coalescer initialization - Add create_block_metadata() helper to standardize metadata creation - Add yield_coalesced_blocks() helper to eliminate duplicate coalescing patterns - Replace all duplicate BlockMetadata creation patterns across Kafka, Kinesis, Flink - Replace all duplicate coalescing+yielding patterns with helper function - Remove ~150 lines of duplicated code across three datasources Signed-off-by: soffer-anyscale <[email protected]>
Signed-off-by: soffer-anyscale <[email protected]>
| # Yield any pending coalesced blocks | ||
| if small_tables: | ||
| yield from yield_coalesced_blocks(coalescer, small_tables, f"kafka://{topic}/{partition}") | ||
| yield from yield_coalesced_blocks(coalescer, small_tables, f"kafka://{topic}/{partition}") |
There was a problem hiding this comment.
Duplicate yield causes data duplication in Kafka streaming
High Severity
The yield from yield_coalesced_blocks(...) is called twice in succession with the same small_tables list at multiple locations. The coalesce_tables method iterates over the list each time it's called. Since small_tables is not cleared between calls, the second call will iterate and yield the same tables again, causing all data to be emitted twice. This results in data duplication in streaming reads.
Additional Locations (2)
| if partitions: | ||
| topic_partitions = [ | ||
| TopicPartition(topic, p) for p in partitions | ||
| ] |
There was a problem hiding this comment.
Missing TopicPartition import causes NameError at runtime
High Severity
In initial_checkpoint(), only KafkaConsumer is imported at line 524, but TopicPartition is used at line 539 in the list comprehension. This will cause a NameError: name 'TopicPartition' is not defined when the method is called with a group_id set.
| # Yield coalesced blocks | ||
| yield from yield_coalesced_blocks(coalescer, small_tables, f"kafka://{topic}/{partition}") | ||
| yield from yield_coalesced_blocks(coalescer, small_tables, f"kafka://{topic}/{partition}") | ||
|
|
There was a problem hiding this comment.
Missing return after end_offset check continues processing
Medium Severity
After detecting that msg.offset >= int(end_offset) and yielding the coalesced blocks, the code lacks a return statement. Execution continues to line 798 where the current message (which should be skipped) is appended to records, causing messages beyond the specified end_offset to be processed.
| small_tables.append(pa.Table.from_pylist(records)) | ||
| # Yield coalesced blocks | ||
| yield from yield_coalesced_blocks(coalescer, small_tables, f"kafka://{topic}/{partition}") | ||
| yield from yield_coalesced_blocks(coalescer, small_tables, f"kafka://{topic}/{partition}") |
There was a problem hiding this comment.
Missing return after max_records check causes infinite loop
Medium Severity
When records_read >= max_records, the code yields coalesced blocks but lacks a return statement. The while True loop continues indefinitely, and since records_read is already at max, the condition will trigger on every subsequent message, leading to repeated yields without termination.
| yield_coalesced_blocks, | ||
| ) | ||
| from ray.data._internal.output_buffer import BlockOutputBuffer, OutputBlockSizeOption | ||
| from ray.data._internal.streaming.streaming_lag_metrics import LagMetrics |
There was a problem hiding this comment.
LagMetrics imported from non-existent module path
High Severity
LagMetrics is imported from ray.data._internal.streaming.streaming_lag_metrics, but the class is actually defined in ray.data._internal.datasource.streaming_lag_metrics. The streaming subdirectory does not contain this module. This will cause an ImportError when the Kafka or Kinesis streaming datasources are used.
Additional Locations (1)
| / self.data_context.streaming_lag_conversion_factor | ||
| if lag_metrics.total_lag > 0 | ||
| else 0.0 | ||
| ) |
There was a problem hiding this comment.
Accessing lag_metrics.total_lag when lag_metrics is None
Medium Severity
In _check_and_apply_autoscaling, the else branch at line 569 executes when lag_metrics is falsy (None), but then the code attempts to access lag_metrics.total_lag at lines 572 and 574. This will raise an AttributeError when autoscaling runs and get_lag_metrics() returns None.
| ) | ||
|
|
||
| # Update byte-level accounting | ||
| self._bytes_in_flight += bundled_bytes |
There was a problem hiding this comment.
bytes_in_flight counter never decremented causes operator stall
High Severity
The _bytes_in_flight counter is incremented at line 1240 when bundles are emitted but is never decremented anywhere in the code. Once this counter exceeds _max_bytes_in_flight, the _prime_generators() method stops priming generators (lines 962-967), causing the streaming operator to permanently stall after processing a certain amount of data.
Additional Locations (1)
| small_tables.append(pa.Table.from_pylist(records_buffer)) | ||
| # Yield coalesced blocks | ||
| yield from yield_coalesced_blocks(coalescer, small_tables, f"kinesis://{stream_name}/{shard_id}") | ||
|
|
There was a problem hiding this comment.
Kinesis missing returns after limit checks like Kafka
Medium Severity
Similar to the Kafka datasource, the Kinesis datasource is missing return statements after yielding when end_sequence is reached (line 385) and when max_records is reached (line 416). Without returns, execution continues and the current record is still appended and processed, violating the intended limit semantics.
Additional Locations (1)
- Create TwoPhaseCommitMixin with default implementations of prepare_commit, commit, abort_commit - Remove duplicate two-phase commit methods from Kafka, Kinesis, Flink datasources - Datasources now inherit from mixin and only override abort_commit for custom logging - Removed ~69 lines of duplicated code across three datasources Signed-off-by: soffer-anyscale <[email protected]>
| # Yield any pending coalesced blocks | ||
| if small_tables: | ||
| yield from yield_coalesced_blocks(coalescer, small_tables, f"kafka://{topic}/{partition}") | ||
| yield from yield_coalesced_blocks(coalescer, small_tables, f"kafka://{topic}/{partition}") |
There was a problem hiding this comment.
Duplicate yield calls cause double emission of blocks
High Severity
yield from yield_coalesced_blocks(...) is called twice in a row at multiple locations in KafkaStreamingDatasource._create_partition_read_task. This appears to be a copy-paste error that will cause the same coalesced blocks to be yielded twice, resulting in duplicate data being emitted downstream. The duplicate calls appear at lines 779-780, 796-797, 827-828, 843-844, and 849-850.
Additional Locations (2)
| small_tables.append(pa.Table.from_pylist(records)) | ||
| # Yield coalesced blocks | ||
| yield from yield_coalesced_blocks(coalescer, small_tables, f"kafka://{topic}/{partition}") | ||
| yield from yield_coalesced_blocks(coalescer, small_tables, f"kafka://{topic}/{partition}") |
There was a problem hiding this comment.
Missing return after max_records causes infinite loop
High Severity
When records_read >= max_records is reached, the code yields coalesced blocks but lacks a return statement. Since this is inside a while True: loop, execution continues, and since records_read already exceeds max_records, this condition will repeatedly trigger on subsequent loop iterations, causing unbounded processing. Compare with the max_bytes check at lines 821-831 which correctly has a return after yielding.
| records = [] | ||
| # Yield coalesced blocks | ||
| yield from yield_coalesced_blocks(coalescer, small_tables, f"kafka://{topic}/{partition}") | ||
| yield from yield_coalesced_blocks(coalescer, small_tables, f"kafka://{topic}/{partition}") |
There was a problem hiding this comment.
Missing return after end_offset continues past boundary
High Severity
When msg.offset >= int(end_offset) is detected, the code yields coalesced blocks but lacks a return statement. After yielding, execution falls through to lines 799-810 which append the current message (the one that matched end_offset) to records, and the loop continues processing subsequent messages. This defeats the purpose of the end_offset boundary.
| topic_partitions = topic_partitions[:max_splits_per_trigger] | ||
| logger.debug( | ||
| f"Limited partitions to {max_splits_per_trigger} " | ||
| f"(from {len(topic_partitions)})" |
There was a problem hiding this comment.
Log message shows wrong count after list slicing
Low Severity
The log message at line 625 says "(from {len(topic_partitions)})" but topic_partitions was already sliced on line 622, so it will display max_splits_per_trigger instead of the original count. The same issue exists in kinesis_datasource.py at line 172 for shard_ids.
Additional Locations (1)
| records_buffer = [] | ||
| # Yield coalesced blocks | ||
| yield from yield_coalesced_blocks(coalescer, small_tables, f"kinesis://{stream_name}/{shard_id}") | ||
|
|
There was a problem hiding this comment.
Missing return statements in Kinesis after limits
High Severity
KinesisDatasource._create_shard_read_task has multiple missing return statements after limit checks. After detecting end_sequence, max_bytes, or max_records limits and yielding blocks, the code continues processing rather than exiting. This occurs in both enhanced fan-out mode (lines 318-327, 341-346, 353-358) and standard polling mode (lines 382-386, 400-406, 413-417).
Additional Locations (2)
| / self.data_context.streaming_lag_conversion_factor | ||
| if lag_metrics.total_lag > 0 | ||
| else 0.0 | ||
| ) |
There was a problem hiding this comment.
Accessing attribute on None causes AttributeError
High Severity
In _check_and_apply_autoscaling, the else branch at line 569 executes when lag_metrics is None, but then immediately tries to access lag_metrics.total_lag at lines 572 and 574. This will raise an AttributeError: 'NoneType' object has no attribute 'total_lag' whenever lag metrics are unavailable (which is the common case when datasources don't implement get_lag_metrics or when the call fails).
| ) | ||
|
|
||
| # Update byte-level accounting | ||
| self._bytes_in_flight += bundled_bytes |
There was a problem hiding this comment.
Bytes-in-flight counter never decremented causes stall
High Severity
The _bytes_in_flight counter is incremented when bundles are emitted (line 1240) but is never decremented when downstream operators consume the blocks. This counter is used to throttle generator priming at lines 962-967. Over time, _bytes_in_flight will monotonically increase until it reaches _max_bytes_in_flight, at which point the operator will stop priming generators and eventually stall, even though the downstream has already consumed the data.
Additional Locations (1)
| # Construct next checkpoint from last timestamps | ||
| next_checkpoint = {str(task_id): timestamp for task_id, timestamp in last_timestamps_dict.items()} | ||
|
|
||
| return read_tasks, next_checkpoint if next_checkpoint else None |
There was a problem hiding this comment.
Flink checkpoint always empty before tasks execute
Medium Severity
The next_checkpoint is constructed from last_timestamps_dict.items() at line 170, but last_timestamps_dict is created empty at line 154 and only gets populated inside the read_fn closures when tasks actually execute. Since get_read_tasks returns before any task executes, the checkpoint will always be empty or None. This breaks checkpoint/resume functionality for Flink streams.
- Add boto3 URL to Kinesis datasource imports - Add requests URL to Flink datasource imports - Add croniter URL to logical operator imports - Improves code documentation and developer experience Signed-off-by: soffer-anyscale <[email protected]>
| # Yield any pending coalesced blocks | ||
| if small_tables: | ||
| yield from yield_coalesced_blocks(coalescer, small_tables, f"kafka://{topic}/{partition}") | ||
| yield from yield_coalesced_blocks(coalescer, small_tables, f"kafka://{topic}/{partition}") |
There was a problem hiding this comment.
Duplicate yield calls produce duplicate data blocks
High Severity
yield from yield_coalesced_blocks(...) is called twice in succession at multiple locations with the same small_tables list. The coalesce_tables method will process the same tables on both calls, causing duplicate data blocks to be yielded to downstream operators. This pattern appears at lines 779-780, 796-797, 827-828, 843-844, and 849-850.
Additional Locations (2)
| if partitions: | ||
| topic_partitions = [ | ||
| TopicPartition(topic, p) for p in partitions | ||
| ] |
There was a problem hiding this comment.
Missing TopicPartition import causes NameError
High Severity
In the initial_checkpoint method, line 525 only imports KafkaConsumer from kafka, but line 540 uses TopicPartition which isn't imported. The TopicPartition at module level (line 38) is only available under TYPE_CHECKING for type hints, not at runtime. This will raise NameError: name 'TopicPartition' is not defined when initial_checkpoint is called with a group_id.
| yield_coalesced_blocks, | ||
| ) | ||
| from ray.data._internal.output_buffer import BlockOutputBuffer, OutputBlockSizeOption | ||
| from ray.data._internal.streaming.streaming_lag_metrics import LagMetrics |
There was a problem hiding this comment.
Wrong import path for LagMetrics causes ModuleNotFoundError
High Severity
The LagMetrics class is defined in ray.data._internal.datasource.streaming_lag_metrics but both kafka_datasource.py and kinesis_datasource.py import from ray.data._internal.streaming.streaming_lag_metrics. This incorrect import path will cause ModuleNotFoundError at runtime when these datasources are used. The flink_datasource.py correctly imports from the datasource path.
Additional Locations (1)
| / self.data_context.streaming_lag_conversion_factor | ||
| if lag_metrics.total_lag > 0 | ||
| else 0.0 | ||
| ) |
There was a problem hiding this comment.
AttributeError accessing None lag_metrics object
High Severity
The else branch at line 569 executes when lag_metrics is falsy (None), but then tries to access lag_metrics.total_lag on lines 572 and 574. This will raise AttributeError: 'NoneType' object has no attribute 'total_lag' whenever get_lag_metrics() returns None, which is a common case for many datasources.
| f"(lag: {lag_seconds:.1f}s if available, " | ||
| f"batch duration: {avg_batch_duration:.2f}s if available, " | ||
| f"empty batches: {self._consecutive_empty_batches})" | ||
| ) |
There was a problem hiding this comment.
Format string fails when lag metrics are None
Medium Severity
The log message at lines 636-637 uses {lag_seconds:.1f} and {avg_batch_duration:.2f} format specifiers, but the condition on lines 617-621 allows entering this code path when either value is None (via not lag_seconds and not avg_batch_duration checks). Formatting None with .1f or .2f raises TypeError.
| ) | ||
| self._max_max_records_per_trigger = ( | ||
| data_context.streaming_max_max_records_per_trigger | ||
| ) |
There was a problem hiding this comment.
Missing DataContext properties causes AttributeError on access
High Severity
The UnboundedDataOperator.__init__ accesses DataContext attributes like data_context.streaming_min_backoff_seconds, streaming_max_backoff_seconds, streaming_batch_duration_window, streaming_default_max_records_per_trigger, etc. However, DataContext only defines these with underscore prefix (_streaming_min_backoff_seconds) and lacks the corresponding @property definitions to expose them. This causes AttributeError when the operator is instantiated.
| # Yield coalesced blocks | ||
| yield from yield_coalesced_blocks(coalescer, small_tables, f"kinesis://{stream_name}/{shard_id}") | ||
|
|
||
| records_buffer.append(_kinesis_record_to_dict(record, shard_id)) |
There was a problem hiding this comment.
Missing return after end offset causes unbounded reads
High Severity
After detecting that end_sequence (or end_offset in Kafka) is reached and yielding the accumulated data, the code lacks a return statement. Execution continues to line 390 which appends the current record to records_buffer, then processes all subsequent records. This violates bounded-read semantics, causing reads beyond the specified end boundary.
Additional Locations (2)
| small_tables.append(pa.Table.from_pylist(records_buffer)) | ||
| records_buffer = [] | ||
| # Yield coalesced blocks | ||
| yield from yield_coalesced_blocks(coalescer, small_tables, f"kinesis://{stream_name}/{shard_id}") |
There was a problem hiding this comment.
Missing return after max_records/max_bytes limits exceeded
Medium Severity
After detecting max_records limit is reached and yielding coalesced blocks, the code lacks a return statement. Processing continues in the loop, adding more records beyond the configured limit. This defeats the purpose of max_records_per_task configuration. The same issue exists for max_bytes checks in Kinesis at lines 343-348 and 402-408.
Additional Locations (2)
|
|
||
| # Skip metrics older than checkpoint timestamp | ||
| if start_timestamp and current_timestamp < start_timestamp: | ||
| continue |
There was a problem hiding this comment.
Checkpoint timestamp comparison uses wrong variable
Medium Severity
The checkpoint skip logic compares current_timestamp (current wall-clock time via time.time()) against start_timestamp (checkpoint). The comment says "Skip metrics older than checkpoint timestamp" but the check current_timestamp < start_timestamp will almost never be true since the current time is always after the checkpoint time. The code should compare the metric's actual timestamp, not the current wall-clock time.
- Add missing 'Any' import to datasource.py for type hints - Add missing 'TaskContext' import to streaming_sink.py with TYPE_CHECKING - Remove duplicate yield_coalesced_blocks calls in kafka_datasource.py - Simplify error handling in kafka_datasource.py (fail-fast approach) - Add third-party library URLs to streaming_utils.py documentation Signed-off-by: soffer-anyscale <[email protected]>
| partitions = consumer.partitions_for_topic(topic) | ||
| if partitions: | ||
| topic_partitions = [ | ||
| TopicPartition(topic, p) for p in partitions |
There was a problem hiding this comment.
Missing TopicPartition import causes NameError at runtime
High Severity
In the initial_checkpoint method, line 526 imports only KafkaConsumer from the kafka module, but line 541 attempts to use TopicPartition which is not imported. The TopicPartition import at line 38 is under TYPE_CHECKING and only available for type hints, not at runtime. This will raise NameError: name 'TopicPartition' is not defined when the method is called.
| records = [] | ||
| # Yield coalesced blocks | ||
| yield from yield_coalesced_blocks(coalescer, small_tables, f"kafka://{topic}/{partition}") | ||
|
|
There was a problem hiding this comment.
Missing return statements after end condition yields
High Severity
In KafkaStreamingDatasource._create_partition_read_task, when the end_offset condition is met (lines 782-792), the code yields coalesced blocks but doesn't return, allowing execution to continue and append the triggering message. Similarly, when max_records is reached (lines 833-837), there's no return after yielding. The max_bytes check at line 825 correctly has a return, highlighting this as an oversight.
Additional Locations (1)
| topic_partitions = topic_partitions[:max_splits_per_trigger] | ||
| logger.debug( | ||
| f"Limited partitions to {max_splits_per_trigger} " | ||
| f"(from {len(topic_partitions)})" |
There was a problem hiding this comment.
Log message shows truncated count instead of original
Low Severity
In both Kafka and Kinesis datasources, when limiting partitions/shards due to max_splits_per_trigger, the debug log message attempts to show the original count with (from {len(...)}). However, the list is truncated before the log statement, so len(topic_partitions) and len(shard_ids) show the new truncated length, not the original. The message would incorrectly read "Limited to 5 (from 5)".
Additional Locations (1)
| # Yield any pending coalesced blocks | ||
| if small_tables: | ||
| yield from yield_coalesced_blocks(coalescer, small_tables, f"kafka://{topic}/{partition}") | ||
| continue |
There was a problem hiding this comment.
Duplicate data yielded when small_tables not cleared
High Severity
In KafkaStreamingDatasource and KinesisDatasource, after yielding coalesced blocks via yield from yield_coalesced_blocks(coalescer, small_tables, ...), the small_tables list is not cleared. When the loop continues (e.g., on empty poll), the same tables are yielded again on the next iteration, causing duplicate data to be produced. The list needs to be cleared with small_tables.clear() or small_tables = [] after yielding.
Additional Locations (1)
| # Yield coalesced blocks | ||
| yield from yield_coalesced_blocks(coalescer, small_tables, f"kinesis://{stream_name}/{shard_id}") | ||
|
|
||
| records_buffer.append(_kinesis_record_to_dict(record, shard_id)) |
There was a problem hiding this comment.
Missing return statements after end condition yields in Kinesis
High Severity
In KinesisDatasource._create_shard_read_task, when end_sequence is met (lines 320-328 in EFO mode, lines 384-388 in standard polling mode), the code yields but doesn't return. The triggering record is still appended at lines 330 and 390 respectively. Same pattern for max_records checks at lines 355-360 and 415-419. This causes records beyond the intended boundary to be processed.
Additional Locations (1)
| small_tables.append(pa.Table.from_pylist(records_buffer)) | ||
| records_buffer = [] | ||
| # Yield coalesced blocks | ||
| yield from yield_coalesced_blocks(coalescer, small_tables, f"kinesis://{stream_name}/{shard_id}") |
There was a problem hiding this comment.
Kinesis missing returns after max_bytes condition yields
High Severity
In KinesisDatasource._create_shard_read_task, when the max_bytes limit is reached (lines 343-348 in EFO mode, lines 403-408 in standard polling mode), the code yields coalesced blocks but doesn't return. Processing continues, causing data beyond the byte limit to be read. The Flink datasource correctly has return statements after its max_bytes yield (line 285), showing the intended pattern.
Additional Locations (1)
| ConsumerARN=consumer_arn, | ||
| ShardId=shard_id, | ||
| StartingPosition={"Type": start_sequence}, | ||
| ) |
There was a problem hiding this comment.
Kinesis EFO consumer not waited for ACTIVE state
High Severity
In the Enhanced Fan-Out (EFO) code path, after registering a new stream consumer via register_stream_consumer (lines 304-308), the code immediately calls subscribe_to_shard (lines 310-314). However, AWS Kinesis requires the consumer to be in ACTIVE state before subscribing. Newly registered consumers start in CREATING state and take several seconds to become ACTIVE. This will cause subscribe_to_shard to fail with a ResourceInUseException or similar error when a new consumer is created.
| # Construct next checkpoint from last timestamps | ||
| next_checkpoint = {str(task_id): timestamp for task_id, timestamp in last_timestamps_dict.items()} | ||
|
|
||
| return read_tasks, next_checkpoint if next_checkpoint else None |
There was a problem hiding this comment.
Checkpoint returns stale values before tasks execute
High Severity
In Flink, Kafka, and Kinesis streaming datasources, the get_read_tasks method constructs next_checkpoint from a shared dict (last_timestamps_dict or last_offsets) that is empty at construction time. The dict comprehension creates a snapshot of the empty dict. Additionally, read tasks execute in separate Ray worker processes, so even if they update the shared dict, those updates cannot propagate back to the driver process. The returned checkpoint will always contain stale/empty values.
Additional Locations (1)
…lint issues - Created yield_coalesced_blocks_with_progress helper to reduce duplication - Simplified UnboundedDataOperator prefetch logic by extracting common methods - Removed silent exception handling - errors now fail loudly - Fixed duplicate parameters in read_kafka function signature - Removed unused imports and variables - Fixed all lint issues (whitespace, unused vars, etc.) Signed-off-by: soffer-anyscale <[email protected]>
| bootstrap_servers=bootstrap_servers, | ||
| kafka_auth_config=kafka_auth_config, | ||
| max_records_per_task=max_records_per_task, | ||
| max_bytes_per_task=max_bytes_per_task, |
There was a problem hiding this comment.
KafkaStreamingDatasource.__init__ missing max_bytes_per_task parameter
High Severity
read_kafka passes max_bytes_per_task=max_bytes_per_task to KafkaStreamingDatasource(), but the __init__ method doesn't accept that parameter. This causes a TypeError at runtime whenever a streaming Kafka read is created with a non-"once" trigger.
Additional Locations (1)
| schema=self._schema, | ||
| input_files=[f"kinesis://{self.stream_name}/{shard_id}"], | ||
| exec_stats=None, | ||
| ) |
There was a problem hiding this comment.
BlockMetadata given invalid schema keyword argument
High Severity
BlockMetadata is constructed with schema=self._schema, but BlockMetadata is a dataclass with fields num_rows, size_bytes, exec_stats, and input_files only — no schema field. This causes a TypeError at runtime when creating a Kinesis read task.
| client = self._get_boto3_client() | ||
| coalescer = create_block_coalescer( | ||
| max_block_size_bytes=self._block_size_bytes | ||
| ) |
There was a problem hiding this comment.
|
|
||
| def read_fn() -> Iterator[Tuple[Block, BlockMetadata]]: | ||
| # Lazily check boto3 import on worker. | ||
| _check_import("boto3", package="boto3") |
There was a problem hiding this comment.
Incorrect _check_import call missing module argument
High Severity
_check_import("boto3", package="boto3") passes a string as the first positional argument obj, but omits the required keyword-only argument module. The correct call pattern, as used on line 80, is _check_import(self, module="boto3", package="boto3").
|
|
||
| k_records = response.get("Records", []) | ||
| if not k_records: | ||
| break |
There was a problem hiding this comment.
Kinesis breaks polling loop on empty records prematurely
Medium Severity
When get_records returns zero records, the code immediately breaks out of the polling loop. Kinesis frequently returns empty responses between batches even when more data exists — the standard pattern is to continue polling with the next shard iterator until the deadline. This causes premature read termination and data loss.
| start_offset = self.start_offset | ||
| end_offset = self.end_offset | ||
| group_id = self.group_id | ||
| poll_timeout_ms = self.poll_timeout_ms |
There was a problem hiding this comment.
Parameter poll_timeout_ms overwritten by instance attribute
Medium Severity
The local variable poll_timeout_ms is reassigned from self.poll_timeout_ms, overwriting the method parameter of the same name. The caller computes a trigger-specific poll timeout and passes it via the poll_timeout_ms parameter, but it's always ignored in favor of the instance's default value.
| checkpoint_key = f"{topic}:{partition}" | ||
| checkpoint_offset = ( | ||
| checkpoint.get(checkpoint_key) if checkpoint else None | ||
| ) |
There was a problem hiding this comment.
Checkpoint passed as scalar but used as dict
High Severity
The caller at get_read_tasks passes checkpoint=checkpoint.get(f"{topic}:{partition}"), which extracts a scalar (int offset or None). But _create_partition_read_task treats checkpoint as a dict and calls checkpoint.get(checkpoint_key) on it. When a checkpoint exists (second microbatch onwards), this crashes with AttributeError: 'int' object has no attribute 'get'.
Additional Locations (1)
| small_tables.append(pa.Table.from_pylist(records)) | ||
| if small_tables: | ||
| yield from _yield_with_progress() | ||
| small_tables.clear() |
There was a problem hiding this comment.
Kafka streaming read loop lacks deadline, runs forever
High Severity
The Kafka streaming read_fn uses while True: with no deadline check, unlike Flink and Kinesis which use while time.time() < deadline:. When fewer records exist than effective_max_records, the loop polls Kafka indefinitely. Additionally, all loop exits are return statements, making the flush code at lines 871-876 unreachable dead code.
| SaveMode, | ||
| ) | ||
| from ray.data.stats import DatasetSummary | ||
| from ray.data.dataset import Dataset, Schema, SinkMode, ClickHouseTableSettings |
There was a problem hiding this comment.
Removed SaveMode export breaks existing imports
High Severity
SaveMode was removed from the ray.data.__init__.py import and __all__, but existing code (including dataset.py docstring examples and test files like test_iceberg.py) still does from ray.data import SaveMode. This causes ImportError at runtime for those existing usages.
## Description Style and grammar pass on Ray Data docs against Ray's [writing-style guide](https://docs.ray.io/en/master/ray-contribute/writing-style.html). Prose only: no code, `literalinclude` blocks, URLs, anchors, or role targets changed. Stacked on #66412, which is stacked on #66381, #66375, and #66352. Review and merge those first. This branch targets `doc-1524-data-vale-cleanup`. It combines this PR's original comparisons-page pass with the custom datasource pass first opened as #66416. ### `comparisons.md` - Renames the legacy "Datasets" product name to "Ray Data". The page already used "Ray Data" for the same subject in the same lists. Third-party "Torch datasets" and "TensorFlow datasets" are unchanged. - Fixes `SageMaker` and `BentoML` casing, which #66412 left as intentional alerts for this pass. - Uses contractions, active voice, second person, and "such as" for examples. - Removes "our blog post", "3rd", "e.g.", mid-sentence colons, and semicolons. - Fixes the grammar of the BentoML-and-Spark sentence and subject-verb agreement for "TensorFlow datasets". - Sentence-cases the dropdown titles and makes them parallel. - Adds a lead-in sentence to each comparison list and uses the `**Term**: explanation` definition-list form from the style guide. - Collapses runs of blank lines between dropdowns to one. ### `custom-datasource-example.md` This is the page whose `<!-- vale off -->` blocks #66412 removed so the future-tense prose they hid could be fixed. - Replaces the three "you'll" future-tense sentences with present tense. - Names Ray Data as the actor in "file types that aren't natively supported" and "Images are already supported". - Replaces "functionality" with "behavior", "Once you've implemented" with "After you implement", and the "(for example, `"png"`)" parenthetical with "such as". - Cuts the time-relative "in the future" from the write-interface note but keeps "is under active development and might change", which is the stability warning. - Corrects the block types. The page said blocks can be dictionaries of NumPy arrays, but `Block` in `block.py` is only a PyArrow table or a pandas DataFrame, including at the commit the page links to. NumPy dictionaries are a batch format. This is a factual correction. - Sentence-cases the title: "Advanced: Read and write custom file types". - Updates the one link in `loading-data.md` whose text quotes the old title. ## Why this isn't a duplicate No other open PR edits `comparisons.md`, `custom-datasource-example.md`, or `doc_code/custom_datasource_example.py`. #55038 adds an experimental SQL API and SQL docs but doesn't edit these pages. See the related question below. I also checked the open Data PRs that mention datasources, including #65760, #57239, and #55467. ## Questions for reviewers Apart from the block-types correction, this pass kept the scope of every claim. These existing claims might be stale, and a Ray Data maintainer is better placed to judge them: - **Third-party feature claims on `comparisons.md`:** Petastorm supports only Parquet, NVTabular supports only Parquet, CSV, and Avro, TensorFlow datasets support only file interleaving across worker shards, and Torch datasets have no I/O layer. - **SQL interface:** "Ray Data doesn't have a SQL interface" would go stale if #55038 lands. - **Comparisons with no measure:** "a streaming paradigm that's better suited to GPU workloads" and "can't effectively handle large datasets". The style guide's "Keep comparisons precise" section applies, but no source for a measure is on the page. - **Repeated comparison points:** the training-ingest dropdowns repeat three points almost word for word. A single comparison table might read better. That moves content, so it isn't in this PR. - **Duplicate headings:** `custom-datasource-example.md` has two H3s named "Implement the constructor", one under reading and one under writing. "Implement the datasource constructor" and "Implement the datasink constructor" would make the right-side TOC clearer. I left them as they are. ## Verification - `vale` with Vale 3.12, run from the repo root: 0 alerts on `comparisons.md`, down from 24, and 0 on `custom-datasource-example.md`, down from 6. `loading-data.md` has no alerts on the edited line. - `codespell`: no hits. - The pre-commit hooks passed on each commit. - A structural check against each pre-edit file confirmed the code-fence count, role targets, anchors, and URLs are unchanged. - For the reworded title, a grep for inbound links found the `{ref}` in `loading-data.md`, updated here, and a toctree entry in `user-guide.md`, which doesn't depend on the title. No links use the heading's implicit slug. - I didn't run a local Sphinx build. The Read the Docs preview covers rendering. ## AI assistance I made these edits with AI assistance (Claude Code) and reviewed the full diff by hand. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Signed-off-by: Douglas Strodtman <[email protected]> Co-authored-by: Claude Opus 5.5 (1M context) <[email protected]>
## Description Style and grammar pass on Ray Data docs against Ray's [writing-style guide](https://docs.ray.io/en/master/ray-contribute/writing-style.html). Prose only: no code, `literalinclude` blocks, URLs, anchors, or role targets changed. Stacked on ray-project#66412, which is stacked on ray-project#66381, ray-project#66375, and ray-project#66352. Review and merge those first. This branch targets `doc-1524-data-vale-cleanup`. It combines this PR's original comparisons-page pass with the custom datasource pass first opened as ray-project#66416. ### `comparisons.md` - Renames the legacy "Datasets" product name to "Ray Data". The page already used "Ray Data" for the same subject in the same lists. Third-party "Torch datasets" and "TensorFlow datasets" are unchanged. - Fixes `SageMaker` and `BentoML` casing, which ray-project#66412 left as intentional alerts for this pass. - Uses contractions, active voice, second person, and "such as" for examples. - Removes "our blog post", "3rd", "e.g.", mid-sentence colons, and semicolons. - Fixes the grammar of the BentoML-and-Spark sentence and subject-verb agreement for "TensorFlow datasets". - Sentence-cases the dropdown titles and makes them parallel. - Adds a lead-in sentence to each comparison list and uses the `**Term**: explanation` definition-list form from the style guide. - Collapses runs of blank lines between dropdowns to one. ### `custom-datasource-example.md` This is the page whose `<!-- vale off -->` blocks ray-project#66412 removed so the future-tense prose they hid could be fixed. - Replaces the three "you'll" future-tense sentences with present tense. - Names Ray Data as the actor in "file types that aren't natively supported" and "Images are already supported". - Replaces "functionality" with "behavior", "Once you've implemented" with "After you implement", and the "(for example, `"png"`)" parenthetical with "such as". - Cuts the time-relative "in the future" from the write-interface note but keeps "is under active development and might change", which is the stability warning. - Corrects the block types. The page said blocks can be dictionaries of NumPy arrays, but `Block` in `block.py` is only a PyArrow table or a pandas DataFrame, including at the commit the page links to. NumPy dictionaries are a batch format. This is a factual correction. - Sentence-cases the title: "Advanced: Read and write custom file types". - Updates the one link in `loading-data.md` whose text quotes the old title. ## Why this isn't a duplicate No other open PR edits `comparisons.md`, `custom-datasource-example.md`, or `doc_code/custom_datasource_example.py`. ray-project#55038 adds an experimental SQL API and SQL docs but doesn't edit these pages. See the related question below. I also checked the open Data PRs that mention datasources, including ray-project#65760, ray-project#57239, and ray-project#55467. ## Questions for reviewers Apart from the block-types correction, this pass kept the scope of every claim. These existing claims might be stale, and a Ray Data maintainer is better placed to judge them: - **Third-party feature claims on `comparisons.md`:** Petastorm supports only Parquet, NVTabular supports only Parquet, CSV, and Avro, TensorFlow datasets support only file interleaving across worker shards, and Torch datasets have no I/O layer. - **SQL interface:** "Ray Data doesn't have a SQL interface" would go stale if ray-project#55038 lands. - **Comparisons with no measure:** "a streaming paradigm that's better suited to GPU workloads" and "can't effectively handle large datasets". The style guide's "Keep comparisons precise" section applies, but no source for a measure is on the page. - **Repeated comparison points:** the training-ingest dropdowns repeat three points almost word for word. A single comparison table might read better. That moves content, so it isn't in this PR. - **Duplicate headings:** `custom-datasource-example.md` has two H3s named "Implement the constructor", one under reading and one under writing. "Implement the datasource constructor" and "Implement the datasink constructor" would make the right-side TOC clearer. I left them as they are. ## Verification - `vale` with Vale 3.12, run from the repo root: 0 alerts on `comparisons.md`, down from 24, and 0 on `custom-datasource-example.md`, down from 6. `loading-data.md` has no alerts on the edited line. - `codespell`: no hits. - The pre-commit hooks passed on each commit. - A structural check against each pre-edit file confirmed the code-fence count, role targets, anchors, and URLs are unchanged. - For the reworded title, a grep for inbound links found the `{ref}` in `loading-data.md`, updated here, and a toctree entry in `user-guide.md`, which doesn't depend on the title. No links use the heading's implicit slug. - I didn't run a local Sphinx build. The Read the Docs preview covers rendering. ## AI assistance I made these edits with AI assistance (Claude Code) and reviewed the full diff by hand. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Signed-off-by: Douglas Strodtman <[email protected]> Co-authored-by: Claude Opus 5.5 (1M context) <[email protected]>


Why are these changes needed?
Much of data ingestion is online streaming data, but Ray Data doesn't have a way of ingesting data for unbounded sources. This PR adds an unbounded source Datasource and three of the common use cases (Kafka, Kinesis, Flink).
Checks
git commit -s) in this PR.scripts/format.shto lint the changes in this PR.method in Tune, I've added it in
doc/source/tune/api/under thecorresponding
.rstfile.Note
Adds unbounded streaming ingestion to Ray Data with Kafka/Kinesis/Flink sources, new UnboundedData operator and triggers, APIs, configs, tests, and planner integration.
UnboundDatasourcebase and utilities inray.data.datasource.unbound_datasource.KafkaDatasource,KinesisDatasource,FlinkDatasourceunder_internal/datasource/.read_api.py:read_kafka,read_kinesis,read_flink, with trigger parsing and schema handling.UnboundedDataandStreamingTriggerin_internal/logical/operators/unbound_data_operator.py.UnboundedDataOperatorfor micro-batch execution in_internal/execution/operators/unbounded_data_operator.py.plan_unbounded_streaming_opand registers inplanner.py.DataContextwith streaming-related defaults and properties (batch size, trigger interval, retries, backpressure, timeouts).read_operator.py.video_datasource.py.kafka-python,boto3,croniter,requests.Written by Cursor Bugbot for commit 10af494. This will update automatically on new commits. Configure here.