Skip to content

[Data] Make PandasBlock.size_bytes deterministic - #64393

Merged
bveeramani merged 1 commit into
ray-project:masterfrom
dragongu:fix/pandas_size_bytes_determinism
Jul 7, 2026
Merged

bveeramani merged 1 commit into
ray-project:masterfrom
dragongu:fix/pandas_size_bytes_determinism

Conversation

@dragongu

@dragongu dragongu commented Jun 27, 2026 •

Copy link
Copy Markdown
Contributor

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):

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().

@dragongu
dragongu requested a review from a team as a code owner June 27, 2026 15:13

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Code Review

This pull request ensures that size estimation in PandasBlockAccessor.size_bytes() is deterministic by using a fixed random_state=0 when sampling columns. This prevents issues like silent hangs or data loss during lineage reconstruction. A corresponding unit test was added to verify determinism. The reviewer suggested a performance optimization to bypass sampling when the sample size equals the total size.

@dragongu
dragongu force-pushed the fix/pandas_size_bytes_determinism branch from 4839bbe to 1d3d4ec Compare June 27, 2026 15:22
@dragongu dragongu changed the title [Data] Make PandasBlock.size_bytes deterministic to avoid streaming generator hangs [Data] Make PandasBlock.size_bytes deterministic Jun 27, 2026
@ray-gardener ray-gardener Bot added data Ray Data-related issues community-contribution Contributed by the community labels Jun 27, 2026
PandasBlock.size_bytes estimates the byte size of string/object columns
by sampling up to 200 rows with pandas.DataFrame.sample(n=), which uses
a fresh random seed on each call by default. The estimate is therefore
non-deterministic: two blocks holding identical data can report different
sizes.

OutputBuffer.next uses size_bytes to decide how to split blocks, so this
non-determinism makes a streaming generator task produce a different
number of objects across replay attempts (e.g. lineage reconstruction),
which can hang or silently drop data downstream.

This passes a fixed random_state to sample() so the estimate is
deterministic. When the whole column is sampled (common for blocks under
200 rows), it reads the values directly and skips sample() entirely,
avoiding the permutation/RNG/copy overhead; that path has no randomness
and is trivially deterministic.

Adds a unit test asserting two blocks with identical data report the
same size_bytes.

Signed-off-by: dragongu <[email protected]>
@dragongu
dragongu force-pushed the fix/pandas_size_bytes_determinism branch from 1d3d4ec to ef3b564 Compare July 2, 2026 12:50
@bveeramani
bveeramani enabled auto-merge (squash) July 7, 2026 00:44
@github-actions github-actions Bot added the go add ONLY when ready to merge, run all tests label Jul 7, 2026
@bveeramani
bveeramani merged commit 6faf087 into ray-project:master Jul 7, 2026
4 checks passed
rueian pushed a commit that referenced this pull request Jul 15, 2026
…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; #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 #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]>
400Ping pushed a commit to 400Ping/ray that referenced this pull request Aug 18, 2026
## 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]>
400Ping pushed a commit to 400Ping/ray that referenced this pull request Aug 18, 2026
…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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

community-contribution Contributed by the community data Ray Data-related issues go add ONLY when ready to merge, run all tests

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants