batch_machines 0.1.4 → 0.5.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.7.0](https://github.com/seuros/batch_machines/compare/batch-machines-v0.6.0...batch-machines-v0.7.0) (2026-11-16)
4
+
5
+
6
+ ### Features
7
+
8
+ * accept an Integer controller output in Batch#adapt ([676da13](https://github.com/seuros/batch_machines/commit/676da134787cb86aa12156445eaec2fbce346cc5))
9
+
10
+ ## [0.6.0](https://github.com/seuros/batch_machines/compare/batch-machines-v0.5.0...batch-machines-v0.6.0) (2026-11-14)
11
+
12
+
13
+ ### ⚠ BREAKING CHANGES
14
+
15
+ * adopt matryona-machines 0.2 (symbols!, frozen-first)
16
+
17
+ ### Features
18
+
19
+ * adopt matryona-machines 0.2 (symbols!, frozen-first) ([8c964b4](https://github.com/seuros/batch_machines/commit/8c964b4fbc9c0a051da4e4e187378a6dcd718fe7))
20
+
21
+ ## [0.5.0](https://github.com/seuros/batch_machines/compare/batch-machines-v0.4.0...batch-machines-v0.5.0) (2026-11-14)
22
+
23
+
24
+ ### ⚠ BREAKING CHANGES
25
+
26
+ * seal Flush, resolve it at load, re-check frozen before keeping
27
+
28
+ ### Features
29
+
30
+ * seal Flush, resolve it at load, re-check frozen before keeping ([3cde5ab](https://github.com/seuros/batch_machines/commit/3cde5ab2b43cdd2d30dc10729570f53a705e7d8c))
31
+
32
+ ## [0.4.0](https://github.com/seuros/batch_machines/compare/batch-machines-v0.3.0...batch-machines-v0.4.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. Requires flow-machines >= 0.3 and feedback-machines >= 0.3. configure_pid is gone; Ruby answers symbols and a Flush value.
38
+
39
+ ### Features
40
+
41
+ * answer Result<_, Refusal>, stop refused pushes recording the clock, adapt a caller-owned controller ([a3746a5](https://github.com/seuros/batch_machines/commit/a3746a5c91bf437e38389cb5aee5022b3b760797))
42
+
3
43
  ## [0.3.0](https://github.com/seuros/batch_machines/compare/batch-machines-v0.2.2...batch-machines-v0.3.0) (2026-11-06)
4
44
 
5
45
 
@@ -1,16 +1,18 @@
1
1
  [package]
2
2
  name = "batch-machines"
3
- version = "0.3.0"
3
+ version = "0.7.0"
4
4
  edition.workspace = true
5
5
  rust-version.workspace = true
6
6
  license.workspace = true
7
7
  description = "Bounded size/deadline batching with explicit feedback adaptation"
8
8
  readme = "README.md"
9
- exclude = ["src/**/tests.rs", "tests/"]
9
+ exclude = ["src/**/tests.rs", "src/tests/", "tests/"]
10
10
  keywords = ["batching", "backpressure", "latency", "adaptive", "no-std"]
11
11
  categories = ["no-std", "algorithms"]
12
12
  [dependencies]
13
13
  flow-machines.workspace = true
14
14
  feedback-machines.workspace = true
15
+ [dev-dependencies]
16
+ matryona-machines = { workspace = true, features = ["testing"] }
15
17
  [lints]
16
18
  workspace = true
@@ -19,3 +19,56 @@ zero and clamped to `[1, capacity]`. Error definition, gains,
19
19
  measurement, and downstream flush concurrency are caller policies. This cannot
20
20
  guarantee an end-to-end latency budget if timers/execution are delayed. No I/O,
21
21
  timer driver, payload storage, partial flush, or Ruby binding is included.
22
+
23
+ ## Contract
24
+
25
+ - **Answers.** Every operation that can refuse returns `Result<T, Refusal>`,
26
+ and `T` describes only honoured outcomes.
27
+
28
+ | Call | Honoured | Records `now` | Refused |
29
+ | --- | --- | --- | --- |
30
+ | `Batch::new(capacity, max_wait)` | `Some(Batch)` | no clock | `None` for a zero `max_wait` (configuration) |
31
+ | `push(now)`, `push_weighted(now, cost)` | `Admission::Buffered`, `Admission::Flush(FlushReason)`; the item is counted either way | yes | `TimeRegression`, `Overflow`, `Full` |
32
+ | `poll(now)` | `Some(FlushReason)`, or `None` when nothing is due at this instant | yes, `None` included | `TimeRegression` |
33
+ | `flush(now)` | the items that were pending, `0` for an empty batch | yes when items left; `0` records nothing | `TimeRegression` |
34
+ | `adapt(pid, error, elapsed)` | the new target | no, `elapsed` is a span | `NotFinite`, `InvalidDuration`, `Overflow` |
35
+ | `retarget(output)` | the new target | no clock | `NotFinite` |
36
+
37
+ - **Refusals change nothing.** Every `Err` leaves the batch equal to a clone
38
+ taken before the call: no item counted, no cost held, and the `now` it
39
+ carried is not observed, so a refused call can never make a later one a
40
+ `TimeRegression`. A refused `adapt` leaves the controller untouched too.
41
+ - **`Refusal`.** `TimeRegression`: `now` is earlier than the latest instant an
42
+ honoured `push`, `poll` or non-empty `flush` observed. `Overflow`: `now + max_wait`
43
+ does not fit a `Duration` (only a push that would start a batch computes
44
+ it), or a term of the PID calculation is not finite. `Full`: the item costs
45
+ more than the capacity still unspent. `NotFinite`: the error or output is
46
+ NaN or infinite. `InvalidDuration`: `adapt` was given a zero `elapsed`.
47
+ - **Which answers record the clock.** An honoured call records `now` exactly
48
+ when its answer depends on `now`: every honoured push (its admission names
49
+ what is due at that instant), every honoured `poll` (`None` is "nothing due
50
+ at this instant"), and a `flush` that emptied the batch. An empty `flush`
51
+ answers `0` whatever the time and records nothing. `adapt` and `retarget`
52
+ read no clock.
53
+ - **No unreachable refusals.** A push asks the credit window what is
54
+ `available()` and only then acquires, so no `flow-machines` refusal is
55
+ translated: `Full` is the batch's own answer. The acquisition that follows
56
+ cannot be refused; that invariant is a `debug_assert!`, and a release build
57
+ answers `Full` with nothing changed. Nothing in the crate panics.
58
+ - **Repeats.** `flush` on an empty batch is honoured and answers `0`; the
59
+ batch can prove it, because nothing is pending. It changes nothing at any
60
+ `now`. A repeated `poll` at the same `now` answers the same and changes
61
+ nothing. `retarget` to the target already set changes nothing. A push is
62
+ never a repeat: the batch counts items, it does not know them.
63
+ - **Time.** Instants and spans are `core::time::Duration` on the caller's
64
+ monotonic clock. The batch reads no clock.
65
+ - **No issued ids.** The batch hands out no handle, so there is no scope and
66
+ nothing to resume: a restarted batch is `Batch::new` again, empty.
67
+ - **Sibling seams.** `Pid`, `Gains` and `Limits` are `feedback-machines`
68
+ types, re-exported here because `adapt` names `Pid`. `adapt` steps the
69
+ caller's controller and aims the target at its output; it is exactly
70
+ `pid.step(error, elapsed)` followed by `retarget(output)`. It is not named
71
+ `adapt_from`: that name is for a method that only reads a sibling object,
72
+ and this one moves the controller's integral and derivative history.
73
+ `retarget` is the same aiming for a caller that computes the output some
74
+ other way. The `flow-machines` credit window is private.
@@ -1,37 +1,39 @@
1
1
  #![no_std]
2
+ #![cfg_attr(not(test), deny(clippy::indexing_slicing))]
2
3
  #![doc = include_str!("../README.md")]
4
+
5
+ mod refusal;
6
+
3
7
  use core::{num::NonZeroU32, time::Duration};
4
- use feedback_machines::Pid;
8
+
5
9
  use flow_machines::CreditWindow;
6
10
 
11
+ pub use feedback_machines::{Gains, Limits, Pid};
12
+ pub use refusal::Refusal;
13
+
7
14
  /// Why pending work should flush.
8
15
  #[derive(Debug, Clone, Copy, PartialEq, Eq)]
9
- #[non_exhaustive]
10
16
  pub enum FlushReason {
11
- /// Target size reached.
17
+ /// Target cost reached.
12
18
  Size,
13
- /// Oldest item's wait budget expired.
19
+ /// Oldest item's wait budget expired. Wins over `Size` when both hold.
14
20
  Deadline,
15
21
  }
16
22
 
17
- /// Admission decision for one item.
23
+ /// What an honoured push did. The item is counted either way.
18
24
  #[derive(Debug, Clone, Copy, PartialEq, Eq)]
19
- #[non_exhaustive]
20
25
  pub enum Admission {
21
- /// Item was buffered.
26
+ /// The item was buffered and nothing is due.
22
27
  Buffered,
23
- /// Item was buffered and a flush is due.
28
+ /// The item was buffered and a flush is due.
24
29
  Flush(FlushReason),
25
- /// Capacity exhausted; item was not accepted.
26
- Full,
27
- /// Invalid time or deadline overflow; item was not accepted.
28
- Rejected,
29
30
  }
30
31
 
31
32
  /// Bounded batch policy, with caller-owned payloads.
32
- #[derive(Debug)]
33
+ #[derive(Debug, Clone, PartialEq, Eq)]
33
34
  pub struct Batch {
34
35
  credits: CreditWindow,
36
+ capacity: NonZeroU32,
35
37
  items: u32,
36
38
  target: NonZeroU32,
37
39
  max_wait: Duration,
@@ -40,7 +42,8 @@ pub struct Batch {
40
42
  }
41
43
 
42
44
  impl Batch {
43
- /// Start empty, with a positive maximum wait and capacity-sized target.
45
+ /// Start empty, with a capacity-sized target. `None` for a zero
46
+ /// `max_wait`: the first item would be due on arrival.
44
47
  #[must_use]
45
48
  pub const fn new(capacity: NonZeroU32, max_wait: Duration) -> Option<Self> {
46
49
  if max_wait.is_zero() {
@@ -48,6 +51,7 @@ impl Batch {
48
51
  }
49
52
  Some(Self {
50
53
  credits: CreditWindow::new(capacity),
54
+ capacity,
51
55
  items: 0,
52
56
  target: capacity,
53
57
  max_wait,
@@ -56,64 +60,141 @@ impl Batch {
56
60
  })
57
61
  }
58
62
 
59
- /// Account one item of cost 1; the caller stores its payload only on acceptance.
60
- #[must_use]
61
- pub fn push(&mut self, now: Duration) -> Admission {
63
+ /// Account one item of cost 1; the caller stores its payload only when
64
+ /// the push is honoured. Exactly `push_weighted(now, 1)`.
65
+ ///
66
+ /// # Errors
67
+ ///
68
+ /// As [`Self::push_weighted`].
69
+ pub fn push(&mut self, now: Duration) -> Result<Admission, Refusal> {
62
70
  self.push_weighted(now, NonZeroU32::MIN)
63
71
  }
64
72
 
65
73
  /// Account one item costing `cost` capacity units; the caller stores its
66
- /// payload only on acceptance.
67
- #[must_use]
68
- pub fn push_weighted(&mut self, now: Duration, cost: NonZeroU32) -> Admission {
69
- if !self.observe(now) {
70
- return Admission::Rejected;
71
- }
72
- let Some(deadline) = self.deadline.or_else(|| now.checked_add(self.max_wait)) else {
73
- return Admission::Rejected;
74
+ /// payload only when the push is honoured.
75
+ ///
76
+ /// # Errors
77
+ ///
78
+ /// [`Refusal::TimeRegression`] when `now` is earlier than the latest
79
+ /// observed instant, [`Refusal::Overflow`] when the item would start a
80
+ /// batch and `now + max_wait` does not fit a `Duration`, [`Refusal::Full`]
81
+ /// when `cost` exceeds the unspent capacity. Nothing changed: `now` is
82
+ /// not observed.
83
+ pub fn push_weighted(&mut self, now: Duration, cost: NonZeroU32) -> Result<Admission, Refusal> {
84
+ self.check(now)?;
85
+ let deadline = match self.deadline {
86
+ Some(deadline) => deadline,
87
+ None => now.checked_add(self.max_wait).ok_or(Refusal::Overflow)?,
74
88
  };
75
- if !self.credits.try_acquire(cost) {
76
- return Admission::Full;
89
+ // Ask the window first, then act: an acquisition within `available()`
90
+ // cannot be refused, so no flow refusal is mapped onto `Full`.
91
+ if cost.get() > self.credits.available() {
92
+ return Err(Refusal::Full);
93
+ }
94
+ match self.credits.try_acquire(cost) {
95
+ Ok(()) => {}
96
+ Err(
97
+ flow_machines::Refusal::Insufficient { .. }
98
+ | flow_machines::Refusal::ExceedsInFlight { .. },
99
+ ) => {
100
+ debug_assert!(false, "the window refused a cost within available()");
101
+ return Err(Refusal::Full);
102
+ }
77
103
  }
104
+ self.observed = now;
105
+ // Each item holds at least one credit of a u32 capacity, so no wrap.
78
106
  self.items += 1;
79
107
  self.deadline = Some(deadline);
80
- self.reason(now)
81
- .map_or(Admission::Buffered, Admission::Flush)
108
+ Ok(self
109
+ .reason(now)
110
+ .map_or(Admission::Buffered, Admission::Flush))
82
111
  }
83
112
 
84
- /// Recommend a flush without changing pending work.
85
- #[must_use]
86
- pub fn poll(&mut self, now: Duration) -> Option<FlushReason> {
87
- if !self.observe(now) {
88
- return None;
113
+ /// Recommend a flush without changing pending work: `Ok(None)` is the
114
+ /// honoured answer "nothing is due at this instant". Every honoured poll
115
+ /// observes `now`, `Ok(None)` included: the answer depends on it.
116
+ ///
117
+ /// # Errors
118
+ ///
119
+ /// [`Refusal::TimeRegression`] when `now` is earlier than the latest
120
+ /// observed instant; nothing changed.
121
+ pub fn poll(&mut self, now: Duration) -> Result<Option<FlushReason>, Refusal> {
122
+ self.check(now)?;
123
+ self.observed = now;
124
+ Ok(self.reason(now))
125
+ }
126
+
127
+ /// Acknowledge a full flush or cancellation: every pending item leaves,
128
+ /// the deadline is cleared, and the old item count is the answer.
129
+ ///
130
+ /// A flush that empties the batch observes `now`. Flushing an empty batch
131
+ /// is an honoured repeat: it answers zero whatever the time, so it
132
+ /// changes nothing and observes nothing.
133
+ ///
134
+ /// # Errors
135
+ ///
136
+ /// [`Refusal::TimeRegression`] when `now` is earlier than the latest
137
+ /// observed instant; nothing changed.
138
+ pub fn flush(&mut self, now: Duration) -> Result<u32, Refusal> {
139
+ self.check(now)?;
140
+ if self.items == 0 {
141
+ return Ok(0);
89
142
  }
90
- self.reason(now)
143
+ self.observed = now;
144
+ self.credits = CreditWindow::new(self.capacity);
145
+ self.deadline = None;
146
+ Ok(core::mem::take(&mut self.items))
91
147
  }
92
148
 
93
- /// Acknowledge a full flush/cancellation and return the old item count.
149
+ /// Step the caller's controller once and aim the target at its output:
150
+ /// exactly `pid.step(error, elapsed)` then [`Self::retarget`]. The answer
151
+ /// is the new target.
94
152
  ///
95
- /// # Panics
96
- /// Panics if internal capacity accounting is inconsistent.
97
- pub fn flush(&mut self, now: Duration) -> Option<u32> {
98
- if !self.observe(now) {
99
- return None;
153
+ /// It is `adapt`, not `adapt_from`: the controller is stepped, not read,
154
+ /// so its integral and derivative history move with every honoured call.
155
+ ///
156
+ /// # Errors
157
+ ///
158
+ /// [`Refusal::NotFinite`] for a NaN or infinite `error`,
159
+ /// [`Refusal::InvalidDuration`] for a zero `elapsed`, [`Refusal::Overflow`]
160
+ /// when a term of the PID calculation is not finite. Nothing changed, in
161
+ /// the batch or in the controller.
162
+ pub fn adapt(&mut self, pid: &mut Pid, error: f64, elapsed: Duration) -> Result<u32, Refusal> {
163
+ match pid.step(error, elapsed) {
164
+ // A PID output lies within its finite limits.
165
+ Ok(output) => Ok(self.aim(output)),
166
+ Err(feedback_machines::Refusal::NotFinite) => Err(Refusal::NotFinite),
167
+ Err(feedback_machines::Refusal::InvalidDuration) => Err(Refusal::InvalidDuration),
168
+ Err(feedback_machines::Refusal::Overflow) => Err(Refusal::Overflow),
100
169
  }
101
- if let Some(cost) = NonZeroU32::new(self.credits.in_flight()) {
102
- assert!(self.credits.release(cost));
170
+ }
171
+
172
+ /// Aim the target at `output`, a cost: truncated toward zero and clamped
173
+ /// to `1..=capacity`. The answer is the new target. Pending work and its
174
+ /// deadline are untouched; setting the target it already has changes
175
+ /// nothing.
176
+ ///
177
+ /// # Errors
178
+ ///
179
+ /// [`Refusal::NotFinite`] for a NaN or infinite `output`; nothing changed.
180
+ pub fn retarget(&mut self, output: f64) -> Result<u32, Refusal> {
181
+ if output.is_finite() {
182
+ Ok(self.aim(output))
183
+ } else {
184
+ Err(Refusal::NotFinite)
103
185
  }
104
- let count = self.items;
105
- self.items = 0;
106
- self.deadline = None;
107
- Some(count)
108
186
  }
109
187
 
110
- /// Interpret finite PID output as a target cost, clamped to capacity.
111
- #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
112
- pub fn adapt(&mut self, pid: &mut Pid, error: f64, elapsed: Duration) -> Option<u32> {
113
- let output = pid.step(error, elapsed)?;
114
- let count = output.clamp(1.0, f64::from(self.credits.capacity())) as u32;
115
- self.target = NonZeroU32::new(count)?;
116
- Some(count)
188
+ /// Hard admission limit, in cost units.
189
+ #[must_use]
190
+ pub const fn capacity(&self) -> u32 {
191
+ self.capacity.get()
192
+ }
193
+
194
+ /// Longest the oldest pending item waits before `Deadline` is due.
195
+ #[must_use]
196
+ pub const fn max_wait(&self) -> Duration {
197
+ self.max_wait
117
198
  }
118
199
 
119
200
  /// Number of accepted items not yet acknowledged by `flush`.
@@ -134,15 +215,22 @@ impl Batch {
134
215
  self.target.get()
135
216
  }
136
217
 
137
- /// Absolute time at which `poll` first reports `Deadline`, while items are pending.
218
+ /// Absolute time at which `poll` first reports `Deadline`; `None` while
219
+ /// nothing is pending.
138
220
  #[must_use]
139
221
  pub const fn deadline(&self) -> Option<Duration> {
140
- if self.items == 0 {
141
- return None;
142
- }
143
222
  self.deadline
144
223
  }
145
224
 
225
+ #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
226
+ fn aim(&mut self, output: f64) -> u32 {
227
+ // Clamped to `1.0..=capacity`, so the cast is exact and at least one:
228
+ // the target is one plus the rest, and no zero arm exists.
229
+ let cost = output.clamp(1.0, f64::from(self.capacity.get())) as u32;
230
+ self.target = NonZeroU32::MIN.saturating_add(cost.saturating_sub(1));
231
+ self.target.get()
232
+ }
233
+
146
234
  fn reason(&self, now: Duration) -> Option<FlushReason> {
147
235
  if self.deadline.is_some_and(|deadline| now >= deadline) {
148
236
  Some(FlushReason::Deadline)
@@ -153,12 +241,12 @@ impl Batch {
153
241
  }
154
242
  }
155
243
 
156
- fn observe(&mut self, now: Duration) -> bool {
157
- if now < self.observed {
158
- return false;
244
+ /// Refuse a regressed clock without recording anything.
245
+ const fn check(&self, now: Duration) -> Result<(), Refusal> {
246
+ if now.as_nanos() < self.observed.as_nanos() {
247
+ return Err(Refusal::TimeRegression);
159
248
  }
160
- self.observed = now;
161
- true
249
+ Ok(())
162
250
  }
163
251
  }
164
252
 
@@ -0,0 +1,34 @@
1
+ use core::fmt;
2
+
3
+ /// Why a call was not honoured. A refused call changes nothing: no item is
4
+ /// counted, no cost is held, and the clock it carried is not observed.
5
+ #[derive(Debug, Clone, Copy, PartialEq, Eq)]
6
+ pub enum Refusal {
7
+ /// `now` is earlier than the latest instant the batch observed.
8
+ TimeRegression,
9
+ /// A value the call had to compute is out of range: `now + max_wait` does
10
+ /// not fit a `Duration` (a push that would start a batch), or a term of
11
+ /// the PID calculation is not finite (`adapt`).
12
+ Overflow,
13
+ /// The item costs more than the capacity still unspent. Flush first; an
14
+ /// item costing more than the whole capacity is never admitted.
15
+ Full,
16
+ /// The PID error (`adapt`) or the output (`retarget`) is NaN or infinite.
17
+ NotFinite,
18
+ /// The elapsed time handed to `adapt` is zero.
19
+ InvalidDuration,
20
+ }
21
+
22
+ impl fmt::Display for Refusal {
23
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
24
+ f.write_str(match self {
25
+ Self::TimeRegression => "now is earlier than the latest observed instant",
26
+ Self::Overflow => "a computed deadline or controller term is out of range",
27
+ Self::Full => "the item costs more than the capacity still unspent",
28
+ Self::NotFinite => "the error or output is NaN or infinite",
29
+ Self::InvalidDuration => "the elapsed time is zero",
30
+ })
31
+ }
32
+ }
33
+
34
+ impl core::error::Error for Refusal {}
@@ -1,6 +1,6 @@
1
1
  [package]
2
2
  name = "batch_machines_native"
3
- version = "0.1.4"
3
+ version = "0.1.8"
4
4
  edition.workspace = true
5
5
  rust-version.workspace = true
6
6
  license.workspace = true
@@ -16,6 +16,7 @@ batch-machines.workspace = true
16
16
  feedback-machines.workspace = true
17
17
  magnus.workspace = true
18
18
  rb-sys.workspace = true
19
+ matryona-machines = { workspace = true, features = ["ruby"] }
19
20
 
20
21
  [lints]
21
22
  workspace = true