arbiter_machines 0.1.5 → 0.3.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,34 @@
1
1
  # Changelog
2
2
 
3
+ ## [0.4.1](https://github.com/seuros/arbiter_machines/compare/arbiter-machines-v0.4.0...arbiter-machines-v0.4.1) (2026-11-16)
4
+
5
+
6
+ ### Bug Fixes
7
+
8
+ * replace runtime indexing in the arbiter core with checked lookups ([5112385](https://github.com/seuros/arbiter_machines/commit/511238591c81c6765c0bdaf844cf5d27afd6ddbb))
9
+
10
+ ## [0.4.0](https://github.com/seuros/arbiter_machines/compare/arbiter-machines-v0.3.0...arbiter-machines-v0.4.0) (2026-11-14)
11
+
12
+
13
+ ### ⚠ BREAKING CHANGES
14
+
15
+ * adopt matryona-machines 0.2 (symbols! tables, exact arrays, frozen-first)
16
+
17
+ ### Features
18
+
19
+ * adopt matryona-machines 0.2 (symbols! tables, exact arrays, frozen-first) ([73fb802](https://github.com/seuros/arbiter_machines/commit/73fb8026556f3fb5982c5e65411d9bc03d36c60d))
20
+
21
+ ## [0.3.0](https://github.com/seuros/arbiter_machines/compare/arbiter-machines-v0.2.2...arbiter-machines-v0.3.0) (2026-11-14)
22
+
23
+
24
+ ### ⚠ BREAKING CHANGES
25
+
26
+ * answer Result with honoured repeats, clone-then-keep acquire, Blocked validated, sealed and resolved at load
27
+
28
+ ### Features
29
+
30
+ * answer Result with honoured repeats, clone-then-keep acquire, Blocked validated, sealed and resolved at load ([11a6258](https://github.com/seuros/arbiter_machines/commit/11a6258887d32dd37ea4d2c687528bab463db843))
31
+
3
32
  ## [0.2.2](https://github.com/seuros/arbiter_machines/compare/arbiter-machines-v0.2.1...arbiter-machines-v0.2.2) (2026-11-06)
4
33
 
5
34
 
@@ -1,13 +1,15 @@
1
1
  [package]
2
2
  name = "arbiter-machines"
3
- version = "0.2.2"
3
+ version = "0.4.1"
4
4
  edition.workspace = true
5
5
  rust-version.workspace = true
6
6
  license.workspace = true
7
7
  description = "Bounded ownership, priority inheritance, ceilings, and wait-cycle detection"
8
8
  readme = "README.md"
9
- exclude = ["src/**/tests.rs", "tests/"]
9
+ exclude = ["src/**/tests.rs", "src/tests/", "tests/"]
10
10
  keywords = ["priority-inheritance", "priority-ceiling", "deadlock", "arbitration", "no-std"]
11
11
  categories = ["no-std", "algorithms", "concurrency"]
12
+ [dev-dependencies]
13
+ matryona-machines = { workspace = true, features = ["testing"] }
12
14
  [lints]
13
15
  workspace = true
@@ -12,9 +12,42 @@ transfer ownership.
12
12
  Inheritance propagates priorities transitively to owners. Immediate-ceiling mode
13
13
  raises owners to held-resource ceilings and blocks acquisition unless effective
14
14
  priority exceeds every ceiling held by another task. Each configured resource
15
- ceiling must bound all tasks permitted to use it; requests exceeding it reject.
15
+ ceiling must bound all tasks permitted to use it; requests exceeding it are refused.
16
16
  The core detects prospective wait-for cycles before inserting a wait.
17
17
 
18
18
  These decisions require an executor honoring priorities and ownership. No OS
19
19
  priority manipulation, lock implementation, waiter-queue fairness, preemption
20
20
  driver, multi-resource atomic acquisition, or Ruby scheduling guarantee.
21
+
22
+ ## Contract
23
+
24
+ - **Refusals.** `acquire`, `release` and `cancel_wait` return
25
+ `Result<_, Refusal>`; `Refusal` is the crate's one refusal type:
26
+ `UnknownTask`, `UnknownResource`, `AboveCeiling` (immediate ceiling only: the
27
+ task's base priority exceeds the resource's declared ceiling), `Deadlock`
28
+ (recording the wait would close a wait-for cycle), `Unowned` (nobody owns the
29
+ resource), `WrongOwner`. A refusal changes nothing: no owner, no wait, no
30
+ priority moves.
31
+ - **Honoured answers.** `Acquisition::{Granted, AlreadyOwned, Blocked(r)}`,
32
+ `release -> Ok(())`, `Cancelling::{Cancelled, NotWaiting}`. `Blocked(r)` is a
33
+ state change, not a refusal: the task's wait on `r` is now recorded and its
34
+ priority is lent to the owner.
35
+ - **Waiting or running.** A task either waits or runs; a task that calls
36
+ `acquire` is running, so it has stopped waiting. `Granted` therefore clears
37
+ a wait the task had recorded on another resource, and `Blocked(r)` replaces
38
+ it. The answer does not name the dropped wait: the caller already holds it
39
+ (the `Blocked` it was given and has not cancelled) and `waiting_on(task)`
40
+ reads it before the call. A caller keeping its own waiter queues calls
41
+ `cancel_wait` when a task gives up a wait, which keeps both views equal.
42
+ - **Repeats.** Honoured when the arbiter can prove the effect already holds,
43
+ and then nothing changes: `AlreadyOwned` (the task owns the resource),
44
+ `Blocked(r)` again while `r` still blocks the task (that wait is already
45
+ recorded), `NotWaiting` (no wait recorded). A repeated `release` cannot be
46
+ proven, because no ownership history is kept: it is `Unowned`.
47
+ - **Exhaustive.** `Protocol`, `Acquisition`, `Cancelling` and `Refusal` carry
48
+ no `#[non_exhaustive]`; a new variant is a breaking change.
49
+ - **Scopes and restarts.** The arbiter issues no ids: tasks and resources are
50
+ caller indices below `T` and `R`. A new arbiter owns nothing and has no waits.
51
+ - **Time.** None. The arbiter reads and records no clock.
52
+ - **Readers.** `effective_priorities`, `owner`, `waiting_on`, `protocol`,
53
+ `task_count` (`T`) and `resource_count` (`R`) are pure.
@@ -1,30 +1,79 @@
1
1
  #![no_std]
2
+ #![cfg_attr(not(test), deny(clippy::indexing_slicing))]
2
3
  #![doc = include_str!("../README.md")]
3
4
 
5
+ use core::fmt;
6
+
4
7
  /// Resource priority protocol.
5
8
  #[derive(Debug, Clone, Copy, PartialEq, Eq)]
6
- #[non_exhaustive]
7
9
  pub enum Protocol {
8
10
  /// Transitive inheritance from blocked waiters.
9
11
  Inheritance,
10
12
  /// Immediate ceilings plus system-ceiling admission.
11
13
  ImmediateCeiling,
12
14
  }
13
- /// Acquisition decision; no underlying lock is manipulated.
15
+
16
+ /// Honoured answer to [`Arbiter::acquire`]; no underlying lock is manipulated.
14
17
  #[derive(Debug, Clone, Copy, PartialEq, Eq)]
15
- #[non_exhaustive]
16
18
  pub enum Acquisition {
17
- /// Caller may acquire the resource.
19
+ /// The task now owns the resource. A task that asks is running, not
20
+ /// waiting, so a wait it had recorded on another resource is cleared; the
21
+ /// caller learns that wait from the `Blocked` it was given, or from
22
+ /// [`Arbiter::waiting_on`] before the call.
18
23
  Granted,
19
- /// Caller owns it; recursion depth is not tracked.
24
+ /// The task already owns the resource: an idempotent repeat that changed
25
+ /// nothing. Recursion depth is not tracked.
20
26
  AlreadyOwned,
21
- /// Caller must wait on this blocking resource index.
27
+ /// The task must wait, and its wait on this blocking resource index is now
28
+ /// recorded (replacing any earlier wait). Asking again while the same
29
+ /// resource still blocks answers the same and changes nothing.
22
30
  Blocked(usize),
23
- /// This wait would create a cycle; old state is retained.
31
+ }
32
+
33
+ /// Honoured answer to [`Arbiter::cancel_wait`].
34
+ #[derive(Debug, Clone, Copy, PartialEq, Eq)]
35
+ pub enum Cancelling {
36
+ /// The task's recorded wait was dropped.
37
+ Cancelled,
38
+ /// The task had no wait recorded: an idempotent repeat that changed nothing.
39
+ NotWaiting,
40
+ }
41
+
42
+ /// Why a call was not honoured. Every refusal leaves the arbiter exactly as
43
+ /// it was: no owner, no wait moves.
44
+ #[derive(Debug, Clone, Copy, PartialEq, Eq)]
45
+ pub enum Refusal {
46
+ /// The task index is not one of the arbiter's `T` tasks.
47
+ UnknownTask,
48
+ /// The resource index is not one of the arbiter's `R` resources.
49
+ UnknownResource,
50
+ /// Under [`Protocol::ImmediateCeiling`], the task's base priority is above
51
+ /// the resource's declared ceiling: a misdeclaration.
52
+ AboveCeiling,
53
+ /// Recording this wait would close a wait-for cycle.
24
54
  Deadlock,
25
- /// Invalid index or declared ceiling.
26
- Invalid,
55
+ /// Nobody owns the resource. A repeated release lands here: the arbiter
56
+ /// keeps no history, so it cannot prove the task ever owned it.
57
+ Unowned,
58
+ /// Another task owns the resource.
59
+ WrongOwner,
60
+ }
61
+
62
+ impl fmt::Display for Refusal {
63
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
64
+ f.write_str(match self {
65
+ Self::UnknownTask => "no such task",
66
+ Self::UnknownResource => "no such resource",
67
+ Self::AboveCeiling => "task priority is above the resource ceiling",
68
+ Self::Deadlock => "waiting would close a wait-for cycle",
69
+ Self::Unowned => "nobody owns the resource",
70
+ Self::WrongOwner => "another task owns the resource",
71
+ })
72
+ }
27
73
  }
74
+
75
+ impl core::error::Error for Refusal {}
76
+
28
77
  /// Fixed task/resource ownership and wait-for graph.
29
78
  #[derive(Debug, Clone, PartialEq, Eq)]
30
79
  pub struct Arbiter<const T: usize, const R: usize> {
@@ -34,8 +83,10 @@ pub struct Arbiter<const T: usize, const R: usize> {
34
83
  owners: [Option<usize>; R],
35
84
  waiting: [Option<usize>; T],
36
85
  }
86
+
37
87
  impl<const T: usize, const R: usize> Arbiter<T, R> {
38
- /// Configure base priorities and resource ceilings.
88
+ /// Configure base priorities and resource ceilings. Nothing is owned and
89
+ /// nobody waits.
39
90
  #[must_use]
40
91
  pub const fn new(base: [u32; T], ceilings: [u32; R], protocol: Protocol) -> Self {
41
92
  Self {
@@ -46,95 +97,121 @@ impl<const T: usize, const R: usize> Arbiter<T, R> {
46
97
  waiting: [None; T],
47
98
  }
48
99
  }
100
+
49
101
  /// Acquire or record one wait; the caller enforces the decision.
50
- #[must_use]
51
- pub fn acquire(&mut self, task: usize, resource: usize) -> Acquisition {
52
- if task >= T || resource >= R {
53
- return Acquisition::Invalid;
102
+ ///
103
+ /// # Errors
104
+ ///
105
+ /// [`Refusal::UnknownTask`], [`Refusal::UnknownResource`],
106
+ /// [`Refusal::AboveCeiling`] or [`Refusal::Deadlock`]. Nothing changes.
107
+ pub fn acquire(&mut self, task: usize, resource: usize) -> Result<Acquisition, Refusal> {
108
+ let base = *self.base.get(task).ok_or(Refusal::UnknownTask)?;
109
+ let ceiling = *self
110
+ .ceilings
111
+ .get(resource)
112
+ .ok_or(Refusal::UnknownResource)?;
113
+ if self.protocol == Protocol::ImmediateCeiling && base > ceiling {
114
+ return Err(Refusal::AboveCeiling);
54
115
  }
55
- if self.protocol == Protocol::ImmediateCeiling && self.base[task] > self.ceilings[resource]
56
- {
57
- return Acquisition::Invalid;
116
+ let owner = self.owner(resource);
117
+ if owner == Some(task) {
118
+ return Ok(Acquisition::AlreadyOwned);
58
119
  }
59
- if self.owners[resource] == Some(task) {
60
- return Acquisition::AlreadyOwned;
61
- }
62
- let blocker = if self.owners[resource].is_some() {
63
- Some(resource)
64
- } else if self.protocol == Protocol::ImmediateCeiling {
65
- let effective = self.effective_priorities()[task];
66
- self.owners
67
- .iter()
68
- .enumerate()
69
- .find(|&(index, owner)| {
70
- owner.is_some_and(|owner| owner != task) && effective <= self.ceilings[index]
71
- })
72
- .map(|(index, _)| index)
73
- } else {
74
- None
120
+ let blocker = match owner {
121
+ Some(_) => Some(resource),
122
+ None => self.ceiling_blocker(task, base),
75
123
  };
76
124
  let Some(blocker) = blocker else {
77
- self.owners[resource] = Some(task);
78
- self.waiting[task] = None;
79
- return Acquisition::Granted;
125
+ let (owner, wait) = self.slots_mut(task, resource)?;
126
+ *owner = Some(task);
127
+ *wait = None;
128
+ return Ok(Acquisition::Granted);
80
129
  };
81
- let mut holder = self.owners[blocker];
130
+ let mut holder = self.owner(blocker);
82
131
  for _ in 0..T {
83
132
  let Some(owner) = holder else {
84
133
  break;
85
134
  };
86
135
  if owner == task {
87
- return Acquisition::Deadlock;
136
+ return Err(Refusal::Deadlock);
88
137
  }
89
- holder = self.waiting[owner].and_then(|resource| self.owners[resource]);
138
+ holder = self
139
+ .waiting_on(owner)
140
+ .and_then(|resource| self.owner(resource));
90
141
  }
91
- self.waiting[task] = Some(blocker);
92
- Acquisition::Blocked(blocker)
142
+ let (_, wait) = self.slots_mut(task, resource)?;
143
+ *wait = Some(blocker);
144
+ Ok(Acquisition::Blocked(blocker))
93
145
  }
94
- /// Release owned state and clear affected waits for explicit retries.
95
- #[must_use]
96
- pub fn release(&mut self, task: usize, resource: usize) -> bool {
97
- let Some(owner) = self.owners.get_mut(resource) else {
98
- return false;
99
- };
100
- if *owner != Some(task) {
101
- return false;
146
+
147
+ /// Release owned state and clear every wait on the resource, so the
148
+ /// waiters retry explicitly. Ownership is never handed over.
149
+ ///
150
+ /// # Errors
151
+ ///
152
+ /// [`Refusal::UnknownTask`], [`Refusal::UnknownResource`],
153
+ /// [`Refusal::Unowned`] when nobody owns the resource (a repeated release
154
+ /// included) or [`Refusal::WrongOwner`]. Nothing changes.
155
+ pub fn release(&mut self, task: usize, resource: usize) -> Result<(), Refusal> {
156
+ if task >= T {
157
+ return Err(Refusal::UnknownTask);
158
+ }
159
+ let owner = self
160
+ .owners
161
+ .get_mut(resource)
162
+ .ok_or(Refusal::UnknownResource)?;
163
+ match *owner {
164
+ None => return Err(Refusal::Unowned),
165
+ Some(current) if current != task => return Err(Refusal::WrongOwner),
166
+ Some(_) => *owner = None,
102
167
  }
103
- *owner = None;
104
168
  for wait in &mut self.waiting {
105
169
  if *wait == Some(resource) {
106
170
  *wait = None;
107
171
  }
108
172
  }
109
- true
173
+ Ok(())
110
174
  }
175
+
111
176
  /// Cancel a wait without releasing owned resources.
112
- #[must_use]
113
- pub fn cancel_wait(&mut self, task: usize) -> bool {
177
+ ///
178
+ /// # Errors
179
+ ///
180
+ /// [`Refusal::UnknownTask`]. Nothing changes.
181
+ pub fn cancel_wait(&mut self, task: usize) -> Result<Cancelling, Refusal> {
114
182
  let Some(wait) = self.waiting.get_mut(task) else {
115
- return false;
183
+ return Err(Refusal::UnknownTask);
116
184
  };
117
- *wait = None;
118
- true
185
+ Ok(match wait.take() {
186
+ Some(_) => Cancelling::Cancelled,
187
+ None => Cancelling::NotWaiting,
188
+ })
119
189
  }
190
+
120
191
  /// Effective priorities for the runtime executor.
121
192
  #[must_use]
122
193
  pub fn effective_priorities(&self) -> [u32; T] {
123
194
  let mut effective = self.base;
124
195
  if self.protocol == Protocol::ImmediateCeiling {
125
- for (resource, owner) in self.owners.iter().enumerate() {
126
- if let Some(owner) = owner {
127
- effective[*owner] = effective[*owner].max(self.ceilings[resource]);
128
- }
196
+ for (task, priority) in effective.iter_mut().enumerate() {
197
+ *priority = self.ceiling_priority(task, *priority);
129
198
  }
130
199
  } else {
131
200
  for _ in 0..T {
132
201
  let mut changed = false;
133
202
  for (task, resource) in self.waiting.iter().enumerate() {
134
- if let Some(owner) = resource.and_then(|resource| self.owners[resource])
135
- && effective[owner] < effective[task]
203
+ // `task` comes from enumerating `waiting`, which is as long
204
+ // as `effective`, so the lookup always lands; a missing
205
+ // owner is no edge to walk.
206
+ let Some(&inherited) = effective.get(task) else {
207
+ continue;
208
+ };
209
+ if let Some(slot) = resource
210
+ .and_then(|resource| self.owner(resource))
211
+ .and_then(|owner| effective.get_mut(owner))
212
+ && *slot < inherited
136
213
  {
137
- effective[owner] = effective[task];
214
+ *slot = inherited;
138
215
  changed = true;
139
216
  }
140
217
  }
@@ -145,6 +222,80 @@ impl<const T: usize, const R: usize> Arbiter<T, R> {
145
222
  }
146
223
  effective
147
224
  }
225
+
226
+ /// The task that owns `resource`; `None` when it is free or no such
227
+ /// resource exists.
228
+ #[must_use]
229
+ pub fn owner(&self, resource: usize) -> Option<usize> {
230
+ self.owners.get(resource).copied().flatten()
231
+ }
232
+
233
+ /// The resource `task` has a wait recorded on; `None` when it is not
234
+ /// waiting or no such task exists.
235
+ #[must_use]
236
+ pub fn waiting_on(&self, task: usize) -> Option<usize> {
237
+ self.waiting.get(task).copied().flatten()
238
+ }
239
+
240
+ /// The protocol this arbiter was configured with.
241
+ #[must_use]
242
+ pub const fn protocol(&self) -> Protocol {
243
+ self.protocol
244
+ }
245
+
246
+ /// Number of tasks (`T`).
247
+ #[must_use]
248
+ pub const fn task_count(&self) -> usize {
249
+ T
250
+ }
251
+
252
+ /// Number of resources (`R`).
253
+ #[must_use]
254
+ pub const fn resource_count(&self) -> usize {
255
+ R
256
+ }
257
+
258
+ /// The two slots `acquire` writes: `resource`'s owner and `task`'s wait.
259
+ /// `acquire` has already looked both indices up, so the refusals only
260
+ /// restate that; they are taken before anything is written.
261
+ fn slots_mut(
262
+ &mut self,
263
+ task: usize,
264
+ resource: usize,
265
+ ) -> Result<(&mut Option<usize>, &mut Option<usize>), Refusal> {
266
+ let wait = self.waiting.get_mut(task).ok_or(Refusal::UnknownTask)?;
267
+ let owner = self
268
+ .owners
269
+ .get_mut(resource)
270
+ .ok_or(Refusal::UnknownResource)?;
271
+ Ok((owner, wait))
272
+ }
273
+
274
+ /// `base` raised to the ceiling of every resource `task` owns.
275
+ fn ceiling_priority(&self, task: usize, base: u32) -> u32 {
276
+ self.owners
277
+ .iter()
278
+ .zip(&self.ceilings)
279
+ .filter(|(owner, _)| **owner == Some(task))
280
+ .fold(base, |priority, (_, &ceiling)| priority.max(ceiling))
281
+ }
282
+
283
+ /// Under [`Protocol::ImmediateCeiling`], the resource another task owns
284
+ /// whose ceiling stops `task` (base priority `base`) from taking a free
285
+ /// resource now, if any.
286
+ fn ceiling_blocker(&self, task: usize, base: u32) -> Option<usize> {
287
+ if self.protocol == Protocol::Inheritance {
288
+ return None;
289
+ }
290
+ let effective = self.ceiling_priority(task, base);
291
+ self.owners
292
+ .iter()
293
+ .zip(&self.ceilings)
294
+ .position(|(owner, &ceiling)| {
295
+ owner.is_some_and(|owner| owner != task) && effective <= ceiling
296
+ })
297
+ }
148
298
  }
299
+
149
300
  #[cfg(test)]
150
301
  mod tests;
@@ -1,6 +1,6 @@
1
1
  [package]
2
2
  name = "arbiter_machines_native"
3
- version = "0.1.3"
3
+ version = "0.1.6"
4
4
  edition.workspace = true
5
5
  rust-version.workspace = true
6
6
  license.workspace = true
@@ -16,6 +16,7 @@ doctest = false
16
16
  arbiter-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