window_machines 0.1.4 → 0.4.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,5 +1,45 @@
1
1
  # Changelog
2
2
 
3
+ ## [0.5.1](https://github.com/seuros/window_machines/compare/window-machines-v0.5.0...window-machines-v0.5.1) (2026-11-16)
4
+
5
+
6
+ ### Bug Fixes
7
+
8
+ * drop slice indexing from the window core ([7f03bb9](https://github.com/seuros/window_machines/commit/7f03bb90791d681a37d24d69f0d8a574dcb1a438))
9
+
10
+ ## [0.5.0](https://github.com/seuros/window_machines/compare/window-machines-v0.4.0...window-machines-v0.5.0) (2026-11-14)
11
+
12
+
13
+ ### ⚠ BREAKING CHANGES
14
+
15
+ * adopt matryona-machines 0.2 (exact_fields, frozen-first, missing_docs)
16
+
17
+ ### Features
18
+
19
+ * adopt matryona-machines 0.2 (exact_fields, frozen-first, missing_docs) ([9ac31a3](https://github.com/seuros/window_machines/commit/9ac31a39d0a1138ea78fadb8a5ff3e65d33dda19))
20
+
21
+ ## [0.4.0](https://github.com/seuros/window_machines/compare/window-machines-v0.3.0...window-machines-v0.4.0) (2026-11-14)
22
+
23
+
24
+ ### ⚠ BREAKING CHANGES
25
+
26
+ * seal window values, check exact classes natively, re-check frozen before keeping
27
+
28
+ ### Features
29
+
30
+ * seal window values, check exact classes natively, re-check frozen before keeping ([9a891df](https://github.com/seuros/window_machines/commit/9a891dfdb502048734b2a4db99823e800ff11e81))
31
+
32
+ ## [0.3.0](https://github.com/seuros/window_machines/compare/window-machines-v0.2.2...window-machines-v0.3.0) (2026-11-13)
33
+
34
+
35
+ ### ⚠ BREAKING CHANGES
36
+
37
+ * converted to the fleet conventions. One exhaustive Refusal per crate, Result from every operation that can refuse, a refusal changes nothing, provable idempotent repeats are honoured, Ruby mirrors the core. No compatibility aliases. A late event inside a still-held session is Covered; Ruby refusals are symbols and no longer raise.
38
+
39
+ ### Features
40
+
41
+ * answer refusals as Result<_, Refusal>, honour repeats, write sliding windows into a caller buffer ([520e126](https://github.com/seuros/window_machines/commit/520e126842a5065411eae7dafed05151da2919ff))
42
+
3
43
  ## [0.2.2](https://github.com/seuros/window_machines/compare/window-machines-v0.2.1...window-machines-v0.2.2) (2026-11-06)
4
44
 
5
45
 
@@ -1,13 +1,15 @@
1
1
  [package]
2
2
  name = "window-machines"
3
- version = "0.2.2"
3
+ version = "0.5.1"
4
4
  edition.workspace = true
5
5
  rust-version.workspace = true
6
6
  license.workspace = true
7
7
  description = "Bounded event-time windows, watermarks, and session merging"
8
8
  readme = "README.md"
9
- exclude = ["src/**/tests.rs", "tests/"]
9
+ exclude = ["src/**/tests.rs", "src/tests/", "tests/"]
10
10
  keywords = ["windowing", "event-time", "watermark", "sessions", "no-std"]
11
11
  categories = ["no-std", "algorithms"]
12
+ [dev-dependencies]
13
+ matryona-machines = { workspace = true, features = ["testing"] }
12
14
  [lints]
13
15
  workspace = true
@@ -5,18 +5,132 @@
5
5
  Engine-room flight manual: divide observation time into bounded survey windows.
6
6
 
7
7
  Allocation-free `no_std` window boundaries and one-key bounded session tracking.
8
- All timestamps and widths use one caller-selected unsigned unit and origin.
9
- Tumbling/sliding windows are aligned to zero and half-open `[start, end)`.
10
- Sliding results are newest-start-first; too-small output capacity rejects rather
11
- than silently truncating. Overflowing boundaries reject.
12
-
13
- Watermarks never regress. A window closes when watermark reaches its end plus
14
- allowed lateness; arithmetic overflow means it cannot yet close.
15
-
16
- Sessions merge events whose inactivity gaps are **at most** the configured gap,
17
- including out-of-order bridging events. Events at/below the current watermark
18
- are late and rejected; session allowed lateness is zero in this version. Advancing
19
- a watermark does not discard sessions: explicitly drain `take_closed()`.
20
- Full tables reject events that cannot merge. Callers retain aggregation payloads
21
- and apply the same merges; the core stores boundaries only. Multi-key indexing,
22
- retractions, and distributed watermark coordination are not implemented.
8
+
9
+ ## Time
10
+
11
+ Every timestamp, watermark and span between them (window `width`, `size`,
12
+ `slide`, session `gap`, `allowed_lateness`) is a `u64` of **event time** in one
13
+ caller-selected unit and origin. Event time is not a monotonic clock, so none of
14
+ it is a `core::time::Duration`; the core reads no clock at all.
15
+
16
+ ## Windows
17
+
18
+ Tumbling and sliding windows are aligned to zero and half-open `[start, end)`.
19
+ `tumbling(timestamp, width)` returns `Result<Window, Refusal>`.
20
+ `sliding(timestamp, size, slide, out: &mut [Window])` writes the windows
21
+ containing the timestamp into the first `n` entries of `out`, newest start
22
+ first, leaves the rest untouched and returns `Ok(n)`; `Ok(0)` is a timestamp in
23
+ a hole between windows. `Window` implements `Default` so a buffer is
24
+ `[Window::default(); N]`; the default is a placeholder, not a sentinel.
25
+
26
+ ## Values
27
+
28
+ `Window` and `Session` keep their fields private and are valid or do not
29
+ exist. `Window::new(start, end)` is `None` unless `start < end` (an interval
30
+ holding no timestamp is not a window); `Session::new(first, last)` is `None`
31
+ unless `first <= last`. Readers: `start()`, `end()`, `first()`, `last()`. The
32
+ only value built otherwise is the `Default` placeholder of an output buffer.
33
+
34
+ ## Watermarks
35
+
36
+ `Watermark::default()` has observed nothing; `Watermark::at(value)` already
37
+ stands at a value (restored progress). `advance(value)` returns
38
+ `Result<Advancing, Refusal>`: `Advancing::Advanced` when it moved forward or
39
+ took its first value, `Advancing::Repeated` when it already held exactly that
40
+ value. `closes(window, allowed_lateness)` is a pure query: true once the
41
+ watermark reaches `window.end() + allowed_lateness`. It reads only `end`, and a
42
+ sum past `u64::MAX` is a point no watermark reaches, so it is `false`.
43
+
44
+ ## Sessions
45
+
46
+ `Sessions<N>` merges events whose inactivity gaps are **at most** the configured
47
+ gap, including out-of-order bridging events. `insert(timestamp)` returns
48
+ `Result<Inserting, Refusal>`; every `Inserting` variant carries the `Session`
49
+ the event is in:
50
+
51
+ - `Opened`: joined no held session; a new one took a slot.
52
+ - `Extended`: grew one held session or bridged several into one.
53
+ - `Covered`: a held session already covered the timestamp; nothing changed.
54
+
55
+ Session allowed lateness is zero. Advancing the watermark does not discard
56
+ sessions: drain them with `take_closed()`, earliest first, `None` when nothing
57
+ is closed (a drain, not a refusal). A session is closed once the watermark
58
+ reaches `last + gap`. Readers: `gap`, `capacity`, `len`, `is_empty`,
59
+ `watermark` (a copy).
60
+
61
+ ## Contract
62
+
63
+ - **One `Refusal` enum, and a refusal changes nothing.** `out` included.
64
+
65
+ | Call | Refusals |
66
+ | --- | --- |
67
+ | `tumbling` | `Overflow` |
68
+ | `sliding` | `Overflow`, `Undersized` |
69
+ | `Watermark::advance`, `Sessions::advance_watermark` | `Regressed` |
70
+ | `Sessions::insert` | `Late`, `Overflow`, `Full` |
71
+
72
+ `Overflow`: a window end, or `timestamp + gap`, would pass `u64::MAX`.
73
+ `Undersized`: `out` is shorter than the windows to write; nothing is
74
+ truncated. `Regressed`: the value is behind the watermark. `Late`: the
75
+ timestamp is at or below the watermark and no held session covers it.
76
+ `Full`: no free slot and no held session to join; nothing is evicted.
77
+ - **Repeats are honoured when provable.** A watermark repeated at its own value
78
+ is `Advancing::Repeated`. A timestamp inside a held session's boundaries is
79
+ `Inserting::Covered`, at or below the watermark too: the effect asked for
80
+ already holds and the boundaries prove it. The core stores boundaries, not
81
+ events, so `Covered` does not prove the *same event* was seen; deduplicating
82
+ events is the caller's job. Once `take_closed` drained a session no history is
83
+ kept, and a replay of its timestamps is `Late`.
84
+ - **Exhaustive.** No public enum is `#[non_exhaustive]`; a new variant is a
85
+ breaking change.
86
+ - **No clock is recorded.** Every value here is event time; there is no `now`
87
+ and no monotonic clock. `Watermark::advance` records the watermark it was
88
+ given (progress, not a clock) when it answers `Advanced`, and nothing on
89
+ `Repeated` or a refusal.
90
+ - **No unreachable arms.** The core has no `panic!`, `assert!`,
91
+ `unreachable!` or `expect` outside tests.
92
+ - **No issued ids, no scopes.** Nothing here hands out handles. To resume after
93
+ a restart, rebuild a watermark with `Watermark::at` and re-insert sessions.
94
+
95
+ Callers retain aggregation payloads and apply the same merges; the core stores
96
+ boundaries only. Multi-key indexing, retractions, and distributed watermark
97
+ coordination are not implemented.
98
+
99
+ ```rust
100
+ use core::num::NonZeroU64;
101
+ use window_machines::{
102
+ Advancing, Inserting, Refusal, Session, Sessions, Watermark, Window, sliding, tumbling,
103
+ };
104
+
105
+ // Hand-built values go through the validating constructors.
106
+ let win = |start, end| Window::new(start, end).ok_or(Refusal::Overflow);
107
+ let span = |first, last| Session::new(first, last).ok_or(Refusal::Overflow);
108
+ let ten = NonZeroU64::new(10).ok_or(Refusal::Overflow)?;
109
+ let five = NonZeroU64::new(5).ok_or(Refusal::Overflow)?;
110
+
111
+ assert_eq!(tumbling(12, ten)?, win(10, 20)?);
112
+ let mut out = [Window::default(); 4];
113
+ let written = sliding(12, ten, five, &mut out)?;
114
+ assert_eq!(out[..written], [win(10, 20)?, win(5, 15)?]);
115
+
116
+ let mut watermark = Watermark::default();
117
+ assert_eq!(watermark.advance(22), Ok(Advancing::Advanced));
118
+ assert_eq!(watermark.advance(22), Ok(Advancing::Repeated));
119
+ assert_eq!(watermark.advance(9), Err(Refusal::Regressed));
120
+ assert!(watermark.closes(out[0], 2));
121
+
122
+ let mut sessions = Sessions::<4>::new(five);
123
+ assert_eq!(sessions.insert(10)?, Inserting::Opened(span(10, 10)?));
124
+ assert_eq!(sessions.insert(15)?, Inserting::Extended(span(10, 15)?));
125
+ assert_eq!(sessions.insert(12)?, Inserting::Covered(span(10, 15)?));
126
+ assert_eq!(sessions.advance_watermark(20), Ok(Advancing::Advanced));
127
+ assert_eq!(sessions.insert(12)?, Inserting::Covered(span(10, 15)?));
128
+ assert_eq!(sessions.insert(16), Err(Refusal::Late));
129
+ assert_eq!(sessions.take_closed(), Some(span(10, 15)?));
130
+ assert_eq!(sessions.insert(12), Err(Refusal::Late));
131
+ # Ok::<(), Refusal>(())
132
+ ```
133
+
134
+ The Ruby gem mirrors `Window` and `Session` as `Data` values of the same names
135
+ and fields, validated at construction by `Window::new` and `Session::new`, the `Inserting` variants as `Opened`, `Extended` and `Covered`
136
+ (`Data` with a `session`), `Advancing` and every `Refusal` as symbols.
@@ -1,84 +1,175 @@
1
1
  #![no_std]
2
+ #![cfg_attr(not(test), deny(clippy::indexing_slicing))]
2
3
  #![doc = include_str!("../README.md")]
3
4
  use core::num::NonZeroU64;
4
5
 
6
+ mod refusal;
5
7
  mod sessions;
6
- pub use sessions::{Insert, Session, Sessions};
7
8
 
8
- /// Half-open event-time interval.
9
- #[derive(Debug, Clone, Copy, PartialEq, Eq)]
9
+ pub use refusal::Refusal;
10
+ pub use sessions::{Inserting, Session, Sessions};
11
+
12
+ /// Half-open event-time interval `[start, end)`, never empty: `start < end`.
13
+ ///
14
+ /// Built by [`Window::new`], [`tumbling`] or [`sliding`]. The `Default` value
15
+ /// is an output-buffer placeholder (`[Window::default(); N]`), the one value
16
+ /// that is not an interval. It is not a sentinel: read only the entries a call
17
+ /// reports.
18
+ #[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
10
19
  pub struct Window {
20
+ start: u64,
21
+ end: u64,
22
+ }
23
+ impl Window {
24
+ /// The interval `[start, end)`, or `None` unless `start < end`: an interval
25
+ /// that holds no timestamp is not a window.
26
+ #[must_use]
27
+ pub const fn new(start: u64, end: u64) -> Option<Self> {
28
+ if start < end {
29
+ Some(Self { start, end })
30
+ } else {
31
+ None
32
+ }
33
+ }
34
+
11
35
  /// Inclusive start.
12
- pub start: u64,
36
+ #[must_use]
37
+ pub const fn start(self) -> u64 {
38
+ self.start
39
+ }
40
+
13
41
  /// Exclusive end.
14
- pub end: u64,
42
+ #[must_use]
43
+ pub const fn end(self) -> u64 {
44
+ self.end
45
+ }
15
46
  }
16
47
 
17
48
  /// Zero-aligned tumbling window containing this event.
18
- #[must_use]
19
- pub const fn tumbling(timestamp: u64, width: NonZeroU64) -> Option<Window> {
49
+ ///
50
+ /// `timestamp` and `width` are event time in one caller-defined unit.
51
+ ///
52
+ /// # Errors
53
+ /// [`Refusal::Overflow`] when the window's end would pass `u64::MAX`.
54
+ pub const fn tumbling(timestamp: u64, width: NonZeroU64) -> Result<Window, Refusal> {
55
+ // `width` is non-zero and the remainder never exceeds `timestamp`.
20
56
  let start = timestamp - timestamp % width.get();
21
57
  match start.checked_add(width.get()) {
22
- Some(end) => Some(Window { start, end }),
23
- None => None,
58
+ Some(end) => Ok(Window { start, end }),
59
+ None => Err(Refusal::Overflow),
24
60
  }
25
61
  }
26
62
 
27
- /// All nonnegative zero-aligned sliding windows containing this event.
28
- #[must_use]
29
- pub fn sliding<const N: usize>(
63
+ /// Write every zero-aligned sliding window containing this event into `out`,
64
+ /// newest start first, and return how many were written.
65
+ ///
66
+ /// Windows are `size` wide and start every `slide`. The first `n` entries of
67
+ /// `out` are written and the rest left untouched; `Ok(0)` means the timestamp
68
+ /// falls in a hole between windows (`slide` wider than `size`).
69
+ ///
70
+ /// # Errors
71
+ /// [`Refusal::Overflow`] when the newest window's end would pass `u64::MAX`,
72
+ /// [`Refusal::Undersized`] when `out` is shorter than the windows to write.
73
+ /// `out` is untouched by a refusal.
74
+ pub fn sliding(
30
75
  timestamp: u64,
31
76
  size: NonZeroU64,
32
77
  slide: NonZeroU64,
33
- ) -> Option<[Option<Window>; N]> {
34
- let mut result = [None; N];
35
- let mut start = timestamp - timestamp % slide.get();
36
- let mut count = 0;
37
- loop {
38
- let end = start.checked_add(size.get())?;
39
- if end <= timestamp {
40
- break;
41
- }
42
- if count == N {
43
- return None;
44
- }
45
- result[count] = Some(Window { start, end });
46
- count += 1;
47
- let Some(previous) = start.checked_sub(slide.get()) else {
48
- break;
78
+ out: &mut [Window],
79
+ ) -> Result<usize, Refusal> {
80
+ let (size, slide) = (size.get(), slide.get());
81
+ // `slide` is non-zero and `offset <= timestamp`; `size > offset` is
82
+ // checked before `size - offset - 1`, and `newest + size` (the largest
83
+ // end below) is checked before the loop.
84
+ let offset = timestamp % slide;
85
+ let newest = timestamp - offset;
86
+ if size <= offset {
87
+ return Ok(0);
88
+ }
89
+ if newest.checked_add(size).is_none() {
90
+ return Err(Refusal::Overflow);
91
+ }
92
+ // Window `k` starts `k` slides before the newest one: it must still reach
93
+ // past the timestamp and must not start below zero.
94
+ let older = ((size - offset - 1) / slide).min(newest / slide);
95
+ let count = usize::try_from(older)
96
+ .ok()
97
+ .and_then(|older| older.checked_add(1))
98
+ .filter(|count| *count <= out.len())
99
+ .ok_or(Refusal::Undersized)?;
100
+ let mut start = newest;
101
+ for slot in out.iter_mut().take(count) {
102
+ *slot = Window {
103
+ start,
104
+ end: start + size,
49
105
  };
50
- start = previous;
106
+ start = start.saturating_sub(slide);
51
107
  }
52
- Some(result)
108
+ Ok(count)
109
+ }
110
+
111
+ /// What an honoured watermark call did. Neither is a refusal.
112
+ #[derive(Debug, Clone, Copy, PartialEq, Eq)]
113
+ pub enum Advancing {
114
+ /// The watermark moved forward to the value given, or took its first.
115
+ Advanced,
116
+ /// The watermark already stood exactly there: an idempotent repeat that
117
+ /// changed nothing.
118
+ Repeated,
53
119
  }
54
120
 
55
121
  /// Monotonic event-time progress, not a wall clock or consensus watermark.
122
+ ///
123
+ /// The `Default` value has observed nothing yet.
56
124
  #[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
57
125
  pub struct Watermark {
58
126
  value: Option<u64>,
59
127
  }
60
128
  impl Watermark {
61
- /// Advance or repeat progress; reject backwards observations.
129
+ /// A watermark that already stands at `value`, for progress restored from
130
+ /// saved state or read from another owner.
62
131
  #[must_use]
63
- pub fn advance(&mut self, value: u64) -> bool {
64
- if self.value.is_some_and(|old| value < old) {
65
- return false;
132
+ pub const fn at(value: u64) -> Self {
133
+ Self { value: Some(value) }
134
+ }
135
+
136
+ /// Advance or repeat progress.
137
+ ///
138
+ /// [`Advancing::Advanced`] when the watermark moved forward or took its
139
+ /// first value. Repeating the value it already holds is the effect asked
140
+ /// for already holding: [`Advancing::Repeated`], and nothing changes.
141
+ ///
142
+ /// # Errors
143
+ /// [`Refusal::Regressed`] when `value` is behind the watermark. Nothing
144
+ /// changes.
145
+ pub const fn advance(&mut self, value: u64) -> Result<Advancing, Refusal> {
146
+ match self.value {
147
+ Some(held) if value < held => Err(Refusal::Regressed),
148
+ Some(held) if value == held => Ok(Advancing::Repeated),
149
+ Some(_) | None => {
150
+ self.value = Some(value);
151
+ Ok(Advancing::Advanced)
152
+ }
66
153
  }
67
- self.value = Some(value);
68
- true
69
154
  }
70
- /// Last observation, or `None` before initialization.
155
+
156
+ /// Last observation, or `None` before the first.
71
157
  #[must_use]
72
158
  pub const fn value(self) -> Option<u64> {
73
159
  self.value
74
160
  }
75
- /// Whether event-time progress closes this interval plus allowed lateness.
161
+
162
+ /// Whether event-time progress has reached this window's end plus the
163
+ /// allowed lateness.
164
+ ///
165
+ /// Only `window.end` is read. An `end + allowed_lateness` past `u64::MAX`
166
+ /// is a point no watermark can reach, so the answer is exactly `false`.
76
167
  #[must_use]
77
- pub fn closes(self, window: Window, allowed_lateness: u64) -> bool {
78
- window
79
- .end
80
- .checked_add(allowed_lateness)
81
- .is_some_and(|end| self.value.is_some_and(|value| value >= end))
168
+ pub const fn closes(self, window: Window, allowed_lateness: u64) -> bool {
169
+ match (window.end.checked_add(allowed_lateness), self.value) {
170
+ (Some(end), Some(value)) => value >= end,
171
+ (None, Some(_) | None) | (Some(_), None) => false,
172
+ }
82
173
  }
83
174
  }
84
175
  #[cfg(test)]
@@ -0,0 +1,44 @@
1
+ //! The one refusal type of the crate.
2
+
3
+ use core::fmt;
4
+
5
+ /// Why a call was not honoured. A refused call changed nothing.
6
+ ///
7
+ /// [`tumbling`](crate::tumbling) answers [`Overflow`](Self::Overflow);
8
+ /// [`sliding`](crate::sliding) answers [`Overflow`](Self::Overflow) or
9
+ /// [`Undersized`](Self::Undersized);
10
+ /// [`Watermark::advance`](crate::Watermark::advance) and
11
+ /// [`Sessions::advance_watermark`](crate::Sessions::advance_watermark) answer
12
+ /// [`Regressed`](Self::Regressed);
13
+ /// [`Sessions::insert`](crate::Sessions::insert) answers [`Late`](Self::Late),
14
+ /// [`Overflow`](Self::Overflow) or [`Full`](Self::Full).
15
+ #[derive(Debug, Clone, Copy, PartialEq, Eq)]
16
+ pub enum Refusal {
17
+ /// A window end, or a session's closing point `timestamp + gap`, would
18
+ /// pass `u64::MAX`.
19
+ Overflow,
20
+ /// The output buffer is shorter than the windows containing the
21
+ /// timestamp; nothing was written rather than a truncated list.
22
+ Undersized,
23
+ /// The value is behind the watermark; a watermark never moves back.
24
+ Regressed,
25
+ /// The timestamp is at or below the watermark and no held session covers
26
+ /// it.
27
+ Late,
28
+ /// No free slot and no held session the event could join.
29
+ Full,
30
+ }
31
+
32
+ impl fmt::Display for Refusal {
33
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
34
+ f.write_str(match self {
35
+ Self::Overflow => "endpoint would pass the end of event time",
36
+ Self::Undersized => "output buffer is shorter than the windows to write",
37
+ Self::Regressed => "value is behind the watermark",
38
+ Self::Late => "timestamp is at or below the watermark",
39
+ Self::Full => "no free session slot",
40
+ })
41
+ }
42
+ }
43
+
44
+ impl core::error::Error for Refusal {}