gemini-code-assist[bot] commented on code in PR #36661:
URL: https://github.com/apache/beam/pull/36661#discussion_r2473304393


##########
sdks/python/apache_beam/examples/cookbook/ordered_window_elements/streaming.py:
##########
@@ -200,10 +200,19 @@ def process(
 
     timer_started = timer_state.read()
     if not timer_started:
+      timestamp_secs = timestamp.micros / 1e6
+
+      # Align the timestamp with the windowing scheme.
+      aligned_timestamp = timestamp_secs - self.offset
+
+      # Calculate the start of the last window that could contain this 
timestamp.
+      last_window_start_aligned = ((aligned_timestamp // self.slide_interval) *
+                                   self.slide_interval)
+      last_window_start = last_window_start_aligned + self.offset
+
+      n = (self.duration - 1) // self.slide_interval
       # Calculate the start of the first sliding window.
-      first_slide_start = int(
-          (timestamp.micros / 1e6 - self.offset) //
-          self.slide_interval) * self.slide_interval + self.offset
+      first_slide_start = last_window_start - n * self.slide_interval
       first_slide_start_ts = Timestamp.of(first_slide_start)

Review Comment:
   ![medium](https://www.gstatic.com/codereviewagent/medium-priority.svg)
   
   The calculation of `first_slide_start` uses floating-point arithmetic which 
can lead to precision issues with timestamps. It's better to use 
`apache_beam.utils.timestamp.Timestamp` and 
`apache_beam.utils.timestamp.Duration` objects for these calculations to ensure 
precision and improve code clarity.
   
   ```suggestion
         offset_ts = beam.utils.timestamp.Timestamp.of(self.offset)
         slide_duration = beam.utils.timestamp.Duration.of(self.slide_interval)
         duration_duration = beam.utils.timestamp.Duration.of(self.duration)
   
         # Align the timestamp with the windowing scheme.
         aligned_micros = (timestamp - offset_ts).micros
   
         # Calculate the start of the last window that could contain this 
timestamp.
         last_window_start_aligned_micros = (
             (aligned_micros // slide_duration.micros) * slide_duration.micros)
         last_window_start = offset_ts + beam.utils.timestamp.Duration(
             micros=last_window_start_aligned_micros)
   
         n = (duration_duration.micros - 1) // slide_duration.micros
         # Calculate the start of the first sliding window.
         first_slide_start_ts = last_window_start - 
beam.utils.timestamp.Duration(
             micros=n * slide_duration.micros)
   ```



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to