damccorm opened a new pull request, #41685:
URL: https://github.com/apache/beam/pull/41685
Note: this PR was auto-generated by tooling. Before moving it out of draft,
the author has done a full review of the PR, specifically evaluating it on the
following criteria:
- The PR is an appropriate fix for the issue (e.g. we're not changing a test
to avoid a bug)
- The PR is a simple fix to the issue (e.g. we're not adding infra when we
could just modify a test)
- The PR is not covering for other problems (e.g. if we're bumping timeouts,
it is not because we're covering for a performance problem)
Full details of the methodology of generation and review can be found here -
https://docs.google.com/document/d/14lj7ECVov4T4EdwmIzNlWrRGE3lLDMOwX5xUMGzaLoc/edit?usp=sharing
If you have concerns with the PR or with the underlying methodology used to
generate this, please comment below - they will be addressed by the author not
the tooling :)
### Summary
Synchronizes all writes, encoding, flushes, and `close()` on
`TimeBasedBufferingClosableOutputStream` under a single `threading.RLock`,
preventing the background `PeriodicThread` flusher from racing with bundle
output/timer writes.
### Root Cause
Observed in [`Python tests` run
45324222811](https://github.com/apache/beam/actions/runs/45324222811)
(`FnApiRunnerTestWithGrpcAndMultiWorkers.test_reshuffle_after_custom_window`,
crashing with `MemoryError` in `stream.pyx` while decoding `Elements.Data` in
`GroupingBuffer.append`):
`TimeBasedBufferingClosableOutputStream`
(`sdks/python/apache_beam/runners/worker/data_plane.py`) spawns a background
`PeriodicThread` that periodically calls `self.flush()`
(`self._flush_callback(self.get())` followed by `self._clear()`). Previously,
its `_flush_lock` only serialized `flush()` against another `flush()`, leaving
all writers completely unsynchronized:
1. **Mid-element partial flushes / buffer corruption:**
`DataOutputOperation.process()` and `OutputTimer.set()` / `clear()` call
`coder_impl.encode_to_stream(val, output_stream, True)` directly without
holding `_flush_lock`. Because encoding an element performs multiple stream
writes (and in Cython `stream.pyx` may `realloc` the underlying buffer),
`PeriodicThread` can snapshot `self.get()` mid-element and call
`self._clear()`, emitting truncated/corrupted bytes across data-plane chunks.
2. **Silent data loss between `get()` and `_clear()`:**
`SizeBasedBufferingClosableOutputStream.flush()` invokes
`self._flush_callback(self.get())` (which enqueues into `ByteLimitedQueue` and
may yield/block) before calling `self._clear()`. Any element written by the
bundle thread while `_flush_callback` is running is silently wiped when
`_clear()` executes.
3. **`close()` race:** `TimeBasedBufferingClosableOutputStream.close()`
released `_schedule_lock` before calling `super().close()`, allowing
`super().close()` to race with an explicit `flush()`.
## Production Impact
This affects any production Python SDK harness pipeline using time-based
output stream flushing (`--experiments=data_buffer_time_limit_ms=<N>` on
Dataflow, Flink, Spark, Prism, or other portable runners, as well as
`FnApiRunner`'s default `DATA_BUFFER_TIME_LIMIT_MS = 1000` in
`GrpcWorkerHandler`/`EmbeddedGrpcWorkerHandler`). Under concurrent writes and
periodic flushes, pipelines can suffer silent element loss (writes discarded
between `get()` and `_clear()`) or corrupted/truncated element streams causing
downstream decode errors or `MemoryError` crashes.
The default size-based path (`SizeBasedBufferingClosableOutputStream`, when
`data_buffer_time_limit_ms == 0`) does not acquire any lock and keeps the exact
same number of Python calls per element via its inlined `write_encoded` method.
### Fix
- Add `ClosableOutputStream.write_encoded(value_coder_impl, value,
nested=True)` (with a zero-extra-frame override on
`SizeBasedBufferingClosableOutputStream`) and call it from
`DataOutputOperation.process()`, `OutputTimer.set()`, and `OutputTimer.clear()`
in `sdks/python/apache_beam/runners/worker/bundle_processor.py`.
- Replace `_flush_lock` and `_schedule_lock` in
`TimeBasedBufferingClosableOutputStream` with a single reentrant
`self._flush_lock = threading.RLock()` guarding `write`, `write_encoded`,
`maybe_flush`, `flush`, `close` (including `super().close()`), and the periodic
`_flush` callback.
- Add regression tests in
`sdks/python/apache_beam/runners/worker/data_plane_test.py`
(`TimeBasedBufferingClosableOutputStreamTest`) reproducing both mid-element
partial flushes and data loss between `get()` and `_clear()` (verified failing
without the fix and passing with it).
### Verification
- Local:
- `pytest apache_beam/runners/worker/data_plane_test.py
apache_beam/runners/worker/bundle_processor_test.py` (37 passed)
- `pytest apache_beam/runners/portability/fn_api_runner/fn_runner_test.py
-k test_reshuffle_after_custom_window` (7 passed)
- `yapf==0.43.0 --style setup.cfg --diff` clean
- CI: triggering `.github/workflows/python_tests.yml` on this PR branch.
### Verification
- Triggered `.github/workflows/python_tests.yml` workflow run on branch:
[`45701292425`](https://github.com/apache/beam/actions/runs/45701292425)
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]