You are viewing a plain text version of this content. The canonical link for it is here.
Posted to github@beam.apache.org by "shunping (via GitHub)" <gi...@apache.org> on 2026/05/09 02:45:17 UTC

[PR] Fix truncating file handle [beam]

shunping opened a new pull request, #38425:
URL: https://github.com/apache/beam/pull/38425

   A few tests in the Python Precommit suite, including `YamlTestingTest::test_create` and `IOTest::test_read_fwf`, `InlinePythonTest::test_line_69`, have been reporting ValueError and AttributeError exceptions during execution (https://github.com/apache/beam/actions/runs/25576871651/job/75086176283). 
   
   The traceback is shwon below:
   ```
     Traceback (most recent call last):
       File "/Users/runner/work/beam/beam/sdks/python/apache_beam/dataframe/io.py", line 587, in flush
         self._underlying.flush()
         ~~~~~~~~~~~~~~~~~~~~~~^^
     ValueError: I/O operation on closed file.
     
     During handling of the above exception, another exception occurred:
     
     Traceback (most recent call last):
       File "/Users/runner/work/beam/beam/sdks/python/target/.tox/py313-macos/lib/python3.13/site-packages/apache_beam/runners/worker/bundle_processor.py", line 235, in process_encoded
         self.output(decoded_value)
         ~~~~~~~~~~~^^^^^^^^^^^^^^^
     AttributeError: '_TruncatingFileHandle' object has no attribute 'close'. Did you mean: 'closed'?
   ```
   
   The issue occurs when `flush()` is called on a `_TruncatingFileHandle` after the underlying file has already been closed, leading to a `ValueError`. This exception then triggers a secondary AttributeError because `_TruncatingFileHandle` lacked a `close()` method
   
   In this PR, we fixed the handling of close and flush operations within `_TruncatingFileHandle`.
   


-- 
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: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Fix truncating file handle [beam]

Posted by "github-actions[bot] (via GitHub)" <gi...@apache.org>.
github-actions[bot] commented on PR #38425:
URL: https://github.com/apache/beam/pull/38425#issuecomment-4546832639

   Assigning reviewers:
   
   R: @claudevdm for label python.
   
   
   Note: If you would like to opt out of this review, comment `assign to next reviewer`.
   
   Available commands:
   - `stop reviewer notifications` - opt out of the automated review tooling
   - `remind me after tests pass` - tag the comment author after tests pass
   - `waiting on author` - shift the attention set back to the author (any comment or push by the author will return the attention set to the reviewers)
   
   The PR bot will only process comments in the main thread (not review comments).


-- 
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: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Fix truncating file handle [beam]

Posted by "shunping (via GitHub)" <gi...@apache.org>.
shunping merged PR #38425:
URL: https://github.com/apache/beam/pull/38425


-- 
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: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Fix truncating file handle [beam]

Posted by "shunping (via GitHub)" <gi...@apache.org>.
shunping commented on code in PR #38425:
URL: https://github.com/apache/beam/pull/38425#discussion_r3212308594


##########
sdks/python/apache_beam/dataframe/io.py:
##########
@@ -584,7 +584,19 @@ def _read(self, size=-1):
     return res
 
   def flush(self):
-    self._underlying.flush()
+    if not self.closed:
+      try:
+        self._underlying.flush()
+      except ValueError:
+        pass
+
+  def close(self):
+    if not self.closed:
+      try:
+        if hasattr(self._underlying, 'close'):
+          self._underlying.close()
+      except Exception:
+        pass

Review Comment:
   Done.



##########
sdks/python/apache_beam/dataframe/io_test.py:
##########
@@ -296,6 +296,27 @@ def test_truncating_filehandle_iter(self):
     self._run_truncating_file_handle_iter_test('aaa b cccccccccccccccccccc')
     self._run_truncating_file_handle_iter_test('aaa b ccccccccccccccccc ')
 
+  def test_truncating_filehandle_flush_on_closed_stream(self):
+    class ClosedFlushingStream(StringIO):
+      def flush(self):
+        if self.closed:
+          raise ValueError("I/O operation on closed file.")
+        super().flush()
+
+    s = 'a b c'
+    tracker = restriction_trackers.OffsetRestrictionTracker(
+        restriction_trackers.OffsetRange(0, len(s)))
+    underlying = ClosedFlushingStream(s)
+    handle = io._TruncatingFileHandle(
+        underlying, tracker, splitter=io._DelimSplitter(' ', 10))
+
+    # Verify that calling flush() when the underlying stream is closed
+    # succeeds without raising ValueError.
+    underlying.close()
+    handle.flush()

Review Comment:
   Done.



-- 
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: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Fix truncating file handle [beam]

Posted by "gemini-code-assist[bot] (via GitHub)" <gi...@apache.org>.
gemini-code-assist[bot] commented on code in PR #38425:
URL: https://github.com/apache/beam/pull/38425#discussion_r3212296562


##########
sdks/python/apache_beam/dataframe/io.py:
##########
@@ -584,7 +584,19 @@ def _read(self, size=-1):
     return res
 
   def flush(self):
-    self._underlying.flush()
+    if not self.closed:
+      try:
+        self._underlying.flush()
+      except ValueError:
+        pass
+
+  def close(self):
+    if not self.closed:
+      try:
+        if hasattr(self._underlying, 'close'):
+          self._underlying.close()
+      except Exception:
+        pass

Review Comment:
   ![medium](https://www.gstatic.com/codereviewagent/medium-priority.svg)
   
   The `close` method uses a broad `except Exception: pass` block, which can suppress unexpected bugs such as `NameError` or `TypeError`. Following PEP 8, it is recommended to catch specific exceptions whenever possible. Since `hasattr` is already used to check for the existence of the `close` method, catching `(OSError, ValueError)` should be sufficient to handle common I/O issues during cleanup while allowing other errors to surface.
   
   ```suggestion
     def close(self):
       if not self.closed and hasattr(self._underlying, 'close'):
         try:
           self._underlying.close()
         except (OSError, ValueError):
           pass
   ```



##########
sdks/python/apache_beam/dataframe/io_test.py:
##########
@@ -296,6 +296,27 @@ def test_truncating_filehandle_iter(self):
     self._run_truncating_file_handle_iter_test('aaa b cccccccccccccccccccc')
     self._run_truncating_file_handle_iter_test('aaa b ccccccccccccccccc ')
 
+  def test_truncating_filehandle_flush_on_closed_stream(self):
+    class ClosedFlushingStream(StringIO):
+      def flush(self):
+        if self.closed:
+          raise ValueError("I/O operation on closed file.")
+        super().flush()
+
+    s = 'a b c'
+    tracker = restriction_trackers.OffsetRestrictionTracker(
+        restriction_trackers.OffsetRange(0, len(s)))
+    underlying = ClosedFlushingStream(s)
+    handle = io._TruncatingFileHandle(
+        underlying, tracker, splitter=io._DelimSplitter(' ', 10))
+
+    # Verify that calling flush() when the underlying stream is closed
+    # succeeds without raising ValueError.
+    underlying.close()
+    handle.flush()

Review Comment:
   ![medium](https://www.gstatic.com/codereviewagent/medium-priority.svg)
   
   The new test case verifies that `flush()` handles closed streams correctly, but it doesn't exercise the newly added `close()` method. Adding a call to `handle.close()` would ensure that the method works as expected and provides coverage for the fix that addresses the `AttributeError` mentioned in the PR description.
   
   ```suggestion
       underlying.close()
       handle.flush()
       handle.close()
   ```



-- 
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: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Fix truncating file handle [beam]

Posted by "shunping (via GitHub)" <gi...@apache.org>.
shunping commented on PR #38425:
URL: https://github.com/apache/beam/pull/38425#issuecomment-4546819857

   assign set of reviewers


-- 
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: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Fix truncating file handle [beam]

Posted by "chamikaramj (via GitHub)" <gi...@apache.org>.
chamikaramj commented on PR #38425:
URL: https://github.com/apache/beam/pull/38425#issuecomment-4597260653

   LGTM. Thanks!


-- 
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: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Fix truncating file handle [beam]

Posted by "codecov[bot] (via GitHub)" <gi...@apache.org>.
codecov[bot] commented on PR #38425:
URL: https://github.com/apache/beam/pull/38425#issuecomment-4411272310

   ## [Codecov](https://app.codecov.io/gh/apache/beam/pull/38425?dropdown=coverage&src=pr&el=h1&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) Report
   :x: Patch coverage is `50.00000%` with `6 lines` in your changes missing coverage. Please review.
   :white_check_mark: Project coverage is 55.75%. Comparing base ([`81828fd`](https://app.codecov.io/gh/apache/beam/commit/81828fd2f0b7aff2d6f6da9f5564394803531cd6?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache)) to head ([`7e4ee0a`](https://app.codecov.io/gh/apache/beam/commit/7e4ee0af9c19c17e8c5739622b312080e26b0c7a?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache)).
   :warning: Report is 1 commits behind head on master.
   
   | [Files with missing lines](https://app.codecov.io/gh/apache/beam/pull/38425?dropdown=coverage&src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | Patch % | Lines |
   |---|---|---|
   | [sdks/python/apache\_beam/dataframe/io.py](https://app.codecov.io/gh/apache/beam/pull/38425?src=pr&el=tree&filepath=sdks%2Fpython%2Fapache_beam%2Fdataframe%2Fio.py&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#diff-c2Rrcy9weXRob24vYXBhY2hlX2JlYW0vZGF0YWZyYW1lL2lvLnB5) | 50.00% | [6 Missing :warning: ](https://app.codecov.io/gh/apache/beam/pull/38425?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) |
   
   <details><summary>Additional details and impacted files</summary>
   
   
   
   ```diff
   @@             Coverage Diff              @@
   ##             master   #38425      +/-   ##
   ============================================
   + Coverage     55.74%   55.75%   +0.01%     
     Complexity     2095     2095              
   ============================================
     Files          1099     1099              
     Lines        172219   172287      +68     
     Branches       1350     1350              
   ============================================
   + Hits          95995    96065      +70     
   + Misses        73829    73827       -2     
     Partials       2395     2395              
   ```
   
   | [Flag](https://app.codecov.io/gh/apache/beam/pull/38425/flags?src=pr&el=flags&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | Coverage Δ | |
   |---|---|---|
   | [python](https://app.codecov.io/gh/apache/beam/pull/38425/flags?src=pr&el=flag&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `79.83% <50.00%> (+0.01%)` | :arrow_up: |
   
   Flags with carried forward coverage won't be shown. [Click here](https://docs.codecov.io/docs/carryforward-flags?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#carryforward-flags-in-the-pull-request-comment) to find out more.
   </details>
   
   [:umbrella: View full report in Codecov by Sentry](https://app.codecov.io/gh/apache/beam/pull/38425?dropdown=coverage&src=pr&el=continue&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache).   
   :loudspeaker: Have feedback on the report? [Share it here](https://about.codecov.io/codecov-pr-comment-feedback/?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache).
   <details><summary> :rocket: New features to boost your workflow: </summary>
   
   - :snowflake: [Test Analytics](https://docs.codecov.com/docs/test-analytics): Detect flaky tests, report on failures, and find test suite problems.
   - :package: [JS Bundle Analysis](https://docs.codecov.com/docs/javascript-bundle-analysis): Save yourself from yourself by tracking and limiting bundle sizes in JS merges.
   </details>


-- 
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: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Fix truncating file handle [beam]

Posted by "gemini-code-assist[bot] (via GitHub)" <gi...@apache.org>.
gemini-code-assist[bot] commented on PR #38425:
URL: https://github.com/apache/beam/pull/38425#issuecomment-4411179035

   ## Summary of Changes
   
   Hello, I'm Gemini Code Assist[^1]! 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!
   
   This pull request addresses stability issues in the Apache Beam Python SDK's `_TruncatingFileHandle` class. By ensuring that file operations are only performed if the underlying stream is open and adding necessary error handling, the changes prevent intermittent crashes during I/O operations that were previously causing failures in the Precommit test suite.
   
   ### Highlights
   
   * **Improved File Handle State Management**: Updated the `closed` property in `_TruncatingFileHandle` to correctly reflect the state of the underlying file object.
   * **Robust Flush and Close Operations**: Added defensive checks to `flush()` and implemented a `close()` method in `_TruncatingFileHandle` to prevent `ValueError` and `AttributeError` exceptions when interacting with already closed files.
   * **Regression Testing**: Added a new test case `test_truncating_filehandle_flush_on_closed_stream` to verify that flushing a closed stream no longer triggers exceptions.
   
   <details>
   <summary><b>New Features</b></summary>
   
   🧠 You can now enable **Memory** (public preview) to help **Gemini Code Assist** learn from your team's feedback. This makes future code reviews more consistent and personalized to your project's style. **Click [here](https://codeassist.google/code-review/login) to enable Memory in your admin console.**
   </details>
   
   <details>
   <summary><b>Using Gemini Code Assist</b></summary>
   <br>
   
   The full guide for Gemini Code Assist can be found on our [documentation page](https://developers.google.com/gemini-code-assist/docs/review-github-code), here are some quick tips.
   
   <b>Invoking Gemini</b>
   
   You can request assistance from Gemini at any point by creating a comment using either `/gemini <command>` or `@gemini-code-assist <command>`. Below is a summary of the supported commands on the current page.
   
   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 pull request comments and review comments.
   Help | `/gemini help` | Displays a list of available commands.
   
   <b>Customization</b>
   
   To customize the 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](https://developers.google.com/gemini-code-assist/docs/customize-gemini-behavior-github).
   
   <b>Limitations & Feedback</b>
   
   Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counterproductive. You can react with :thumbsup: and :thumbsdown: on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for GitHub and other Google products, sign up [here](https://google.qualtrics.com/jfe/form/SV_2cyuGuTWsEw84yG).
   </details>
   
   
   [^1]: Review the [Privacy Notices](https://policies.google.com/privacy), [Generative AI Prohibited Use Policy](https://policies.google.com/terms/generative-ai/use-policy), [Terms of Service](https://policies.google.com/terms), and learn how to configure Gemini Code Assist in GitHub [here](https://developers.google.com/gemini-code-assist/docs/customize-gemini-behavior-github). Gemini can make mistakes, so double check it and [use code with caution](https://support.google.com/legal/answer/13505487).
   


-- 
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: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Fix truncating file handle [beam]

Posted by "github-actions[bot] (via GitHub)" <gi...@apache.org>.
github-actions[bot] commented on PR #38425:
URL: https://github.com/apache/beam/pull/38425#issuecomment-4411651806

   Checks are failing. Will not request review until checks are succeeding. If you'd like to override that behavior, comment `assign set of reviewers`


-- 
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: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org