Repository navigation
[Core] Fail-fast on streaming generator replay object-count mismatch - #64394
Conversation
There was a problem hiding this comment.
Code Review
This pull request introduces a mechanism to detect and fail streaming generator tasks whose replays produce a different number of objects than their initial successful execution, preventing silent hangs or data loss. This is achieved by adding FailStreamingGeneratorReplayIfInconsistent in TaskManager and introducing a new error type STREAMING_GENERATOR_REPLAY_INCONSISTENT. The review feedback suggests moving the inconsistency check to the very beginning of CompletePendingTask to prevent side-effects from inconsistent replays being written to memory before the task is failed. Additionally, it recommends simplifying the method signature by checking the execution count internally and adding defensive checks against empty return objects.
5812a1f to
e139a5a
Compare
e139a5a to
dbc5c23
Compare
dbc5c23 to
9f1b688
Compare
9f1b688 to
5638094
Compare
## Description `PandasBlockAccessor.size_bytes()` estimates string/object column sizes by sampling up to 200 rows via `pandas.DataFrame.sample(n=...)` without a seed, so two blocks holding identical data report different sizes. That estimate drives block splitting in streaming generators, so a re-executed task can emit a different number of objects than the original attempt — which leaves downstream consumers silently hanging or silently dropping data (the companion #64394 fails fast when that mismatch occurs). This PR fixes the sampling non-determinism by passing `random_state=0`, and skips sampling entirely when the column fits in the sample. User UDFs remain responsible for their own determinism. **Symptom.** A streaming generator task re-executed for lineage reconstruction can leave the pipeline silently hanging or silently dropping data, with no error logged. **Root cause.** `PandasBlockAccessor.size_bytes()` estimates string/object columns by sampling up to 200 rows via `pandas.DataFrame.sample(n=...)`. No seed is passed, so each call samples different rows and two blocks holding identical data report different sizes. **How it turns into a bug.** That estimate drives block splitting: 1. `OutputBuffer.next()` calls `size_bytes()` to compute `target_num_rows`, so a task can split the same output into a different number of blocks each time it runs. 2. The first successful attempt pins the end-of-stream index to the object count it produced. 3. On re-execution, a different split produces a different object count: - **fewer** → downstream consumers block on indices that are never produced (silent hang); - **more** → the extras past the pinned end-of-stream index are dropped by `ObjectRefStream::InsertToStream` (silent data loss). **Fix.** Pass `random_state=0` to `sample()`, and skip sampling when the column has fewer than `sample_size` rows. Identical input now always yields the same size estimate. This removes one Ray-internal source of streaming-generator object-count non-determinism; user UDFs remain responsible for their own determinism. **Scope.** Only `PandasBlockAccessor.size_bytes()` is affected — the Arrow equivalent already uses `table.nbytes` and is deterministic. Pandas blocks are produced along several common paths: - a UDF that returns a `pandas.DataFrame` (e.g. `map_batches(fn, batch_format="pandas")`), kept as a pandas block by `BlockAccessor.batch_to_block`; - batches that Arrow cannot convert (object/ragged columns), which fall back to pandas blocks; - `split_repartition` preserving a pandas input schema; and - the built-in preprocessors (`encoder`, `vectorizer`, `imputer`). On released branches these paths default to pandas, so the bug is broadly reachable. On `master`, #61733 added a default that converts many UDF outputs to Arrow, but the fallback and pandas-schema paths above still build pandas blocks. ## Related issues None. ## Additional information **Reproduction** (before this PR, the two printed sizes frequently differ): ```python import pandas as pd from ray.data._internal.pandas_block import PandasBlockAccessor data = [f"str_{i}" for i in range(10_000)] b1 = pd.DataFrame({"col": pd.Series(data, dtype="string")}) b2 = pd.DataFrame({"col": pd.Series(data, dtype="string")}) print(PandasBlockAccessor.for_block(b1).size_bytes()) print(PandasBlockAccessor.for_block(b2).size_bytes()) ``` - **Test**: added `TestSizeBytes.test_deterministic_across_blocks`, asserting that two blocks holding identical data report the same `size_bytes()`. Signed-off-by: dragongu <[email protected]>
fc8d038 to
6500aa3
Compare
6500aa3 to
56d26cd
Compare
A streaming generator task that is replayed (e.g. for lineage reconstruction) after its first successful attempt can produce a different number of objects if the generator output is non-deterministic. Downstream consumers were already created against the original object count, so a replay with fewer objects hangs them on indices that are never produced, and a replay with more objects silently drops the extras beyond the pinned EOF. Detect the mismatch at the start of CompletePendingTask, before any return object is written to the store, and fail the task with a new STREAMING_GENERATOR_REPLAY_INCONSISTENT error type so the failure propagates through lineage instead of silently hanging or dropping data. Adds C++ unit tests covering fewer/more/same object counts on replay. Signed-off-by: dragongu <[email protected]>
56d26cd to
6437e4a
Compare
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes using default effort and found 1 potential issue.
Reviewed by Cursor Bugbot for commit 6437e4a. Configure here.
Signed-off-by: dragongu <[email protected]>
6437e4a to
6ea48d0
Compare
## Description `PandasBlockAccessor.size_bytes()` estimates string/object column sizes by sampling up to 200 rows via `pandas.DataFrame.sample(n=...)` without a seed, so two blocks holding identical data report different sizes. That estimate drives block splitting in streaming generators, so a re-executed task can emit a different number of objects than the original attempt — which leaves downstream consumers silently hanging or silently dropping data (the companion ray-project#64394 fails fast when that mismatch occurs). This PR fixes the sampling non-determinism by passing `random_state=0`, and skips sampling entirely when the column fits in the sample. User UDFs remain responsible for their own determinism. **Symptom.** A streaming generator task re-executed for lineage reconstruction can leave the pipeline silently hanging or silently dropping data, with no error logged. **Root cause.** `PandasBlockAccessor.size_bytes()` estimates string/object columns by sampling up to 200 rows via `pandas.DataFrame.sample(n=...)`. No seed is passed, so each call samples different rows and two blocks holding identical data report different sizes. **How it turns into a bug.** That estimate drives block splitting: 1. `OutputBuffer.next()` calls `size_bytes()` to compute `target_num_rows`, so a task can split the same output into a different number of blocks each time it runs. 2. The first successful attempt pins the end-of-stream index to the object count it produced. 3. On re-execution, a different split produces a different object count: - **fewer** → downstream consumers block on indices that are never produced (silent hang); - **more** → the extras past the pinned end-of-stream index are dropped by `ObjectRefStream::InsertToStream` (silent data loss). **Fix.** Pass `random_state=0` to `sample()`, and skip sampling when the column has fewer than `sample_size` rows. Identical input now always yields the same size estimate. This removes one Ray-internal source of streaming-generator object-count non-determinism; user UDFs remain responsible for their own determinism. **Scope.** Only `PandasBlockAccessor.size_bytes()` is affected — the Arrow equivalent already uses `table.nbytes` and is deterministic. Pandas blocks are produced along several common paths: - a UDF that returns a `pandas.DataFrame` (e.g. `map_batches(fn, batch_format="pandas")`), kept as a pandas block by `BlockAccessor.batch_to_block`; - batches that Arrow cannot convert (object/ragged columns), which fall back to pandas blocks; - `split_repartition` preserving a pandas input schema; and - the built-in preprocessors (`encoder`, `vectorizer`, `imputer`). On released branches these paths default to pandas, so the bug is broadly reachable. On `master`, ray-project#61733 added a default that converts many UDF outputs to Arrow, but the fallback and pandas-schema paths above still build pandas blocks. ## Related issues None. ## Additional information **Reproduction** (before this PR, the two printed sizes frequently differ): ```python import pandas as pd from ray.data._internal.pandas_block import PandasBlockAccessor data = [f"str_{i}" for i in range(10_000)] b1 = pd.DataFrame({"col": pd.Series(data, dtype="string")}) b2 = pd.DataFrame({"col": pd.Series(data, dtype="string")}) print(PandasBlockAccessor.for_block(b1).size_bytes()) print(PandasBlockAccessor.for_block(b2).size_bytes()) ``` - **Test**: added `TestSizeBytes.test_deterministic_across_blocks`, asserting that two blocks holding identical data report the same `size_bytes()`. Signed-off-by: dragongu <[email protected]> Signed-off-by: 400Ping <[email protected]>
…ay-project#64394) ## Description When a streaming generator task's replay emits a different number of objects than the original successful attempt, downstream consumers break — fewer objects leaves the pipeline silently hanging (the scenario we hit in production), and more objects silently drops data past the pinned end-of-stream index (theoretical). Nothing detects this mismatch today. This PR fails the task fast with a new `STREAMING_GENERATOR_REPLAY_INCONSISTENT` error so the failure propagates through lineage to downstream consumers instead. The underlying object-count non-determinism is not fixed here; ray-project#64393 removes one Ray-internal source, and a future opt-in `rows_per_block` parameter would let users with unstable UDFs make the count deterministic. **Symptom.** We hit this on an elastic-resource pipeline (worker pods can be preempted at any time) running `read_parquet → tokenize → predict → write_parquet`. The job occasionally hung: one last `predict` task sat in `PENDING_ARGS_AVAIL` for 5h+ with no error logged, blocked on object 12 from an upstream `tokenize` task that was never produced. **Root cause.** A worker preemption had triggered lineage reconstruction of that `tokenize` task — but the replay produced only 11 objects instead of the original 12, so object 12 was never created. We added logging in production to confirm this is systematic, not a one-off. For the same task, two attempts received identical input (`in_rows`/`in_bytes` equal) and produced an identical *row* count, yet emitted a different number of objects (one per output block): ``` Task 377d5b47 in_rows=8,510 in_bytes=332,299,291 (identical across attempts) attempt 1 (pid=428): out_blocks=3 out_rows=8,510 out_bytes=1,947,213,121 attempt 2 (pid=652): out_blocks=4 out_rows=8,510 out_bytes=1,520,930,614 → out_blocks 3 → 4; out_bytes estimate drifted ~22% (228KB/row → 179KB/row) Task 5668fd1c in_rows=9,330 in_bytes=383,047,785 (identical across attempts) attempt 1 (pid=307): out_blocks=5 out_rows=9,330 out_bytes=2,284,886,568 attempt 2 (pid=12772): out_blocks=4 out_rows=9,330 out_bytes=2,388,146,403 → out_blocks 5 → 4; out_bytes estimate drifted ~4.5% (245KB/row → 256KB/row) ``` `out_rows` is identical across attempts but `out_blocks` is not — a replay genuinely produces a different object count. A task's object count is non-deterministic: block boundaries drift across attempts (see *Why the object count drifts* below), so a replay can emit fewer or more objects than the original successful attempt. Downstream consumers were created against the original count: - **fewer** → the consumer blocks on stream indices that are never produced (the scenario we hit); - **more** → the extras past the pinned end-of-stream index are silently dropped by `ObjectRefStream::InsertToStream`. Why this goes undetected: the first successful execution pins the stream's end-of-stream index (EOF), `MarkEndOfStream` early-returns afterward so EOF can never move, and `CompletePendingTask` only re-checks replays that fail with an application error — a normally-completing replay with a different count falls through unhandled. **Why the object count drifts.** A streaming generator yields one object per *output block*, and `OutputBuffer.next()` cuts a new block once accumulated rows reach `target_num_rows` — a value derived from `size_bytes()`. The object count therefore tracks the running size estimate rather than the input, so anything that changes that estimate or the data across attempts shifts the boundaries and changes the count: - a non-deterministic `size_bytes()` estimate (e.g. `PandasBlock.size_bytes` sampling without a fixed seed — addressed in [Data] Make PandasBlock.size_bytes deterministic ray-project#64393); - a UDF whose output is unstable across runs — the same input produces slightly different results across attempts (nondeterministic ordering, floating-point jitter, or wall-clock/random-dependent content), shifting the block boundaries. **Fix.** This PR surfaces the mismatch loudly: detect it in `CompletePendingTask` and fail the task with a new `STREAMING_GENERATOR_REPLAY_INCONSISTENT` error type, so the failure propagates through lineage to downstream tasks instead of leaving the pipeline stuck or dropping data silently. The behavior change is strictly hang/silent-loss → explicit error; no caller relies on the old silent behavior. **Implementation notes.** - Detection runs in a new `FailStreamingGeneratorReplayIfInconsistent` helper called early in `CompletePendingTask` — *before* any return object is written to the store (so downstream consumers can't observe the inconsistent objects before the failure propagates) and *before* `SetTaskStatus(FINISHED)` (`FailPendingTask` `RAY_CHECK`s `IsPending()`). - `expected_count` comes from `spec.NumStreamingGeneratorReturns()` (recorded on the first successful attempt); `actual_count` is `reply.streaming_generator_return_ids_size()`. - Both the fewer- and more-objects cases fail the task: either way the stream is already inconsistent with what downstream consumers were created against. - Known limitation: a first attempt that yields *zero* objects does not record a count, so a replay yielding a non-zero count is not flagged. This cannot hang (the stream's EOF is pinned to 0, so consumers finish immediately); detecting it would require tracking "count recorded" separately and is left out of scope here. ## Related issues None. ## Additional information **Tests.** Adds C++ unit tests in `task_manager_test.cc` that drive `CompletePendingTask` with controlled object counts — the deterministic repro of the bug: - fewer objects on replay → task fails with `STREAMING_GENERATOR_REPLAY_INCONSISTENT`; - more objects on replay → task fails with the same error; - same count → completes normally (no false positive). **End-to-end illustration.** Requires a dev build (`PYTHONPATH=$(pwd)/python python repro.py`). Without the fix, hangs on `refs[2]`; with the fix, fails fast with `produced 2 objects, expected 3`. ```python import numpy as np import ray from ray.cluster_utils import Cluster cluster = Cluster() cluster.add_node( num_cpus=0, resources={"head": 1}, _system_config={"max_direct_call_object_size": 100}, enable_object_reconstruction=True, ) ray.init(address=cluster.address) worker = cluster.add_node(num_cpus=1, resources={"worker": 1}) cluster.wait_for_nodes() @ray.remote(num_cpus=0, resources={"head": 0.01}) class AttemptCounter: def __init__(self): self.n = 0 def next(self): self.n += 1 return self.n AttemptCounter.options(name="counter", lifetime="detached").remote() @ray.remote(num_returns="streaming", resources={"worker": 1}, max_retries=-1) def gen(): attempt = ray.get(ray.get_actor("counter").next.remote()) num_objects = 3 if attempt == 1 else 2 for i in range(num_objects): yield np.zeros(1024, dtype=np.uint8) + i gen_ref = gen.remote() refs = list(gen_ref) print(f"first attempt produced {len(refs)} objects") del gen_ref cluster.remove_node(worker, allow_graceful=False) cluster.add_node(num_cpus=1, resources={"worker": 1}) cluster.wait_for_nodes() for i, ref in enumerate(refs): print(f"ray.get(refs[{i}])...", end=" ") val = ray.get(ref, timeout=30) print(f"ok, shape={val.shape}") ``` --------- Signed-off-by: dragongu <[email protected]> Signed-off-by: 400Ping <[email protected]>

Description
When a streaming generator task's replay emits a different number of objects than the original successful attempt, downstream consumers break — fewer objects leaves the pipeline silently hanging (the scenario we hit in production), and more objects silently drops data past the pinned end-of-stream index (theoretical). Nothing detects this mismatch today. This PR fails the task fast with a new
STREAMING_GENERATOR_REPLAY_INCONSISTENTerror so the failure propagates through lineage to downstream consumers instead. The underlying object-count non-determinism is not fixed here; #64393 removes one Ray-internal source, and a future opt-inrows_per_blockparameter would let users with unstable UDFs make the count deterministic.Symptom. We hit this on an elastic-resource pipeline (worker pods can be preempted at any time) running
read_parquet → tokenize → predict → write_parquet. The job occasionally hung: one lastpredicttask sat inPENDING_ARGS_AVAILfor 5h+ with no error logged, blocked on object 12 from an upstreamtokenizetask that was never produced.Root cause. A worker preemption had triggered lineage reconstruction of that
tokenizetask — but the replay produced only 11 objects instead of the original 12, so object 12 was never created.We added logging in production to confirm this is systematic, not a one-off. For the same task, two attempts received identical input (
in_rows/in_bytesequal) and produced an identical row count, yet emitted a different number of objects (one per output block):out_rowsis identical across attempts butout_blocksis not — a replay genuinely produces a different object count.A task's object count is non-deterministic: block boundaries drift across attempts (see Why the object count drifts below), so a replay can emit fewer or more objects than the original successful attempt. Downstream consumers were created against the original count:
ObjectRefStream::InsertToStream.Why this goes undetected: the first successful execution pins the stream's end-of-stream index (EOF),
MarkEndOfStreamearly-returns afterward so EOF can never move, andCompletePendingTaskonly re-checks replays that fail with an application error — a normally-completing replay with a different count falls through unhandled.Why the object count drifts. A streaming generator yields one object per output block, and
OutputBuffer.next()cuts a new block once accumulated rows reachtarget_num_rows— a value derived fromsize_bytes(). The object count therefore tracks the running size estimate rather than the input, so anything that changes that estimate or the data across attempts shifts the boundaries and changes the count:size_bytes()estimate (e.g.PandasBlock.size_bytessampling without a fixed seed — addressed in [Data] Make PandasBlock.size_bytes deterministic [Data] Make PandasBlock.size_bytes deterministic #64393);Fix. This PR surfaces the mismatch loudly: detect it in
CompletePendingTaskand fail the task with a newSTREAMING_GENERATOR_REPLAY_INCONSISTENTerror type, so the failure propagates through lineage to downstream tasks instead of leaving the pipeline stuck or dropping data silently. The behavior change is strictly hang/silent-loss → explicit error; no caller relies on the old silent behavior.Implementation notes.
FailStreamingGeneratorReplayIfInconsistenthelper called early inCompletePendingTask— before any return object is written to the store (so downstream consumers can't observe the inconsistent objects before the failure propagates) and beforeSetTaskStatus(FINISHED)(FailPendingTaskRAY_CHECKsIsPending()).expected_countcomes fromspec.NumStreamingGeneratorReturns()(recorded on the first successful attempt);actual_countisreply.streaming_generator_return_ids_size().Related issues
None.
Additional information
Tests. Adds C++ unit tests in
task_manager_test.ccthat driveCompletePendingTaskwith controlled object counts — the deterministic repro of the bug:STREAMING_GENERATOR_REPLAY_INCONSISTENT;End-to-end illustration. Requires a dev build (
PYTHONPATH=$(pwd)/python python repro.py). Without the fix, hangs onrefs[2]; with the fix, fails fast withproduced 2 objects, expected 3.