When we were studying the flink source code, we found that there was a problem with its algorithm for calculating the window start time. When timestamp - offset + windowSize < 0 , the element will be incorrectly allocated to a window with a WindowSize larger than its own timestamp.
The problem is in org.apache.flink.streaming.api.windowing.windows.TimeWindow
We believe that this violates the constraints between time and window. That is, an element should fall within a window whose start time is less than its own timestamp and whose end time is greater than its own timestamp. However, the current situation is when timestamp - offset + windowSize < 0, the element falls into a future time window.
You can reproduce the bug with the code at the end of the post.
In fact, the original algorithm is no problem in python, the key to this problem is the processing of the remainder operation by the programming language.
We finally think that it should be modified to the following algorithm.
windowSize & (timestamp - offset) >> 63 The function of this formula is to subtract windowSize from the overall operation result when timestamp - offset<0, otherwise do nothing. This way we can handle both positive and negative timestamps.
Finally, the element can be assigned to the correct window.
This code can pass current unit tests.
I think that there should be many places in getWindowStartWithOffset. We searched for this method in the project and found that the problem of negative timestamps is handled in flink.table.
Below is their source code.
When we wrote the test case, we found that the algorithm we wrote would violate the convention that the window is closed on the left and open on the right. In addition, considering the readability of the code, we decided to use the same code as in org.apache.flink.table.runtime.operators.window.grouping.WindowsGrouping.
In addition, in the process of modification, we found that the algorithm of getWindowStartWithOffset in org.apache.flink.table.runtime.operators.window.TimeWindow is the same as that in org.apache.flink.streaming.api.windowing.windows.TimeWindow. So it should cause the same problem. I think it should also be modified to support negative timestamps
FLINK-26334[datastream] Fix getWindowStartWithOffset in TimeWindow.java by realdengziqi · Pull Request #18982 · apache/flink (github.com)|https://github.com/apache/flink/pull/18982]
If the community deems it necessary to revise it, hopefully this task can be handed over to us. Our members are all students who have just graduated from school, and it is a great encouragement for us to contribute code to flink.
Thank you so much!
From Deng Ziqi & Lin Wanni & Guo Yuanfang