New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Hopping window #196
Merged
Merged
Hopping window #196
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
2700fc0
Added SlidingWindow
Psykopear 654c4fe
Refactoring and fixes
Psykopear 7924c88
Document and fix macro
Psykopear 0e32e2a
Renamed Sliding->Hopping
Psykopear 7db15dd
Doctest fixes
Psykopear e827576
Update src/macros.rs
Psykopear d38f4bc
Refactoring: TumblingWindowConfig now uses HoopingWindower
Psykopear File filter
Filter by extension
Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -72,5 +72,6 @@ | |
EventClockConfig, | ||
SystemClockConfig, | ||
TumblingWindowConfig, | ||
HoppingWindowConfig, | ||
WindowConfig, | ||
) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,166 @@ | ||
use std::collections::HashMap; | ||
|
||
use chrono::{DateTime, Duration, Utc}; | ||
use pyo3::{pyclass, Python}; | ||
|
||
use crate::{add_pymethods, common::StringResult, window::WindowConfig}; | ||
|
||
use super::{Builder, InsertError, StateBytes, WindowBuilder, WindowKey, Windower}; | ||
|
||
/// Hopping windows of fixed duration. | ||
/// If offset == length, you get tumbling windows. | ||
/// If offset < length, windows overlap. | ||
/// If offset > length, there will be holes between windows. | ||
/// | ||
/// Args: | ||
/// | ||
/// length (datetime.timedelta): Length of window. | ||
/// | ||
/// offset (datetime.timedelta): Offset between windows. | ||
/// | ||
/// start_at (datetime.datetime): Instant of the first window. You | ||
/// can use this to align all windows to an hour, | ||
/// e.g. Defaults to system time of dataflow start. | ||
/// | ||
/// Returns: | ||
/// | ||
/// Config object. Pass this as the `window_config` parameter to | ||
/// your windowing operator. | ||
#[pyclass(module="bytewax.window", extends=WindowConfig)] | ||
#[derive(Clone)] | ||
pub(crate) struct HoppingWindowConfig { | ||
#[pyo3(get)] | ||
pub(crate) length: Duration, | ||
#[pyo3(get)] | ||
pub(crate) offset: Duration, | ||
#[pyo3(get)] | ||
pub(crate) start_at: Option<DateTime<Utc>>, | ||
} | ||
|
||
add_pymethods!( | ||
HoppingWindowConfig, | ||
parent: WindowConfig, | ||
py_args: (length, offset, start_at = "None"), | ||
args { | ||
length: Duration => Duration::zero(), | ||
offset: Duration => Duration::zero(), | ||
start_at: Option<DateTime<Utc>> => None | ||
} | ||
); | ||
|
||
impl WindowBuilder for HoppingWindowConfig { | ||
fn build(&self, _py: Python) -> StringResult<Builder> { | ||
Ok(Box::new(HoppingWindower::builder( | ||
self.length, | ||
self.offset, | ||
self.start_at.unwrap_or_else(Utc::now), | ||
))) | ||
} | ||
} | ||
|
||
pub(crate) struct HoppingWindower { | ||
length: Duration, | ||
offset: Duration, | ||
start_at: DateTime<Utc>, | ||
close_times: HashMap<WindowKey, DateTime<Utc>>, | ||
} | ||
|
||
impl HoppingWindower { | ||
pub(crate) fn builder( | ||
length: Duration, | ||
offset: Duration, | ||
start_at: DateTime<Utc>, | ||
) -> impl Fn(Option<StateBytes>) -> Box<dyn Windower> { | ||
move |resume_snapshot| { | ||
let close_times = resume_snapshot | ||
.map(StateBytes::de::<HashMap<WindowKey, DateTime<Utc>>>) | ||
.unwrap_or_default(); | ||
Box::new(Self { | ||
length, | ||
offset, | ||
start_at, | ||
close_times, | ||
}) | ||
} | ||
} | ||
|
||
fn add_close_time(&mut self, key: WindowKey, window_end: DateTime<Utc>) { | ||
self.close_times | ||
.entry(key) | ||
.and_modify(|existing| { | ||
assert!( | ||
existing == &window_end, | ||
"HoppingWindower is not generating consistent boundaries" | ||
) | ||
}) | ||
.or_insert(window_end); | ||
} | ||
} | ||
|
||
impl Windower for HoppingWindower { | ||
fn insert( | ||
&mut self, | ||
watermark: &DateTime<Utc>, | ||
item_time: &DateTime<Utc>, | ||
) -> Vec<Result<WindowKey, InsertError>> { | ||
let since_start_at = (*item_time - self.start_at).num_milliseconds(); | ||
let since_watermark = (*watermark - self.start_at).num_milliseconds(); | ||
let offset = self.offset.num_milliseconds(); | ||
|
||
let windows_count = since_start_at / offset + 1; | ||
let first_window = (since_watermark / offset - 1).max(0); | ||
|
||
(first_window..windows_count) | ||
.map(|i| { | ||
// First generate the WindowKey and calculate | ||
// the window_end time | ||
let key = WindowKey(i); | ||
let window_start = self.start_at + Duration::milliseconds(i * offset); | ||
let window_end = window_start + self.length; | ||
// We only want to add items that happened between | ||
// start and end of the window. | ||
// If the watermark is past the end of the window, | ||
// any item is late for this window. | ||
if *item_time >= window_start && *item_time < window_end && *watermark <= window_end | ||
{ | ||
self.add_close_time(key, window_end); | ||
Ok(key) | ||
} else { | ||
// We send `Late` even if the item came too early, | ||
// maybe we should differentate | ||
Err(InsertError::Late(key)) | ||
} | ||
}) | ||
.collect() | ||
} | ||
|
||
/// Look at the current watermark, determine which windows are now | ||
/// closed, return them, and remove them from internal state. | ||
fn drain_closed(&mut self, watermark: &DateTime<Utc>) -> Vec<WindowKey> { | ||
let mut future_close_times = HashMap::new(); | ||
let mut closed_ids = Vec::new(); | ||
|
||
for (id, close_at) in self.close_times.iter() { | ||
if close_at < watermark { | ||
closed_ids.push(*id); | ||
} else { | ||
future_close_times.insert(*id, *close_at); | ||
} | ||
} | ||
|
||
self.close_times = future_close_times; | ||
closed_ids | ||
} | ||
|
||
fn is_empty(&self) -> bool { | ||
self.close_times.is_empty() | ||
} | ||
|
||
fn next_close(&self) -> Option<DateTime<Utc>> { | ||
self.close_times.values().cloned().min() | ||
} | ||
|
||
fn snapshot(&self) -> StateBytes { | ||
StateBytes::ser::<HashMap<WindowKey, DateTime<Utc>>>(&self.close_times) | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I rewrote this test to make it a little easier (for me) to satisfy myself that the window was doing what I expected.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I do think #196 (comment) is a little more readable. Not for this PR, but probably all the window tests should look like this.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Yes that's much more clear, I'm changing it