You are viewing a plain text version of this content. The canonical link for it is here.
Posted to github@beam.apache.org by "razvanculea (via GitHub)" <gi...@apache.org> on 2025/04/29 13:11:37 UTC

[PR] unbounded PCollections writes to files support in iobase derived IOs: AvroIO, ParquetIO , TextIO, TFRecordIO [beam]

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

   iobase patch for writing unbounded PColl sources.
   Implement unbounded PCollections writes to files support in iobase derived IOs:  AvroIO, ParquetIO , TextIO, TFRecordIO
   Tests for streming PCollections writes to files in AvroIO, ParquetIO , TextIO, TFRecordIO
   
   ------------------------
   
   To check the build health, please visit [https://github.com/apache/beam/blob/master/.test-infra/BUILD_STATUS.md](https://github.com/apache/beam/blob/master/.test-infra/BUILD_STATUS.md)
   
   GitHub Actions Tests Status (on master branch)
   ------------------------------------------------------------------------------------------------
   [![Build python source distribution and wheels](https://github.com/apache/beam/actions/workflows/build_wheels.yml/badge.svg?event=schedule&&?branch=master)](https://github.com/apache/beam/actions?query=workflow%3A%22Build+python+source+distribution+and+wheels%22+branch%3Amaster+event%3Aschedule)
   [![Python tests](https://github.com/apache/beam/actions/workflows/python_tests.yml/badge.svg?event=schedule&&?branch=master)](https://github.com/apache/beam/actions?query=workflow%3A%22Python+Tests%22+branch%3Amaster+event%3Aschedule)
   [![Java tests](https://github.com/apache/beam/actions/workflows/java_tests.yml/badge.svg?event=schedule&&?branch=master)](https://github.com/apache/beam/actions?query=workflow%3A%22Java+Tests%22+branch%3Amaster+event%3Aschedule)
   [![Go tests](https://github.com/apache/beam/actions/workflows/go_tests.yml/badge.svg?event=schedule&&?branch=master)](https://github.com/apache/beam/actions?query=workflow%3A%22Go+tests%22+branch%3Amaster+event%3Aschedule)
   
   See [CI.md](https://github.com/apache/beam/blob/master/CI.md) for more information about GitHub Actions CI or the [workflows README](https://github.com/apache/beam/blob/master/.github/workflows/README.md) to see a list of phrases to trigger workflows.
   


-- 
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] unbounded PCollections writes to files support in iobase derived IOs: AvroIO, ParquetIO , TextIO, TFRecordIO [beam]

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

   Reminder, please take a look at this pr: @jrmccluskey 


-- 
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] unbounded PCollections writes to files support in iobase derived IOs: AvroIO, ParquetIO , TextIO, TFRecordIO [beam]

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


##########
sdks/python/apache_beam/io/iobase.py:
##########
@@ -1235,10 +1430,20 @@ def _finalize_write(
         writer = sink.open_writer(init_result, str(uuid.uuid4()))
         extra_shards.append(writer.close())
   outputs = sink.finalize_write(
-      init_result, write_results + extra_shards, pre_finalize_results)
+      init_result, write_results + extra_shards, pre_finalize_results, w)
+  outputs = list(outputs)
+  _LOGGER.info("*** _finalize_write outputs %s",outputs)
   if outputs:
-    return (
-        window.TimestampedValue(v, timestamp.MAX_TIMESTAMP) for v in outputs)
+    if not isinstance(w, window.GlobalWindow):
+      #handle windowed finalize
+      yield (
+          window.TimestampedValue(v, 
+              timestamp=self.window.start,
+              windows=[w]
+            ) for v in outputs)
+    else:
+      return (
+          window.TimestampedValue(v, timestamp.MAX_TIMESTAMP) for v in outputs)

Review Comment:
   The constructor of `TimestampedValue` has no argument `windows` afaik and you likely want to shift these resulting elements to the window's end time.
   ```suggestion
         return (
             window.TimestampedValue(v, w.end()) for v in outputs)
   ```



-- 
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] unbounded PCollections writes to files support in iobase derived IOs: AvroIO, ParquetIO , TextIO, TFRecordIO [beam]

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


##########
sdks/python/apache_beam/io/iobase.py:
##########
@@ -1127,47 +1130,155 @@ def __init__(self, sink: Sink) -> None:
     self.sink = sink
 
   def expand(self, pcoll):
-    do_once = pcoll.pipeline | 'DoOnce' >> core.Create([None])
-    init_result_coll = do_once | 'InitializeWrite' >> core.Map(
-        lambda _, sink: sink.initialize_write(), self.sink)
+    if (pcoll.is_bounded):
+      do_once = pcoll.pipeline | 'DoOnce' >> core.Create([None])
+      init_result_coll = do_once | 'InitializeWrite' >> core.Map(
+          lambda _, sink: sink.initialize_write(), self.sink)
     if getattr(self.sink, 'num_shards', 0):
       min_shards = self.sink.num_shards
-      if min_shards == 1:
-        keyed_pcoll = pcoll | core.Map(lambda x: (None, x))
-      else:
-        keyed_pcoll = pcoll | core.ParDo(_RoundRobinKeyFn(), count=min_shards)
-      write_result_coll = (
+      
+      if (pcoll.is_bounded):
+        if min_shards == 1:
+          keyed_pcoll = pcoll | core.Map(lambda x: (None, x))
+        else:
+          keyed_pcoll = pcoll | core.ParDo(_RoundRobinKeyFn(), count=min_shards)
+        write_result_coll = (
+            keyed_pcoll
+            | core.WindowInto(window.GlobalWindows())
+            | core.GroupByKey()
+            | 'WriteBundles' >> core.ParDo(
+                _WriteKeyedBundleDoFn(self.sink), AsSingleton(init_result_coll)))
+      else: #unbounded PCollection needes to be written per window
+        if isinstance(pcoll.windowing.windowfn, window.GlobalWindows):
+          widowed_pcoll = (
+            pcoll
+              | core.WindowInto(window.FixedWindows(self.sink.triggering_frequency),
+                                trigger=beam.transforms.trigger.AfterWatermark(),
+                                accumulation_mode=beam.transforms.trigger.AccumulationMode.DISCARDING,
+                                allowed_lateness=beam.utils.timestamp.Duration(seconds=0))
+          )
+        else: #keep user windowing
+          widowed_pcoll = pcoll
+        if self.sink.convert_fn is not None:
+          widowed_pcoll = widowed_pcoll | core.ParDo(self.sink.convert_fn)
+        if min_shards == 1:
+          keyed_pcoll = widowed_pcoll | core.Map(lambda x: (None, x))
+        else:
+          keyed_pcoll = widowed_pcoll | core.ParDo(_RoundRobinKeyFn(), count=min_shards)
+        init_result_window_coll = (
           keyed_pcoll
-          | core.WindowInto(window.GlobalWindows())
-          | core.GroupByKey()
-          | 'WriteBundles' >> core.ParDo(
-              _WriteKeyedBundleDoFn(self.sink), AsSingleton(init_result_coll)))
+            | 'Pair init' >> core.Map(lambda x: (None, x))
+            | 'Pair init gbk' >> core.GroupByKey()
+            | 'InitializeWindowedWrite' >> core.Map(
+              lambda _, sink: sink.initialize_write(), self.sink)
+            #| 'LogElements init_result_window_coll' >> LogElements(prefix="init_result_window_coll :",with_window=True,with_timestamp=True,level=logging.INFO)
+        )
+        
+        write_result_coll = (
+          keyed_pcoll
+            | 'Group by random key' >> core.GroupByKey()
+            #| 'LogElements before WriteWindowedBundles' >> LogElements(prefix="before WriteWindowedBundles :",with_window=True,with_timestamp=True,level=logging.INFO)
+            | 'WriteWindowedBundles' >> core.ParDo(
+                _WriteWindowedBundleDoFn(sink=self.sink,per_key=True), 
+                AsSingleton(init_result_window_coll))
+            #| 'LogElements' >> LogElements(prefix="after WriteWindowedBundles :",with_window=True,with_timestamp=True,level=logging.INFO)
+            | 'Pair' >> core.Map(lambda x: (None, x))
+            | core.GroupByKey()
+            | 'Extract' >> core.Map(lambda x: x[1])
+        )
+        pre_finalized_write_result_coll = (
+          write_result_coll 
+          | 'PreFinalize' >> core.ParDo(
+                _PreFinalizeWindowedBundleDoFn(self.sink), AsSingleton(init_result_window_coll))
+        )
+        finalized_write_result_coll = (
+          pre_finalized_write_result_coll 
+          #| 'LogElements pre_finalized_write_result_coll' >> LogElements(prefix="pre_finalized_write_result_coll :",with_window=True,with_timestamp=True,level=logging.INFO)
+          | 'FinalizeWrite' >> core.FlatMap(
+              _finalize_write,
+              self.sink,
+              AsSingleton(init_result_window_coll),
+              AsSingleton(write_result_coll),
+              min_shards,
+              AsIter(pre_finalized_write_result_coll)
+            ).with_output_types(str)
+        )
+        return finalized_write_result_coll
     else:
+      _LOGGER.info("*** WriteImpl min_shards undef so it's 1, and we write per Bundle")
       min_shards = 1
-      write_result_coll = (
+      if (pcoll.is_bounded):
+        write_result_coll = (
+            pcoll
+            | core.WindowInto(window.GlobalWindows())
+            | 'WriteBundles' >> core.ParDo(
+                _WriteBundleDoFn(self.sink), AsSingleton(init_result_coll))
+            | 'Pair' >> core.Map(lambda x: (None, x))
+            | core.GroupByKey()
+            | 'Extract' >> core.FlatMap(lambda x: x[1]))
+      else: #unbounded PCollection needes to be written per window
+        widowed_pcoll = (
           pcoll
-          | core.WindowInto(window.GlobalWindows())
-          | 'WriteBundles' >> core.ParDo(
-              _WriteBundleDoFn(self.sink), AsSingleton(init_result_coll))
-          | 'Pair' >> core.Map(lambda x: (None, x))
-          | core.GroupByKey()
-          | 'Extract' >> core.FlatMap(lambda x: x[1]))
+            | core.WindowInto(window.FixedWindows(self.sink.triggering_frequency),
+                              trigger=beam.transforms.trigger.AfterWatermark(),
+                              accumulation_mode=beam.transforms.trigger.AccumulationMode.DISCARDING,
+                              allowed_lateness=beam.utils.timestamp.Duration(seconds=0))
+        )
+        init_result_window_coll = (
+          widowed_pcoll
+            | 'Pair init' >> core.Map(lambda x: (None, x))
+            | 'Pair init gbk' >> core.GroupByKey()
+            | 'InitializeWindowedWrite' >> core.Map(
+              lambda _, sink: sink.initialize_write(), self.sink)
+        )
+        if self.sink.convert_fn is not None:
+          widowed_pcoll = widowed_pcoll | core.ParDo(self.sink.convert_fn)
+        write_result_coll = (
+          widowed_pcoll
+            | 'WriteWindowedBundles' >> core.ParDo(
+                _WriteWindowedBundleDoFn(self.sink), AsSingleton(init_result_window_coll))
+            | 'LogElements' >> LogElements(prefix="after WriteWindowedBundles :",with_window=True,with_timestamp=True,level=logging.INFO)
+            | 'Pair' >> core.Map(lambda x: (None, x))
+            | core.GroupByKey()
+            | 'Extract' >> core.Map(lambda x: x[1])
+        )
+        pre_finalized_write_result_coll = (
+          write_result_coll 
+          | 'PreFinalize' >> core.ParDo(
+                _PreFinalizeWindowedBundleDoFn(self.sink), AsSingleton(init_result_window_coll))
+        )
+        finalized_write_result_coll = (
+          pre_finalized_write_result_coll 
+          | 'LogElements 2' >> LogElements(prefix="before finalize :",with_window=True,with_timestamp=True,level=logging.INFO)
+          | 'FinalizeWrite' >> core.FlatMap(
+              _finalize_write,
+              self.sink,
+              AsSingleton(init_result_window_coll),
+              AsSingleton(write_result_coll),
+              min_shards,
+              AsIter(pre_finalized_write_result_coll)
+            ).with_output_types(str)
+        )
+        return finalized_write_result_coll
     # PreFinalize should run before FinalizeWrite, and the two should not be
     # fused.
-    pre_finalize_coll = (
-        do_once
-        | 'PreFinalize' >> core.FlatMap(
-            _pre_finalize,
-            self.sink,
-            AsSingleton(init_result_coll),
-            AsIter(write_result_coll)))
-    return do_once | 'FinalizeWrite' >> core.FlatMap(
-        _finalize_write,
-        self.sink,
-        AsSingleton(init_result_coll),
-        AsIter(write_result_coll),
-        min_shards,
-        AsSingleton(pre_finalize_coll)).with_output_types(str)
+    if (pcoll.is_bounded):
+      pre_finalize_coll = (
+          do_once
+          | 'PreFinalize' >> core.FlatMap(
+              _pre_finalize,
+              self.sink,
+              AsSingleton(init_result_coll),
+              AsIter(write_result_coll)))
+      return (do_once | 'FinalizeWrite' >> core.FlatMap(
+          _finalize_write,
+          self.sink,
+          AsSingleton(init_result_coll),
+          AsIter(write_result_coll),
+          min_shards,
+          AsSingleton(pre_finalize_coll)).with_output_types(str)
+          | 'LogElements after FinalizeWrite' >> LogElements(prefix='after FinalizeWrite ', with_window=False,level=logging.INFO) 
+      )

Review Comment:
   Remove
   ```suggestion
   ```



-- 
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] unbounded PCollections writes to files support in iobase derived IOs: AvroIO, ParquetIO , TextIO, TFRecordIO [beam]

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

   Assigning reviewers. If you would like to opt out of this review, comment `assign to next reviewer`:
   
   R: @shunping for label python.
   
   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] unbounded PCollections writes to files support in iobase derived IOs: AvroIO, ParquetIO , TextIO, TFRecordIO [beam]

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

   ## [Codecov](https://app.codecov.io/gh/apache/beam/pull/34777?dropdown=coverage&src=pr&el=h1&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) Report
   Attention: Patch coverage is `88.55422%` with `19 lines` in your changes missing coverage. Please review.
   > Project coverage is 56.48%. Comparing base [(`b46a636`)](https://app.codecov.io/gh/apache/beam/commit/b46a6361d2b758f5779ba711d4a41c3fb9327f36?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) to head [(`1bd138c`)](https://app.codecov.io/gh/apache/beam/commit/1bd138c3016dc8dcea8548dd83160a86ae140692?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache).
   > Report is 6 commits behind head on master.
   
   | [Files with missing lines](https://app.codecov.io/gh/apache/beam/pull/34777?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/io/iobase.py](https://app.codecov.io/gh/apache/beam/pull/34777?src=pr&el=tree&filepath=sdks%2Fpython%2Fapache_beam%2Fio%2Fiobase.py&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#diff-c2Rrcy9weXRob24vYXBhY2hlX2JlYW0vaW8vaW9iYXNlLnB5) | 83.52% | [14 Missing :warning: ](https://app.codecov.io/gh/apache/beam/pull/34777?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) |
   | [sdks/python/apache\_beam/io/parquetio.py](https://app.codecov.io/gh/apache/beam/pull/34777?src=pr&el=tree&filepath=sdks%2Fpython%2Fapache_beam%2Fio%2Fparquetio.py&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#diff-c2Rrcy9weXRob24vYXBhY2hlX2JlYW0vaW8vcGFycXVldGlvLnB5) | 84.21% | [3 Missing :warning: ](https://app.codecov.io/gh/apache/beam/pull/34777?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) |
   | [sdks/python/apache\_beam/io/filebasedsink.py](https://app.codecov.io/gh/apache/beam/pull/34777?src=pr&el=tree&filepath=sdks%2Fpython%2Fapache_beam%2Fio%2Ffilebasedsink.py&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#diff-c2Rrcy9weXRob24vYXBhY2hlX2JlYW0vaW8vZmlsZWJhc2Vkc2luay5weQ==) | 95.91% | [2 Missing :warning: ](https://app.codecov.io/gh/apache/beam/pull/34777?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   #34777      +/-   ##
   ============================================
   + Coverage     56.46%   56.48%   +0.01%     
     Complexity     3289     3289              
   ============================================
     Files          1181     1181              
     Lines        181455   181543      +88     
     Branches       3399     3392       -7     
   ============================================
   + Hits         102464   102540      +76     
   - Misses        75731    75746      +15     
   + Partials       3260     3257       -3     
   ```
   
   | [Flag](https://app.codecov.io/gh/apache/beam/pull/34777/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/34777/flags?src=pr&el=flag&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `81.12% <88.55%> (+<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/34777?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] unbounded PCollections writes to files support in iobase derived IOs: AvroIO, ParquetIO , TextIO, TFRecordIO [beam]

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

   This PR is related to #34814 and may also fix #25598.


-- 
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] unbounded PCollections writes to files support in iobase derived IOs: AvroIO, ParquetIO , TextIO, TFRecordIO [beam]

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


##########
sdks/python/apache_beam/io/iobase.py:
##########
@@ -1127,47 +1130,155 @@ def __init__(self, sink: Sink) -> None:
     self.sink = sink
 
   def expand(self, pcoll):
-    do_once = pcoll.pipeline | 'DoOnce' >> core.Create([None])
-    init_result_coll = do_once | 'InitializeWrite' >> core.Map(
-        lambda _, sink: sink.initialize_write(), self.sink)
+    if (pcoll.is_bounded):
+      do_once = pcoll.pipeline | 'DoOnce' >> core.Create([None])
+      init_result_coll = do_once | 'InitializeWrite' >> core.Map(
+          lambda _, sink: sink.initialize_write(), self.sink)
     if getattr(self.sink, 'num_shards', 0):
       min_shards = self.sink.num_shards
-      if min_shards == 1:
-        keyed_pcoll = pcoll | core.Map(lambda x: (None, x))
-      else:
-        keyed_pcoll = pcoll | core.ParDo(_RoundRobinKeyFn(), count=min_shards)
-      write_result_coll = (
+      
+      if (pcoll.is_bounded):
+        if min_shards == 1:
+          keyed_pcoll = pcoll | core.Map(lambda x: (None, x))
+        else:
+          keyed_pcoll = pcoll | core.ParDo(_RoundRobinKeyFn(), count=min_shards)
+        write_result_coll = (
+            keyed_pcoll
+            | core.WindowInto(window.GlobalWindows())
+            | core.GroupByKey()
+            | 'WriteBundles' >> core.ParDo(
+                _WriteKeyedBundleDoFn(self.sink), AsSingleton(init_result_coll)))
+      else: #unbounded PCollection needes to be written per window
+        if isinstance(pcoll.windowing.windowfn, window.GlobalWindows):
+          widowed_pcoll = (
+            pcoll
+              | core.WindowInto(window.FixedWindows(self.sink.triggering_frequency),
+                                trigger=beam.transforms.trigger.AfterWatermark(),
+                                accumulation_mode=beam.transforms.trigger.AccumulationMode.DISCARDING,
+                                allowed_lateness=beam.utils.timestamp.Duration(seconds=0))
+          )
+        else: #keep user windowing
+          widowed_pcoll = pcoll
+        if self.sink.convert_fn is not None:
+          widowed_pcoll = widowed_pcoll | core.ParDo(self.sink.convert_fn)
+        if min_shards == 1:
+          keyed_pcoll = widowed_pcoll | core.Map(lambda x: (None, x))
+        else:
+          keyed_pcoll = widowed_pcoll | core.ParDo(_RoundRobinKeyFn(), count=min_shards)
+        init_result_window_coll = (
           keyed_pcoll
-          | core.WindowInto(window.GlobalWindows())
-          | core.GroupByKey()
-          | 'WriteBundles' >> core.ParDo(
-              _WriteKeyedBundleDoFn(self.sink), AsSingleton(init_result_coll)))
+            | 'Pair init' >> core.Map(lambda x: (None, x))
+            | 'Pair init gbk' >> core.GroupByKey()
+            | 'InitializeWindowedWrite' >> core.Map(
+              lambda _, sink: sink.initialize_write(), self.sink)
+            #| 'LogElements init_result_window_coll' >> LogElements(prefix="init_result_window_coll :",with_window=True,with_timestamp=True,level=logging.INFO)
+        )
+        
+        write_result_coll = (
+          keyed_pcoll
+            | 'Group by random key' >> core.GroupByKey()
+            #| 'LogElements before WriteWindowedBundles' >> LogElements(prefix="before WriteWindowedBundles :",with_window=True,with_timestamp=True,level=logging.INFO)
+            | 'WriteWindowedBundles' >> core.ParDo(
+                _WriteWindowedBundleDoFn(sink=self.sink,per_key=True), 
+                AsSingleton(init_result_window_coll))
+            #| 'LogElements' >> LogElements(prefix="after WriteWindowedBundles :",with_window=True,with_timestamp=True,level=logging.INFO)
+            | 'Pair' >> core.Map(lambda x: (None, x))
+            | core.GroupByKey()
+            | 'Extract' >> core.Map(lambda x: x[1])
+        )
+        pre_finalized_write_result_coll = (
+          write_result_coll 
+          | 'PreFinalize' >> core.ParDo(
+                _PreFinalizeWindowedBundleDoFn(self.sink), AsSingleton(init_result_window_coll))
+        )
+        finalized_write_result_coll = (
+          pre_finalized_write_result_coll 
+          #| 'LogElements pre_finalized_write_result_coll' >> LogElements(prefix="pre_finalized_write_result_coll :",with_window=True,with_timestamp=True,level=logging.INFO)
+          | 'FinalizeWrite' >> core.FlatMap(
+              _finalize_write,
+              self.sink,
+              AsSingleton(init_result_window_coll),
+              AsSingleton(write_result_coll),
+              min_shards,
+              AsIter(pre_finalized_write_result_coll)
+            ).with_output_types(str)
+        )
+        return finalized_write_result_coll
     else:
+      _LOGGER.info("*** WriteImpl min_shards undef so it's 1, and we write per Bundle")
       min_shards = 1
-      write_result_coll = (
+      if (pcoll.is_bounded):
+        write_result_coll = (
+            pcoll
+            | core.WindowInto(window.GlobalWindows())
+            | 'WriteBundles' >> core.ParDo(
+                _WriteBundleDoFn(self.sink), AsSingleton(init_result_coll))
+            | 'Pair' >> core.Map(lambda x: (None, x))
+            | core.GroupByKey()
+            | 'Extract' >> core.FlatMap(lambda x: x[1]))
+      else: #unbounded PCollection needes to be written per window
+        widowed_pcoll = (
           pcoll
-          | core.WindowInto(window.GlobalWindows())
-          | 'WriteBundles' >> core.ParDo(
-              _WriteBundleDoFn(self.sink), AsSingleton(init_result_coll))
-          | 'Pair' >> core.Map(lambda x: (None, x))
-          | core.GroupByKey()
-          | 'Extract' >> core.FlatMap(lambda x: x[1]))
+            | core.WindowInto(window.FixedWindows(self.sink.triggering_frequency),
+                              trigger=beam.transforms.trigger.AfterWatermark(),
+                              accumulation_mode=beam.transforms.trigger.AccumulationMode.DISCARDING,
+                              allowed_lateness=beam.utils.timestamp.Duration(seconds=0))
+        )
+        init_result_window_coll = (
+          widowed_pcoll
+            | 'Pair init' >> core.Map(lambda x: (None, x))
+            | 'Pair init gbk' >> core.GroupByKey()
+            | 'InitializeWindowedWrite' >> core.Map(
+              lambda _, sink: sink.initialize_write(), self.sink)
+        )
+        if self.sink.convert_fn is not None:
+          widowed_pcoll = widowed_pcoll | core.ParDo(self.sink.convert_fn)
+        write_result_coll = (
+          widowed_pcoll
+            | 'WriteWindowedBundles' >> core.ParDo(
+                _WriteWindowedBundleDoFn(self.sink), AsSingleton(init_result_window_coll))
+            | 'LogElements' >> LogElements(prefix="after WriteWindowedBundles :",with_window=True,with_timestamp=True,level=logging.INFO)
+            | 'Pair' >> core.Map(lambda x: (None, x))
+            | core.GroupByKey()
+            | 'Extract' >> core.Map(lambda x: x[1])
+        )
+        pre_finalized_write_result_coll = (
+          write_result_coll 
+          | 'PreFinalize' >> core.ParDo(
+                _PreFinalizeWindowedBundleDoFn(self.sink), AsSingleton(init_result_window_coll))
+        )
+        finalized_write_result_coll = (
+          pre_finalized_write_result_coll 
+          | 'LogElements 2' >> LogElements(prefix="before finalize :",with_window=True,with_timestamp=True,level=logging.INFO)
+          | 'FinalizeWrite' >> core.FlatMap(
+              _finalize_write,
+              self.sink,
+              AsSingleton(init_result_window_coll),
+              AsSingleton(write_result_coll),
+              min_shards,
+              AsIter(pre_finalized_write_result_coll)
+            ).with_output_types(str)
+        )
+        return finalized_write_result_coll
     # PreFinalize should run before FinalizeWrite, and the two should not be
     # fused.
-    pre_finalize_coll = (
-        do_once
-        | 'PreFinalize' >> core.FlatMap(
-            _pre_finalize,
-            self.sink,
-            AsSingleton(init_result_coll),
-            AsIter(write_result_coll)))
-    return do_once | 'FinalizeWrite' >> core.FlatMap(
-        _finalize_write,
-        self.sink,
-        AsSingleton(init_result_coll),
-        AsIter(write_result_coll),
-        min_shards,
-        AsSingleton(pre_finalize_coll)).with_output_types(str)
+    if (pcoll.is_bounded):
+      pre_finalize_coll = (
+          do_once
+          | 'PreFinalize' >> core.FlatMap(
+              _pre_finalize,
+              self.sink,
+              AsSingleton(init_result_coll),
+              AsIter(write_result_coll)))
+      return (do_once | 'FinalizeWrite' >> core.FlatMap(
+          _finalize_write,
+          self.sink,
+          AsSingleton(init_result_coll),
+          AsIter(write_result_coll),
+          min_shards,
+          AsSingleton(pre_finalize_coll)).with_output_types(str)
+          | 'LogElements after FinalizeWrite' >> LogElements(prefix='after FinalizeWrite ', with_window=False,level=logging.INFO) 
+      )

Review Comment:
   Looks like debug code?
   ```suggestion
   ```



-- 
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] unbounded PCollections writes to files support in iobase derived IOs: AvroIO, ParquetIO , TextIO, TFRecordIO [beam]

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


##########
sdks/python/apache_beam/io/iobase.py:
##########
@@ -1127,47 +1130,155 @@ def __init__(self, sink: Sink) -> None:
     self.sink = sink
 
   def expand(self, pcoll):
-    do_once = pcoll.pipeline | 'DoOnce' >> core.Create([None])
-    init_result_coll = do_once | 'InitializeWrite' >> core.Map(
-        lambda _, sink: sink.initialize_write(), self.sink)
+    if (pcoll.is_bounded):
+      do_once = pcoll.pipeline | 'DoOnce' >> core.Create([None])
+      init_result_coll = do_once | 'InitializeWrite' >> core.Map(
+          lambda _, sink: sink.initialize_write(), self.sink)
     if getattr(self.sink, 'num_shards', 0):
       min_shards = self.sink.num_shards
-      if min_shards == 1:
-        keyed_pcoll = pcoll | core.Map(lambda x: (None, x))
-      else:
-        keyed_pcoll = pcoll | core.ParDo(_RoundRobinKeyFn(), count=min_shards)
-      write_result_coll = (
+      
+      if (pcoll.is_bounded):
+        if min_shards == 1:
+          keyed_pcoll = pcoll | core.Map(lambda x: (None, x))
+        else:
+          keyed_pcoll = pcoll | core.ParDo(_RoundRobinKeyFn(), count=min_shards)
+        write_result_coll = (
+            keyed_pcoll
+            | core.WindowInto(window.GlobalWindows())
+            | core.GroupByKey()
+            | 'WriteBundles' >> core.ParDo(
+                _WriteKeyedBundleDoFn(self.sink), AsSingleton(init_result_coll)))
+      else: #unbounded PCollection needes to be written per window
+        if isinstance(pcoll.windowing.windowfn, window.GlobalWindows):
+          widowed_pcoll = (
+            pcoll
+              | core.WindowInto(window.FixedWindows(self.sink.triggering_frequency),
+                                trigger=beam.transforms.trigger.AfterWatermark(),
+                                accumulation_mode=beam.transforms.trigger.AccumulationMode.DISCARDING,
+                                allowed_lateness=beam.utils.timestamp.Duration(seconds=0))
+          )
+        else: #keep user windowing
+          widowed_pcoll = pcoll
+        if self.sink.convert_fn is not None:
+          widowed_pcoll = widowed_pcoll | core.ParDo(self.sink.convert_fn)
+        if min_shards == 1:
+          keyed_pcoll = widowed_pcoll | core.Map(lambda x: (None, x))
+        else:
+          keyed_pcoll = widowed_pcoll | core.ParDo(_RoundRobinKeyFn(), count=min_shards)
+        init_result_window_coll = (
           keyed_pcoll
-          | core.WindowInto(window.GlobalWindows())
-          | core.GroupByKey()
-          | 'WriteBundles' >> core.ParDo(
-              _WriteKeyedBundleDoFn(self.sink), AsSingleton(init_result_coll)))
+            | 'Pair init' >> core.Map(lambda x: (None, x))
+            | 'Pair init gbk' >> core.GroupByKey()
+            | 'InitializeWindowedWrite' >> core.Map(
+              lambda _, sink: sink.initialize_write(), self.sink)
+            #| 'LogElements init_result_window_coll' >> LogElements(prefix="init_result_window_coll :",with_window=True,with_timestamp=True,level=logging.INFO)
+        )
+        
+        write_result_coll = (
+          keyed_pcoll
+            | 'Group by random key' >> core.GroupByKey()
+            #| 'LogElements before WriteWindowedBundles' >> LogElements(prefix="before WriteWindowedBundles :",with_window=True,with_timestamp=True,level=logging.INFO)
+            | 'WriteWindowedBundles' >> core.ParDo(
+                _WriteWindowedBundleDoFn(sink=self.sink,per_key=True), 
+                AsSingleton(init_result_window_coll))
+            #| 'LogElements' >> LogElements(prefix="after WriteWindowedBundles :",with_window=True,with_timestamp=True,level=logging.INFO)
+            | 'Pair' >> core.Map(lambda x: (None, x))
+            | core.GroupByKey()
+            | 'Extract' >> core.Map(lambda x: x[1])
+        )
+        pre_finalized_write_result_coll = (
+          write_result_coll 
+          | 'PreFinalize' >> core.ParDo(
+                _PreFinalizeWindowedBundleDoFn(self.sink), AsSingleton(init_result_window_coll))
+        )
+        finalized_write_result_coll = (
+          pre_finalized_write_result_coll 
+          #| 'LogElements pre_finalized_write_result_coll' >> LogElements(prefix="pre_finalized_write_result_coll :",with_window=True,with_timestamp=True,level=logging.INFO)

Review Comment:
   Remove
   ```suggestion
   ```



-- 
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] unbounded PCollections writes to files support in iobase derived IOs: AvroIO, ParquetIO , TextIO, TFRecordIO [beam]

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


##########
sdks/python/apache_beam/io/iobase.py:
##########
@@ -1127,47 +1130,155 @@ def __init__(self, sink: Sink) -> None:
     self.sink = sink
 
   def expand(self, pcoll):
-    do_once = pcoll.pipeline | 'DoOnce' >> core.Create([None])
-    init_result_coll = do_once | 'InitializeWrite' >> core.Map(
-        lambda _, sink: sink.initialize_write(), self.sink)
+    if (pcoll.is_bounded):
+      do_once = pcoll.pipeline | 'DoOnce' >> core.Create([None])
+      init_result_coll = do_once | 'InitializeWrite' >> core.Map(
+          lambda _, sink: sink.initialize_write(), self.sink)
     if getattr(self.sink, 'num_shards', 0):
       min_shards = self.sink.num_shards
-      if min_shards == 1:
-        keyed_pcoll = pcoll | core.Map(lambda x: (None, x))
-      else:
-        keyed_pcoll = pcoll | core.ParDo(_RoundRobinKeyFn(), count=min_shards)
-      write_result_coll = (
+      
+      if (pcoll.is_bounded):
+        if min_shards == 1:
+          keyed_pcoll = pcoll | core.Map(lambda x: (None, x))
+        else:
+          keyed_pcoll = pcoll | core.ParDo(_RoundRobinKeyFn(), count=min_shards)
+        write_result_coll = (
+            keyed_pcoll
+            | core.WindowInto(window.GlobalWindows())
+            | core.GroupByKey()
+            | 'WriteBundles' >> core.ParDo(
+                _WriteKeyedBundleDoFn(self.sink), AsSingleton(init_result_coll)))
+      else: #unbounded PCollection needes to be written per window
+        if isinstance(pcoll.windowing.windowfn, window.GlobalWindows):
+          widowed_pcoll = (
+            pcoll
+              | core.WindowInto(window.FixedWindows(self.sink.triggering_frequency),
+                                trigger=beam.transforms.trigger.AfterWatermark(),
+                                accumulation_mode=beam.transforms.trigger.AccumulationMode.DISCARDING,
+                                allowed_lateness=beam.utils.timestamp.Duration(seconds=0))
+          )
+        else: #keep user windowing
+          widowed_pcoll = pcoll
+        if self.sink.convert_fn is not None:
+          widowed_pcoll = widowed_pcoll | core.ParDo(self.sink.convert_fn)
+        if min_shards == 1:
+          keyed_pcoll = widowed_pcoll | core.Map(lambda x: (None, x))
+        else:
+          keyed_pcoll = widowed_pcoll | core.ParDo(_RoundRobinKeyFn(), count=min_shards)
+        init_result_window_coll = (
           keyed_pcoll
-          | core.WindowInto(window.GlobalWindows())
-          | core.GroupByKey()
-          | 'WriteBundles' >> core.ParDo(
-              _WriteKeyedBundleDoFn(self.sink), AsSingleton(init_result_coll)))
+            | 'Pair init' >> core.Map(lambda x: (None, x))
+            | 'Pair init gbk' >> core.GroupByKey()
+            | 'InitializeWindowedWrite' >> core.Map(
+              lambda _, sink: sink.initialize_write(), self.sink)

Review Comment:
   This doesn't have to depend on the main input, right?
   I'm almost certain a globally windowed side input should suffice.



-- 
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] unbounded PCollections writes to files support in iobase derived IOs: AvroIO, ParquetIO , TextIO, TFRecordIO [beam]

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


##########
sdks/python/apache_beam/io/iobase.py:
##########
@@ -1235,10 +1430,20 @@ def _finalize_write(
         writer = sink.open_writer(init_result, str(uuid.uuid4()))
         extra_shards.append(writer.close())
   outputs = sink.finalize_write(
-      init_result, write_results + extra_shards, pre_finalize_results)
+      init_result, write_results + extra_shards, pre_finalize_results, w)
+  outputs = list(outputs)
+  _LOGGER.info("*** _finalize_write outputs %s",outputs)
   if outputs:
-    return (
-        window.TimestampedValue(v, timestamp.MAX_TIMESTAMP) for v in outputs)
+    if not isinstance(w, window.GlobalWindow):
+      #handle windowed finalize
+      yield (
+          window.TimestampedValue(v, 
+              timestamp=self.window.start,
+              windows=[w]
+            ) for v in outputs)
+    else:
+      return (
+          window.TimestampedValue(v, timestamp.MAX_TIMESTAMP) for v in outputs)

Review Comment:
   The constructor of `TimestampedValue` has no argument `windows` afaik and you likely want to shift these resulting elements to the window's end time.
   ```suggestion
         return (
             window.TimestampedValue(v, w.end) for v in outputs)
   ```



-- 
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] unbounded PCollections writes to files support in iobase derived IOs: AvroIO, ParquetIO , TextIO, TFRecordIO [beam]

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


##########
sdks/python/apache_beam/io/iobase.py:
##########
@@ -1127,47 +1130,155 @@ def __init__(self, sink: Sink) -> None:
     self.sink = sink
 
   def expand(self, pcoll):
-    do_once = pcoll.pipeline | 'DoOnce' >> core.Create([None])
-    init_result_coll = do_once | 'InitializeWrite' >> core.Map(
-        lambda _, sink: sink.initialize_write(), self.sink)
+    if (pcoll.is_bounded):
+      do_once = pcoll.pipeline | 'DoOnce' >> core.Create([None])
+      init_result_coll = do_once | 'InitializeWrite' >> core.Map(
+          lambda _, sink: sink.initialize_write(), self.sink)
     if getattr(self.sink, 'num_shards', 0):
       min_shards = self.sink.num_shards
-      if min_shards == 1:
-        keyed_pcoll = pcoll | core.Map(lambda x: (None, x))
-      else:
-        keyed_pcoll = pcoll | core.ParDo(_RoundRobinKeyFn(), count=min_shards)
-      write_result_coll = (
+      
+      if (pcoll.is_bounded):
+        if min_shards == 1:
+          keyed_pcoll = pcoll | core.Map(lambda x: (None, x))
+        else:
+          keyed_pcoll = pcoll | core.ParDo(_RoundRobinKeyFn(), count=min_shards)
+        write_result_coll = (
+            keyed_pcoll
+            | core.WindowInto(window.GlobalWindows())
+            | core.GroupByKey()
+            | 'WriteBundles' >> core.ParDo(
+                _WriteKeyedBundleDoFn(self.sink), AsSingleton(init_result_coll)))
+      else: #unbounded PCollection needes to be written per window
+        if isinstance(pcoll.windowing.windowfn, window.GlobalWindows):
+          widowed_pcoll = (
+            pcoll
+              | core.WindowInto(window.FixedWindows(self.sink.triggering_frequency),
+                                trigger=beam.transforms.trigger.AfterWatermark(),
+                                accumulation_mode=beam.transforms.trigger.AccumulationMode.DISCARDING,
+                                allowed_lateness=beam.utils.timestamp.Duration(seconds=0))
+          )
+        else: #keep user windowing
+          widowed_pcoll = pcoll
+        if self.sink.convert_fn is not None:
+          widowed_pcoll = widowed_pcoll | core.ParDo(self.sink.convert_fn)
+        if min_shards == 1:
+          keyed_pcoll = widowed_pcoll | core.Map(lambda x: (None, x))
+        else:
+          keyed_pcoll = widowed_pcoll | core.ParDo(_RoundRobinKeyFn(), count=min_shards)
+        init_result_window_coll = (
           keyed_pcoll
-          | core.WindowInto(window.GlobalWindows())
-          | core.GroupByKey()
-          | 'WriteBundles' >> core.ParDo(
-              _WriteKeyedBundleDoFn(self.sink), AsSingleton(init_result_coll)))
+            | 'Pair init' >> core.Map(lambda x: (None, x))
+            | 'Pair init gbk' >> core.GroupByKey()
+            | 'InitializeWindowedWrite' >> core.Map(
+              lambda _, sink: sink.initialize_write(), self.sink)

Review Comment:
   This doesn't have to depend on the main input, right?



-- 
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] unbounded PCollections writes to files support in iobase derived IOs: AvroIO, ParquetIO , TextIO, TFRecordIO [beam]

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

   > > > is this PR tested with DataflowRunner?
   > > 
   > > 
   > > @liferoad i've added the iobase_it_test from PR 34814 and it runs on Dataflow (it's actually using TextIO for write), but i don't have an IT for TextIO/parquetIO/AvroIO/TFRecordIO, I can try to add them, but i can't use TestStream in Dataflow, so i'll need to use PubSub public topics , right ?
   > 
   > > > is this PR tested with DataflowRunner?
   > > 
   > > 
   > > @liferoad i've added the iobase_it_test from PR 34814 and it runs on Dataflow (it's actually using TextIO for write), but i don't have an IT for TextIO/parquetIO/AvroIO/TFRecordIO, I can try to add them, but i can't use TestStream in Dataflow, so i'll need to use PubSub public topics , right ?
   > 
   > I forgot whether periodic impulse can trigger #25598. You could try that. And better add some checks about the output results.
   
   @liferoad, I added an IT in parquetio_it_test.py using PeriodicImpulse and it's working fine on Dataflow
   
   Did not add IT for AvroIO/TFRecordIO because there is no IT at all. I could do like for parquetIO later, if we deem this really a plus.


-- 
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] unbounded PCollections writes to files support in iobase derived IOs: AvroIO, ParquetIO , TextIO, TFRecordIO [beam]

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

   waiting on author


-- 
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] unbounded PCollections writes to files support in iobase derived IOs: AvroIO, ParquetIO , TextIO, TFRecordIO [beam]

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

   @razvanculea, sorry about the delay of the review. Do you mind merging to the latest master so that the tests are re-triggered.


-- 
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] unbounded PCollections writes to files support in iobase derived IOs: AvroIO, ParquetIO , TextIO, TFRecordIO [beam]

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


##########
sdks/python/apache_beam/io/iobase.py:
##########
@@ -1127,47 +1130,155 @@ def __init__(self, sink: Sink) -> None:
     self.sink = sink
 
   def expand(self, pcoll):
-    do_once = pcoll.pipeline | 'DoOnce' >> core.Create([None])
-    init_result_coll = do_once | 'InitializeWrite' >> core.Map(
-        lambda _, sink: sink.initialize_write(), self.sink)
+    if (pcoll.is_bounded):
+      do_once = pcoll.pipeline | 'DoOnce' >> core.Create([None])
+      init_result_coll = do_once | 'InitializeWrite' >> core.Map(
+          lambda _, sink: sink.initialize_write(), self.sink)
     if getattr(self.sink, 'num_shards', 0):
       min_shards = self.sink.num_shards
-      if min_shards == 1:
-        keyed_pcoll = pcoll | core.Map(lambda x: (None, x))
-      else:
-        keyed_pcoll = pcoll | core.ParDo(_RoundRobinKeyFn(), count=min_shards)
-      write_result_coll = (
+      
+      if (pcoll.is_bounded):
+        if min_shards == 1:
+          keyed_pcoll = pcoll | core.Map(lambda x: (None, x))
+        else:
+          keyed_pcoll = pcoll | core.ParDo(_RoundRobinKeyFn(), count=min_shards)
+        write_result_coll = (
+            keyed_pcoll
+            | core.WindowInto(window.GlobalWindows())
+            | core.GroupByKey()
+            | 'WriteBundles' >> core.ParDo(
+                _WriteKeyedBundleDoFn(self.sink), AsSingleton(init_result_coll)))
+      else: #unbounded PCollection needes to be written per window
+        if isinstance(pcoll.windowing.windowfn, window.GlobalWindows):
+          widowed_pcoll = (
+            pcoll
+              | core.WindowInto(window.FixedWindows(self.sink.triggering_frequency),
+                                trigger=beam.transforms.trigger.AfterWatermark(),
+                                accumulation_mode=beam.transforms.trigger.AccumulationMode.DISCARDING,
+                                allowed_lateness=beam.utils.timestamp.Duration(seconds=0))
+          )
+        else: #keep user windowing
+          widowed_pcoll = pcoll
+        if self.sink.convert_fn is not None:
+          widowed_pcoll = widowed_pcoll | core.ParDo(self.sink.convert_fn)
+        if min_shards == 1:
+          keyed_pcoll = widowed_pcoll | core.Map(lambda x: (None, x))
+        else:
+          keyed_pcoll = widowed_pcoll | core.ParDo(_RoundRobinKeyFn(), count=min_shards)
+        init_result_window_coll = (
           keyed_pcoll
-          | core.WindowInto(window.GlobalWindows())
-          | core.GroupByKey()
-          | 'WriteBundles' >> core.ParDo(
-              _WriteKeyedBundleDoFn(self.sink), AsSingleton(init_result_coll)))
+            | 'Pair init' >> core.Map(lambda x: (None, x))
+            | 'Pair init gbk' >> core.GroupByKey()
+            | 'InitializeWindowedWrite' >> core.Map(
+              lambda _, sink: sink.initialize_write(), self.sink)
+            #| 'LogElements init_result_window_coll' >> LogElements(prefix="init_result_window_coll :",with_window=True,with_timestamp=True,level=logging.INFO)
+        )
+        
+        write_result_coll = (
+          keyed_pcoll
+            | 'Group by random key' >> core.GroupByKey()
+            #| 'LogElements before WriteWindowedBundles' >> LogElements(prefix="before WriteWindowedBundles :",with_window=True,with_timestamp=True,level=logging.INFO)
+            | 'WriteWindowedBundles' >> core.ParDo(
+                _WriteWindowedBundleDoFn(sink=self.sink,per_key=True), 
+                AsSingleton(init_result_window_coll))
+            #| 'LogElements' >> LogElements(prefix="after WriteWindowedBundles :",with_window=True,with_timestamp=True,level=logging.INFO)

Review Comment:
   Remove
   ```suggestion
   ```



##########
sdks/python/apache_beam/io/iobase.py:
##########
@@ -1127,47 +1130,155 @@ def __init__(self, sink: Sink) -> None:
     self.sink = sink
 
   def expand(self, pcoll):
-    do_once = pcoll.pipeline | 'DoOnce' >> core.Create([None])
-    init_result_coll = do_once | 'InitializeWrite' >> core.Map(
-        lambda _, sink: sink.initialize_write(), self.sink)
+    if (pcoll.is_bounded):
+      do_once = pcoll.pipeline | 'DoOnce' >> core.Create([None])
+      init_result_coll = do_once | 'InitializeWrite' >> core.Map(
+          lambda _, sink: sink.initialize_write(), self.sink)
     if getattr(self.sink, 'num_shards', 0):
       min_shards = self.sink.num_shards
-      if min_shards == 1:
-        keyed_pcoll = pcoll | core.Map(lambda x: (None, x))
-      else:
-        keyed_pcoll = pcoll | core.ParDo(_RoundRobinKeyFn(), count=min_shards)
-      write_result_coll = (
+      
+      if (pcoll.is_bounded):
+        if min_shards == 1:
+          keyed_pcoll = pcoll | core.Map(lambda x: (None, x))
+        else:
+          keyed_pcoll = pcoll | core.ParDo(_RoundRobinKeyFn(), count=min_shards)
+        write_result_coll = (
+            keyed_pcoll
+            | core.WindowInto(window.GlobalWindows())
+            | core.GroupByKey()
+            | 'WriteBundles' >> core.ParDo(
+                _WriteKeyedBundleDoFn(self.sink), AsSingleton(init_result_coll)))
+      else: #unbounded PCollection needes to be written per window
+        if isinstance(pcoll.windowing.windowfn, window.GlobalWindows):
+          widowed_pcoll = (
+            pcoll
+              | core.WindowInto(window.FixedWindows(self.sink.triggering_frequency),
+                                trigger=beam.transforms.trigger.AfterWatermark(),
+                                accumulation_mode=beam.transforms.trigger.AccumulationMode.DISCARDING,
+                                allowed_lateness=beam.utils.timestamp.Duration(seconds=0))
+          )
+        else: #keep user windowing
+          widowed_pcoll = pcoll
+        if self.sink.convert_fn is not None:
+          widowed_pcoll = widowed_pcoll | core.ParDo(self.sink.convert_fn)
+        if min_shards == 1:
+          keyed_pcoll = widowed_pcoll | core.Map(lambda x: (None, x))
+        else:
+          keyed_pcoll = widowed_pcoll | core.ParDo(_RoundRobinKeyFn(), count=min_shards)
+        init_result_window_coll = (
           keyed_pcoll
-          | core.WindowInto(window.GlobalWindows())
-          | core.GroupByKey()
-          | 'WriteBundles' >> core.ParDo(
-              _WriteKeyedBundleDoFn(self.sink), AsSingleton(init_result_coll)))
+            | 'Pair init' >> core.Map(lambda x: (None, x))
+            | 'Pair init gbk' >> core.GroupByKey()
+            | 'InitializeWindowedWrite' >> core.Map(
+              lambda _, sink: sink.initialize_write(), self.sink)
+            #| 'LogElements init_result_window_coll' >> LogElements(prefix="init_result_window_coll :",with_window=True,with_timestamp=True,level=logging.INFO)
+        )
+        
+        write_result_coll = (
+          keyed_pcoll
+            | 'Group by random key' >> core.GroupByKey()
+            #| 'LogElements before WriteWindowedBundles' >> LogElements(prefix="before WriteWindowedBundles :",with_window=True,with_timestamp=True,level=logging.INFO)

Review Comment:
   Remove
   ```suggestion
   ```



##########
sdks/python/apache_beam/io/iobase.py:
##########
@@ -1127,47 +1130,155 @@ def __init__(self, sink: Sink) -> None:
     self.sink = sink
 
   def expand(self, pcoll):
-    do_once = pcoll.pipeline | 'DoOnce' >> core.Create([None])
-    init_result_coll = do_once | 'InitializeWrite' >> core.Map(
-        lambda _, sink: sink.initialize_write(), self.sink)
+    if (pcoll.is_bounded):
+      do_once = pcoll.pipeline | 'DoOnce' >> core.Create([None])
+      init_result_coll = do_once | 'InitializeWrite' >> core.Map(
+          lambda _, sink: sink.initialize_write(), self.sink)
     if getattr(self.sink, 'num_shards', 0):
       min_shards = self.sink.num_shards
-      if min_shards == 1:
-        keyed_pcoll = pcoll | core.Map(lambda x: (None, x))
-      else:
-        keyed_pcoll = pcoll | core.ParDo(_RoundRobinKeyFn(), count=min_shards)
-      write_result_coll = (
+      
+      if (pcoll.is_bounded):
+        if min_shards == 1:
+          keyed_pcoll = pcoll | core.Map(lambda x: (None, x))
+        else:
+          keyed_pcoll = pcoll | core.ParDo(_RoundRobinKeyFn(), count=min_shards)
+        write_result_coll = (
+            keyed_pcoll
+            | core.WindowInto(window.GlobalWindows())
+            | core.GroupByKey()
+            | 'WriteBundles' >> core.ParDo(
+                _WriteKeyedBundleDoFn(self.sink), AsSingleton(init_result_coll)))
+      else: #unbounded PCollection needes to be written per window
+        if isinstance(pcoll.windowing.windowfn, window.GlobalWindows):
+          widowed_pcoll = (
+            pcoll
+              | core.WindowInto(window.FixedWindows(self.sink.triggering_frequency),
+                                trigger=beam.transforms.trigger.AfterWatermark(),
+                                accumulation_mode=beam.transforms.trigger.AccumulationMode.DISCARDING,
+                                allowed_lateness=beam.utils.timestamp.Duration(seconds=0))
+          )
+        else: #keep user windowing
+          widowed_pcoll = pcoll
+        if self.sink.convert_fn is not None:
+          widowed_pcoll = widowed_pcoll | core.ParDo(self.sink.convert_fn)
+        if min_shards == 1:
+          keyed_pcoll = widowed_pcoll | core.Map(lambda x: (None, x))
+        else:
+          keyed_pcoll = widowed_pcoll | core.ParDo(_RoundRobinKeyFn(), count=min_shards)
+        init_result_window_coll = (
           keyed_pcoll
-          | core.WindowInto(window.GlobalWindows())
-          | core.GroupByKey()
-          | 'WriteBundles' >> core.ParDo(
-              _WriteKeyedBundleDoFn(self.sink), AsSingleton(init_result_coll)))
+            | 'Pair init' >> core.Map(lambda x: (None, x))
+            | 'Pair init gbk' >> core.GroupByKey()
+            | 'InitializeWindowedWrite' >> core.Map(
+              lambda _, sink: sink.initialize_write(), self.sink)
+            #| 'LogElements init_result_window_coll' >> LogElements(prefix="init_result_window_coll :",with_window=True,with_timestamp=True,level=logging.INFO)

Review Comment:
   Remove
   ```suggestion
   ```



-- 
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] unbounded PCollections writes to files support in iobase derived IOs: AvroIO, ParquetIO , TextIO, TFRecordIO [beam]

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


##########
sdks/python/apache_beam/io/iobase.py:
##########
@@ -1127,47 +1130,155 @@ def __init__(self, sink: Sink) -> None:
     self.sink = sink
 
   def expand(self, pcoll):
-    do_once = pcoll.pipeline | 'DoOnce' >> core.Create([None])
-    init_result_coll = do_once | 'InitializeWrite' >> core.Map(
-        lambda _, sink: sink.initialize_write(), self.sink)
+    if (pcoll.is_bounded):
+      do_once = pcoll.pipeline | 'DoOnce' >> core.Create([None])
+      init_result_coll = do_once | 'InitializeWrite' >> core.Map(
+          lambda _, sink: sink.initialize_write(), self.sink)
     if getattr(self.sink, 'num_shards', 0):
       min_shards = self.sink.num_shards
-      if min_shards == 1:
-        keyed_pcoll = pcoll | core.Map(lambda x: (None, x))
-      else:
-        keyed_pcoll = pcoll | core.ParDo(_RoundRobinKeyFn(), count=min_shards)
-      write_result_coll = (
+      
+      if (pcoll.is_bounded):
+        if min_shards == 1:
+          keyed_pcoll = pcoll | core.Map(lambda x: (None, x))
+        else:
+          keyed_pcoll = pcoll | core.ParDo(_RoundRobinKeyFn(), count=min_shards)
+        write_result_coll = (
+            keyed_pcoll
+            | core.WindowInto(window.GlobalWindows())
+            | core.GroupByKey()
+            | 'WriteBundles' >> core.ParDo(
+                _WriteKeyedBundleDoFn(self.sink), AsSingleton(init_result_coll)))
+      else: #unbounded PCollection needes to be written per window
+        if isinstance(pcoll.windowing.windowfn, window.GlobalWindows):
+          widowed_pcoll = (
+            pcoll
+              | core.WindowInto(window.FixedWindows(self.sink.triggering_frequency),
+                                trigger=beam.transforms.trigger.AfterWatermark(),
+                                accumulation_mode=beam.transforms.trigger.AccumulationMode.DISCARDING,
+                                allowed_lateness=beam.utils.timestamp.Duration(seconds=0))
+          )

Review Comment:
   that would be an alternative way to implement. 
   The windowing will help have elements of the same window in the same file, vs group into batches & trigger will have elements as they come (possibly mixed)



-- 
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] unbounded PCollections writes to files support in iobase derived IOs: AvroIO, ParquetIO , TextIO, TFRecordIO [beam]

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


##########
sdks/python/apache_beam/io/iobase.py:
##########
@@ -1235,10 +1430,20 @@ def _finalize_write(
         writer = sink.open_writer(init_result, str(uuid.uuid4()))
         extra_shards.append(writer.close())
   outputs = sink.finalize_write(
-      init_result, write_results + extra_shards, pre_finalize_results)
+      init_result, write_results + extra_shards, pre_finalize_results, w)
+  outputs = list(outputs)
+  _LOGGER.info("*** _finalize_write outputs %s",outputs)

Review Comment:
   The returned generator should not be materialized into a list afaik.
   ```suggestion
   ```



-- 
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] unbounded PCollections writes to files support in iobase derived IOs: AvroIO, ParquetIO , TextIO, TFRecordIO [beam]

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


##########
sdks/python/apache_beam/io/iobase.py:
##########
@@ -1127,47 +1130,155 @@ def __init__(self, sink: Sink) -> None:
     self.sink = sink
 
   def expand(self, pcoll):
-    do_once = pcoll.pipeline | 'DoOnce' >> core.Create([None])
-    init_result_coll = do_once | 'InitializeWrite' >> core.Map(
-        lambda _, sink: sink.initialize_write(), self.sink)
+    if (pcoll.is_bounded):
+      do_once = pcoll.pipeline | 'DoOnce' >> core.Create([None])
+      init_result_coll = do_once | 'InitializeWrite' >> core.Map(
+          lambda _, sink: sink.initialize_write(), self.sink)
     if getattr(self.sink, 'num_shards', 0):
       min_shards = self.sink.num_shards
-      if min_shards == 1:
-        keyed_pcoll = pcoll | core.Map(lambda x: (None, x))
-      else:
-        keyed_pcoll = pcoll | core.ParDo(_RoundRobinKeyFn(), count=min_shards)
-      write_result_coll = (
+      
+      if (pcoll.is_bounded):
+        if min_shards == 1:
+          keyed_pcoll = pcoll | core.Map(lambda x: (None, x))
+        else:
+          keyed_pcoll = pcoll | core.ParDo(_RoundRobinKeyFn(), count=min_shards)
+        write_result_coll = (
+            keyed_pcoll
+            | core.WindowInto(window.GlobalWindows())
+            | core.GroupByKey()
+            | 'WriteBundles' >> core.ParDo(
+                _WriteKeyedBundleDoFn(self.sink), AsSingleton(init_result_coll)))
+      else: #unbounded PCollection needes to be written per window
+        if isinstance(pcoll.windowing.windowfn, window.GlobalWindows):
+          widowed_pcoll = (
+            pcoll
+              | core.WindowInto(window.FixedWindows(self.sink.triggering_frequency),
+                                trigger=beam.transforms.trigger.AfterWatermark(),
+                                accumulation_mode=beam.transforms.trigger.AccumulationMode.DISCARDING,
+                                allowed_lateness=beam.utils.timestamp.Duration(seconds=0))
+          )

Review Comment:
   If the input is globally windowed a trigger within the global window set to repeat every `sink.triggering_frequency` would be what I'd expect instead of windowing into `FixedWindows`.



-- 
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] unbounded PCollections writes to files support in iobase derived IOs: AvroIO, ParquetIO , TextIO, TFRecordIO [beam]

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

   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


Re: [PR] unbounded PCollections writes to files support in iobase derived IOs: AvroIO, ParquetIO , TextIO, TFRecordIO [beam]

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

   Improved support for user windowing.
   If an unbounded PCollection with GlobalWindow is written:
   * without setting triggering_frequency => throw an exception
   * if triggering_frequency is set, then the output will be written per requested frequency
   
   If an unbounded PCollection with a user set windowing is written:
   * without setting triggering_frequency => tthen the output will be written per user defined window
   * if triggering_frequency is set, then the output will be written per requested frequency
   
   If num_shards is set : per triggering_frequency/user window, the output is written in num_shards
   If num_shards is not set : per triggering_frequency/user window, the output is written with 1 file per bundle
   


-- 
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] unbounded PCollections writes to files support in iobase derived IOs: AvroIO, ParquetIO , TextIO, TFRecordIO [beam]

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

   Assigning new set of reviewers because Pr has gone too long without review. If you would like to opt out of this review, comment `assign to next reviewer`:
   
   R: @jrmccluskey for label python.
   
   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)


-- 
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] unbounded PCollections writes to files support in iobase derived IOs: AvroIO, ParquetIO , TextIO, TFRecordIO [beam]

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

   @shunping don't review this anymore. 
   I'll break it into IObase+FileBasedSync PR, and 1 PR per IO (Parquet,Avro,TFRecord,Text)
   As @sjvanrossum pointed out I could avoid breaking changes, in case there are any private developped IOs that currently work for batch. These would not work for streaming without changes, but would still work as before on batch with newer SDK.


-- 
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] unbounded PCollections writes to files support in iobase derived IOs: AvroIO, ParquetIO , TextIO, TFRecordIO [beam]

Posted by "razvanculea (via GitHub)" <gi...@apache.org>.
razvanculea closed pull request #34777: unbounded PCollections writes to files support in iobase derived IOs:  AvroIO, ParquetIO , TextIO, TFRecordIO
URL: https://github.com/apache/beam/pull/34777


-- 
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] unbounded PCollections writes to files support in iobase derived IOs: AvroIO, ParquetIO , TextIO, TFRecordIO [beam]

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


##########
sdks/python/apache_beam/io/iobase.py:
##########
@@ -1235,10 +1430,20 @@ def _finalize_write(
         writer = sink.open_writer(init_result, str(uuid.uuid4()))
         extra_shards.append(writer.close())
   outputs = sink.finalize_write(
-      init_result, write_results + extra_shards, pre_finalize_results)
+      init_result, write_results + extra_shards, pre_finalize_results, w)
+  outputs = list(outputs)
+  _LOGGER.info("*** _finalize_write outputs %s",outputs)
   if outputs:
-    return (
-        window.TimestampedValue(v, timestamp.MAX_TIMESTAMP) for v in outputs)
+    if not isinstance(w, window.GlobalWindow):
+      #handle windowed finalize
+      yield (
+          window.TimestampedValue(v, 
+              timestamp=self.window.start,
+              windows=[w]
+            ) for v in outputs)
+    else:
+      return (
+          window.TimestampedValue(v, timestamp.MAX_TIMESTAMP) for v in outputs)

Review Comment:
   w.end, but it's true that the result values should be at the end of the window



-- 
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] unbounded PCollections writes to files support in iobase derived IOs: AvroIO, ParquetIO , TextIO, TFRecordIO [beam]

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


##########
sdks/python/apache_beam/io/iobase.py:
##########
@@ -1127,47 +1130,155 @@ def __init__(self, sink: Sink) -> None:
     self.sink = sink
 
   def expand(self, pcoll):
-    do_once = pcoll.pipeline | 'DoOnce' >> core.Create([None])
-    init_result_coll = do_once | 'InitializeWrite' >> core.Map(
-        lambda _, sink: sink.initialize_write(), self.sink)
+    if (pcoll.is_bounded):
+      do_once = pcoll.pipeline | 'DoOnce' >> core.Create([None])
+      init_result_coll = do_once | 'InitializeWrite' >> core.Map(
+          lambda _, sink: sink.initialize_write(), self.sink)
     if getattr(self.sink, 'num_shards', 0):
       min_shards = self.sink.num_shards
-      if min_shards == 1:
-        keyed_pcoll = pcoll | core.Map(lambda x: (None, x))
-      else:
-        keyed_pcoll = pcoll | core.ParDo(_RoundRobinKeyFn(), count=min_shards)
-      write_result_coll = (
+      
+      if (pcoll.is_bounded):
+        if min_shards == 1:
+          keyed_pcoll = pcoll | core.Map(lambda x: (None, x))
+        else:
+          keyed_pcoll = pcoll | core.ParDo(_RoundRobinKeyFn(), count=min_shards)
+        write_result_coll = (
+            keyed_pcoll
+            | core.WindowInto(window.GlobalWindows())
+            | core.GroupByKey()
+            | 'WriteBundles' >> core.ParDo(
+                _WriteKeyedBundleDoFn(self.sink), AsSingleton(init_result_coll)))
+      else: #unbounded PCollection needes to be written per window
+        if isinstance(pcoll.windowing.windowfn, window.GlobalWindows):
+          widowed_pcoll = (
+            pcoll
+              | core.WindowInto(window.FixedWindows(self.sink.triggering_frequency),
+                                trigger=beam.transforms.trigger.AfterWatermark(),
+                                accumulation_mode=beam.transforms.trigger.AccumulationMode.DISCARDING,
+                                allowed_lateness=beam.utils.timestamp.Duration(seconds=0))
+          )
+        else: #keep user windowing
+          widowed_pcoll = pcoll
+        if self.sink.convert_fn is not None:
+          widowed_pcoll = widowed_pcoll | core.ParDo(self.sink.convert_fn)
+        if min_shards == 1:
+          keyed_pcoll = widowed_pcoll | core.Map(lambda x: (None, x))
+        else:
+          keyed_pcoll = widowed_pcoll | core.ParDo(_RoundRobinKeyFn(), count=min_shards)
+        init_result_window_coll = (
           keyed_pcoll
-          | core.WindowInto(window.GlobalWindows())
-          | core.GroupByKey()
-          | 'WriteBundles' >> core.ParDo(
-              _WriteKeyedBundleDoFn(self.sink), AsSingleton(init_result_coll)))
+            | 'Pair init' >> core.Map(lambda x: (None, x))
+            | 'Pair init gbk' >> core.GroupByKey()
+            | 'InitializeWindowedWrite' >> core.Map(
+              lambda _, sink: sink.initialize_write(), self.sink)
+            #| 'LogElements init_result_window_coll' >> LogElements(prefix="init_result_window_coll :",with_window=True,with_timestamp=True,level=logging.INFO)
+        )
+        
+        write_result_coll = (
+          keyed_pcoll
+            | 'Group by random key' >> core.GroupByKey()
+            #| 'LogElements before WriteWindowedBundles' >> LogElements(prefix="before WriteWindowedBundles :",with_window=True,with_timestamp=True,level=logging.INFO)
+            | 'WriteWindowedBundles' >> core.ParDo(
+                _WriteWindowedBundleDoFn(sink=self.sink,per_key=True), 
+                AsSingleton(init_result_window_coll))
+            #| 'LogElements' >> LogElements(prefix="after WriteWindowedBundles :",with_window=True,with_timestamp=True,level=logging.INFO)
+            | 'Pair' >> core.Map(lambda x: (None, x))
+            | core.GroupByKey()
+            | 'Extract' >> core.Map(lambda x: x[1])
+        )
+        pre_finalized_write_result_coll = (
+          write_result_coll 
+          | 'PreFinalize' >> core.ParDo(
+                _PreFinalizeWindowedBundleDoFn(self.sink), AsSingleton(init_result_window_coll))
+        )
+        finalized_write_result_coll = (
+          pre_finalized_write_result_coll 
+          #| 'LogElements pre_finalized_write_result_coll' >> LogElements(prefix="pre_finalized_write_result_coll :",with_window=True,with_timestamp=True,level=logging.INFO)
+          | 'FinalizeWrite' >> core.FlatMap(
+              _finalize_write,
+              self.sink,
+              AsSingleton(init_result_window_coll),
+              AsSingleton(write_result_coll),
+              min_shards,
+              AsIter(pre_finalized_write_result_coll)
+            ).with_output_types(str)
+        )
+        return finalized_write_result_coll
     else:
+      _LOGGER.info("*** WriteImpl min_shards undef so it's 1, and we write per Bundle")
       min_shards = 1
-      write_result_coll = (
+      if (pcoll.is_bounded):
+        write_result_coll = (
+            pcoll
+            | core.WindowInto(window.GlobalWindows())
+            | 'WriteBundles' >> core.ParDo(
+                _WriteBundleDoFn(self.sink), AsSingleton(init_result_coll))
+            | 'Pair' >> core.Map(lambda x: (None, x))
+            | core.GroupByKey()
+            | 'Extract' >> core.FlatMap(lambda x: x[1]))
+      else: #unbounded PCollection needes to be written per window
+        widowed_pcoll = (
           pcoll
-          | core.WindowInto(window.GlobalWindows())
-          | 'WriteBundles' >> core.ParDo(
-              _WriteBundleDoFn(self.sink), AsSingleton(init_result_coll))
-          | 'Pair' >> core.Map(lambda x: (None, x))
-          | core.GroupByKey()
-          | 'Extract' >> core.FlatMap(lambda x: x[1]))
+            | core.WindowInto(window.FixedWindows(self.sink.triggering_frequency),
+                              trigger=beam.transforms.trigger.AfterWatermark(),
+                              accumulation_mode=beam.transforms.trigger.AccumulationMode.DISCARDING,
+                              allowed_lateness=beam.utils.timestamp.Duration(seconds=0))
+        )
+        init_result_window_coll = (
+          widowed_pcoll
+            | 'Pair init' >> core.Map(lambda x: (None, x))
+            | 'Pair init gbk' >> core.GroupByKey()
+            | 'InitializeWindowedWrite' >> core.Map(
+              lambda _, sink: sink.initialize_write(), self.sink)
+        )
+        if self.sink.convert_fn is not None:
+          widowed_pcoll = widowed_pcoll | core.ParDo(self.sink.convert_fn)
+        write_result_coll = (
+          widowed_pcoll
+            | 'WriteWindowedBundles' >> core.ParDo(
+                _WriteWindowedBundleDoFn(self.sink), AsSingleton(init_result_window_coll))
+            | 'LogElements' >> LogElements(prefix="after WriteWindowedBundles :",with_window=True,with_timestamp=True,level=logging.INFO)

Review Comment:
   Remove
   ```suggestion
   ```



##########
sdks/python/apache_beam/io/iobase.py:
##########
@@ -1127,47 +1130,155 @@ def __init__(self, sink: Sink) -> None:
     self.sink = sink
 
   def expand(self, pcoll):
-    do_once = pcoll.pipeline | 'DoOnce' >> core.Create([None])
-    init_result_coll = do_once | 'InitializeWrite' >> core.Map(
-        lambda _, sink: sink.initialize_write(), self.sink)
+    if (pcoll.is_bounded):
+      do_once = pcoll.pipeline | 'DoOnce' >> core.Create([None])
+      init_result_coll = do_once | 'InitializeWrite' >> core.Map(
+          lambda _, sink: sink.initialize_write(), self.sink)
     if getattr(self.sink, 'num_shards', 0):
       min_shards = self.sink.num_shards
-      if min_shards == 1:
-        keyed_pcoll = pcoll | core.Map(lambda x: (None, x))
-      else:
-        keyed_pcoll = pcoll | core.ParDo(_RoundRobinKeyFn(), count=min_shards)
-      write_result_coll = (
+      
+      if (pcoll.is_bounded):
+        if min_shards == 1:
+          keyed_pcoll = pcoll | core.Map(lambda x: (None, x))
+        else:
+          keyed_pcoll = pcoll | core.ParDo(_RoundRobinKeyFn(), count=min_shards)
+        write_result_coll = (
+            keyed_pcoll
+            | core.WindowInto(window.GlobalWindows())
+            | core.GroupByKey()
+            | 'WriteBundles' >> core.ParDo(
+                _WriteKeyedBundleDoFn(self.sink), AsSingleton(init_result_coll)))
+      else: #unbounded PCollection needes to be written per window
+        if isinstance(pcoll.windowing.windowfn, window.GlobalWindows):
+          widowed_pcoll = (
+            pcoll
+              | core.WindowInto(window.FixedWindows(self.sink.triggering_frequency),
+                                trigger=beam.transforms.trigger.AfterWatermark(),
+                                accumulation_mode=beam.transforms.trigger.AccumulationMode.DISCARDING,
+                                allowed_lateness=beam.utils.timestamp.Duration(seconds=0))
+          )
+        else: #keep user windowing
+          widowed_pcoll = pcoll
+        if self.sink.convert_fn is not None:
+          widowed_pcoll = widowed_pcoll | core.ParDo(self.sink.convert_fn)
+        if min_shards == 1:
+          keyed_pcoll = widowed_pcoll | core.Map(lambda x: (None, x))
+        else:
+          keyed_pcoll = widowed_pcoll | core.ParDo(_RoundRobinKeyFn(), count=min_shards)
+        init_result_window_coll = (
           keyed_pcoll
-          | core.WindowInto(window.GlobalWindows())
-          | core.GroupByKey()
-          | 'WriteBundles' >> core.ParDo(
-              _WriteKeyedBundleDoFn(self.sink), AsSingleton(init_result_coll)))
+            | 'Pair init' >> core.Map(lambda x: (None, x))
+            | 'Pair init gbk' >> core.GroupByKey()
+            | 'InitializeWindowedWrite' >> core.Map(
+              lambda _, sink: sink.initialize_write(), self.sink)
+            #| 'LogElements init_result_window_coll' >> LogElements(prefix="init_result_window_coll :",with_window=True,with_timestamp=True,level=logging.INFO)
+        )
+        
+        write_result_coll = (
+          keyed_pcoll
+            | 'Group by random key' >> core.GroupByKey()
+            #| 'LogElements before WriteWindowedBundles' >> LogElements(prefix="before WriteWindowedBundles :",with_window=True,with_timestamp=True,level=logging.INFO)
+            | 'WriteWindowedBundles' >> core.ParDo(
+                _WriteWindowedBundleDoFn(sink=self.sink,per_key=True), 
+                AsSingleton(init_result_window_coll))
+            #| 'LogElements' >> LogElements(prefix="after WriteWindowedBundles :",with_window=True,with_timestamp=True,level=logging.INFO)
+            | 'Pair' >> core.Map(lambda x: (None, x))
+            | core.GroupByKey()
+            | 'Extract' >> core.Map(lambda x: x[1])
+        )
+        pre_finalized_write_result_coll = (
+          write_result_coll 
+          | 'PreFinalize' >> core.ParDo(
+                _PreFinalizeWindowedBundleDoFn(self.sink), AsSingleton(init_result_window_coll))
+        )
+        finalized_write_result_coll = (
+          pre_finalized_write_result_coll 
+          #| 'LogElements pre_finalized_write_result_coll' >> LogElements(prefix="pre_finalized_write_result_coll :",with_window=True,with_timestamp=True,level=logging.INFO)
+          | 'FinalizeWrite' >> core.FlatMap(
+              _finalize_write,
+              self.sink,
+              AsSingleton(init_result_window_coll),
+              AsSingleton(write_result_coll),
+              min_shards,
+              AsIter(pre_finalized_write_result_coll)
+            ).with_output_types(str)
+        )
+        return finalized_write_result_coll
     else:
+      _LOGGER.info("*** WriteImpl min_shards undef so it's 1, and we write per Bundle")
       min_shards = 1
-      write_result_coll = (
+      if (pcoll.is_bounded):
+        write_result_coll = (
+            pcoll
+            | core.WindowInto(window.GlobalWindows())
+            | 'WriteBundles' >> core.ParDo(
+                _WriteBundleDoFn(self.sink), AsSingleton(init_result_coll))
+            | 'Pair' >> core.Map(lambda x: (None, x))
+            | core.GroupByKey()
+            | 'Extract' >> core.FlatMap(lambda x: x[1]))
+      else: #unbounded PCollection needes to be written per window
+        widowed_pcoll = (
           pcoll
-          | core.WindowInto(window.GlobalWindows())
-          | 'WriteBundles' >> core.ParDo(
-              _WriteBundleDoFn(self.sink), AsSingleton(init_result_coll))
-          | 'Pair' >> core.Map(lambda x: (None, x))
-          | core.GroupByKey()
-          | 'Extract' >> core.FlatMap(lambda x: x[1]))
+            | core.WindowInto(window.FixedWindows(self.sink.triggering_frequency),
+                              trigger=beam.transforms.trigger.AfterWatermark(),
+                              accumulation_mode=beam.transforms.trigger.AccumulationMode.DISCARDING,
+                              allowed_lateness=beam.utils.timestamp.Duration(seconds=0))
+        )
+        init_result_window_coll = (
+          widowed_pcoll
+            | 'Pair init' >> core.Map(lambda x: (None, x))
+            | 'Pair init gbk' >> core.GroupByKey()
+            | 'InitializeWindowedWrite' >> core.Map(
+              lambda _, sink: sink.initialize_write(), self.sink)
+        )
+        if self.sink.convert_fn is not None:
+          widowed_pcoll = widowed_pcoll | core.ParDo(self.sink.convert_fn)
+        write_result_coll = (
+          widowed_pcoll
+            | 'WriteWindowedBundles' >> core.ParDo(
+                _WriteWindowedBundleDoFn(self.sink), AsSingleton(init_result_window_coll))
+            | 'LogElements' >> LogElements(prefix="after WriteWindowedBundles :",with_window=True,with_timestamp=True,level=logging.INFO)
+            | 'Pair' >> core.Map(lambda x: (None, x))
+            | core.GroupByKey()
+            | 'Extract' >> core.Map(lambda x: x[1])
+        )
+        pre_finalized_write_result_coll = (
+          write_result_coll 
+          | 'PreFinalize' >> core.ParDo(
+                _PreFinalizeWindowedBundleDoFn(self.sink), AsSingleton(init_result_window_coll))
+        )
+        finalized_write_result_coll = (
+          pre_finalized_write_result_coll 
+          | 'LogElements 2' >> LogElements(prefix="before finalize :",with_window=True,with_timestamp=True,level=logging.INFO)

Review Comment:
   Remove
   ```suggestion
   ```



-- 
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] unbounded PCollections writes to files support in iobase derived IOs: AvroIO, ParquetIO , TextIO, TFRecordIO [beam]

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


##########
sdks/python/apache_beam/io/iobase.py:
##########
@@ -1235,10 +1430,20 @@ def _finalize_write(
         writer = sink.open_writer(init_result, str(uuid.uuid4()))
         extra_shards.append(writer.close())
   outputs = sink.finalize_write(
-      init_result, write_results + extra_shards, pre_finalize_results)
+      init_result, write_results + extra_shards, pre_finalize_results, w)
+  outputs = list(outputs)
+  _LOGGER.info("*** _finalize_write outputs %s",outputs)
   if outputs:
-    return (
-        window.TimestampedValue(v, timestamp.MAX_TIMESTAMP) for v in outputs)
+    if not isinstance(w, window.GlobalWindow):
+      #handle windowed finalize
+      yield (
+          window.TimestampedValue(v, 
+              timestamp=self.window.start,
+              windows=[w]
+            ) for v in outputs)
+    else:
+      return (
+          window.TimestampedValue(v, timestamp.MAX_TIMESTAMP) for v in outputs)

Review Comment:
   The constructor of `TimestampedValue` has no argument `windows` afaik and you likely want to shift these resulting elements to the window's end time, although looking at the Java SDK perhaps this should be `w.max_timestamp()`.
   ```suggestion
         return (
             window.TimestampedValue(v, w.end) for v in outputs)
   ```



-- 
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] unbounded PCollections writes to files support in iobase derived IOs: AvroIO, ParquetIO , TextIO, TFRecordIO [beam]

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

   cc @liferoad 


-- 
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] unbounded PCollections writes to files support in iobase derived IOs: AvroIO, ParquetIO , TextIO, TFRecordIO [beam]

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

   is this PR tested with DataflowRunner?


-- 
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] unbounded PCollections writes to files support in iobase derived IOs: AvroIO, ParquetIO , TextIO, TFRecordIO [beam]

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

   > > is this PR tested with DataflowRunner?
   > 
   > @liferoad i've added the iobase_it_test from PR 34814 and it runs on Dataflow (it's actually using TextIO for write), but i don't have an IT for TextIO/parquetIO/AvroIO/TFRecordIO, I can try to add them, but i can't use TestStream in Dataflow, so i'll need to use PubSub public topics , right ?
   
   
   
   > > is this PR tested with DataflowRunner?
   > 
   > @liferoad i've added the iobase_it_test from PR 34814 and it runs on Dataflow (it's actually using TextIO for write), but i don't have an IT for TextIO/parquetIO/AvroIO/TFRecordIO, I can try to add them, but i can't use TestStream in Dataflow, so i'll need to use PubSub public topics , right ?
   
   I forgot whether periodic impulse can trigger https://github.com/apache/beam/issues/25598. You could try that. And better add some checks about the output results.


-- 
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] unbounded PCollections writes to files support in iobase derived IOs: AvroIO, ParquetIO , TextIO, TFRecordIO [beam]

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

   > is this PR tested with DataflowRunner?
   
   @liferoad i've added the iobase_it_test from PR 34814 and it runs on Dataflow (it's actually using TextIO for write), but i don't have an IT for TextIO/parquetIO/AvroIO/TFRecordIO, I can try to add them, but i can't use TestStream in Dataflow, so i'll need to use PubSub public topics , right ?


-- 
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] unbounded PCollections writes to files support in iobase derived IOs: AvroIO, ParquetIO , TextIO, TFRecordIO [beam]

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


##########
sdks/python/apache_beam/io/iobase.py:
##########
@@ -1235,10 +1430,20 @@ def _finalize_write(
         writer = sink.open_writer(init_result, str(uuid.uuid4()))
         extra_shards.append(writer.close())
   outputs = sink.finalize_write(
-      init_result, write_results + extra_shards, pre_finalize_results)
+      init_result, write_results + extra_shards, pre_finalize_results, w)
+  outputs = list(outputs)
+  _LOGGER.info("*** _finalize_write outputs %s",outputs)

Review Comment:
   correct, fixed in [3c720d3](https://github.com/apache/beam/pull/34777/commits/3c720d38668e70c05da761d743239f24f1a375e0)



-- 
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] unbounded PCollections writes to files support in iobase derived IOs: AvroIO, ParquetIO , TextIO, TFRecordIO [beam]

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

   sg! Feel free to tag me when they are ready.


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