Skip to main content

aither_core/
ids.rs

1//! Model-facing ids: the words a model reads and types back to name what it
2//! can address, such as a background job, a stored output or a finished
3//! subagent.
4//!
5//! aither mints none of them itself: each is leased from an [`IdAllocator`]
6//! the embedder supplies, and the lease lasts as long as what the word names
7//! can still be addressed. An embedder that also names its own things for the
8//! model leases their words from the same allocator, so no two live ids share
9//! a word. [`WordAllocator`] is the allocator used when none is supplied.
10
11use alloc::{
12    boxed::Box,
13    collections::BTreeMap,
14    string::String,
15    sync::{Arc, Weak},
16};
17use core::{
18    fmt,
19    ops::Deref,
20    sync::atomic::{AtomicBool, AtomicUsize, Ordering},
21};
22
23/// Hands out the words that name what a model can address.
24///
25/// [`lease`](Self::lease) hands out a word no live lease holds, and
26/// [`release`](Self::release) takes it back once what it names can no longer
27/// be addressed. Callers lease through [`AnyIdAllocator::lease`], whose
28/// [`IdLease`] releases the word when its last clone drops, so every lease is
29/// released exactly once. [`claim`](Self::claim) leases one word by name, for
30/// an embedder that keeps a word naming the same thing across restarts.
31///
32/// A word is one or more lowercase ASCII letters: it names files, is written
33/// into commands and is recognized in text the model wrote.
34pub trait IdAllocator: Send + Sync + 'static {
35    /// Leases a word that no live lease holds.
36    ///
37    /// # Errors
38    ///
39    /// Returns [`IdsExhausted`] when every word the allocator can hand out is
40    /// leased.
41    fn lease(&self) -> Result<String, IdsExhausted>;
42
43    /// Leases `word` itself, for an embedder that persisted a lease and
44    /// restores it after a restart.
45    ///
46    /// # Errors
47    ///
48    /// Returns [`WordUnavailable`] when a live lease holds `word` or the
49    /// allocator never hands it out.
50    fn claim(&self, word: &str) -> Result<(), WordUnavailable>;
51
52    /// Ends the lease of `word`, which [`lease`](Self::lease) or
53    /// [`claim`](Self::claim) handed out and which has not been released
54    /// since.
55    fn release(&self, word: &str);
56}
57
58/// Every word an [`IdAllocator`] can hand out is leased.
59#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
60#[error("every model-facing id is leased")]
61pub struct IdsExhausted;
62
63/// A word an [`IdAllocator`] cannot hand out on a claim: a live lease holds
64/// it, or it is not one of the allocator's words.
65#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
66#[error("the model-facing id '{0}' is leased or not one this allocator hands out")]
67pub struct WordUnavailable(pub String);
68
69/// A shared [`IdAllocator`].
70///
71/// Clones lease from the same allocator. The default is a [`WordAllocator`]
72/// over its built-in word list.
73#[derive(Clone)]
74pub struct AnyIdAllocator(Arc<dyn IdAllocator>);
75
76impl AnyIdAllocator {
77    /// Shares `allocator`.
78    pub fn new(allocator: impl IdAllocator) -> Self {
79        Self(Arc::new(allocator))
80    }
81
82    /// Leases a word that no live lease holds; it is released when the last
83    /// clone of the returned lease drops.
84    ///
85    /// # Errors
86    ///
87    /// Returns [`IdsExhausted`] when every word is leased.
88    ///
89    /// # Panics
90    ///
91    /// Panics when the allocator hands out a word that is not one or more
92    /// lowercase ASCII letters.
93    pub fn lease(&self) -> Result<IdLease, IdsExhausted> {
94        let word = self.0.lease()?;
95        assert!(
96            is_word(&word),
97            "the id allocator handed out '{word}', which is not one or more lowercase ASCII letters"
98        );
99        Ok(self.held(word))
100    }
101
102    /// Leases `word` itself, as [`IdAllocator::claim`] does; it is released
103    /// when the last clone of the returned lease drops.
104    ///
105    /// # Errors
106    ///
107    /// Returns [`WordUnavailable`] when a live lease holds `word` or the
108    /// allocator never hands it out.
109    pub fn claim(&self, word: &str) -> Result<IdLease, WordUnavailable> {
110        self.0.claim(word)?;
111        Ok(self.held(String::from(word)))
112    }
113
114    fn held(&self, word: String) -> IdLease {
115        IdLease(Arc::new(Held {
116            word,
117            allocator: self.clone(),
118        }))
119    }
120}
121
122/// Whether `word` has the shape every model-facing id has.
123fn is_word(word: &str) -> bool {
124    !word.is_empty() && word.bytes().all(|byte| byte.is_ascii_lowercase())
125}
126
127impl Default for AnyIdAllocator {
128    fn default() -> Self {
129        Self::new(WordAllocator::default())
130    }
131}
132
133impl fmt::Debug for AnyIdAllocator {
134    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
135        f.debug_struct("AnyIdAllocator").finish_non_exhaustive()
136    }
137}
138
139/// A word leased from an [`AnyIdAllocator`].
140///
141/// Clones share the lease, which ends when the last of them drops: whatever
142/// can still address the named thing holds a clone.
143#[derive(Clone)]
144pub struct IdLease(Arc<Held>);
145
146/// The word of a lease and the allocator it goes back to.
147struct Held {
148    word: String,
149    allocator: AnyIdAllocator,
150}
151
152impl Drop for Held {
153    fn drop(&mut self) {
154        self.allocator.0.release(&self.word);
155    }
156}
157
158impl IdLease {
159    /// The leased word.
160    #[must_use]
161    pub fn as_str(&self) -> &str {
162        &self.0.word
163    }
164
165    /// Whether `other` is a clone of this lease, not merely a lease of the
166    /// same word: a word released and leased again names something else.
167    #[must_use]
168    pub fn same_lease(&self, other: &Self) -> bool {
169        Arc::ptr_eq(&self.0, &other.0)
170    }
171
172    /// A reference to this lease that does not keep the word leased.
173    #[must_use]
174    pub fn downgrade(&self) -> WeakIdLease {
175        WeakIdLease(Arc::downgrade(&self.0))
176    }
177}
178
179/// A reference to an [`IdLease`] that does not keep its word leased, for
180/// what must still tell whether the word names the same thing later.
181#[derive(Clone)]
182pub struct WeakIdLease(Weak<Held>);
183
184impl WeakIdLease {
185    /// The lease, while a clone of it still holds the word; `None` once the
186    /// word went back to its allocator, after which it may name something
187    /// else.
188    #[must_use]
189    pub fn upgrade(&self) -> Option<IdLease> {
190        self.0.upgrade().map(IdLease)
191    }
192
193    /// Whether this refers to `lease` itself, not merely to a lease of the
194    /// same word.
195    #[must_use]
196    pub fn refers_to(&self, lease: &IdLease) -> bool {
197        // The weak reference keeps the lease's allocation, so no later lease
198        // can share its address.
199        core::ptr::eq(self.0.as_ptr(), Arc::as_ptr(&lease.0))
200    }
201}
202
203impl fmt::Debug for WeakIdLease {
204    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
205        f.write_str("WeakIdLease")
206    }
207}
208
209impl Deref for IdLease {
210    type Target = str;
211
212    fn deref(&self) -> &str {
213        self.as_str()
214    }
215}
216
217impl AsRef<str> for IdLease {
218    fn as_ref(&self) -> &str {
219        self.as_str()
220    }
221}
222
223impl fmt::Display for IdLease {
224    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
225        f.write_str(self.as_str())
226    }
227}
228
229impl fmt::Debug for IdLease {
230    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
231        f.debug_tuple("IdLease").field(&self.as_str()).finish()
232    }
233}
234
235/// The words of the default [`WordAllocator`]: the BIP-39 English word list
236/// (CC0), 2048 common English words, SHA-256
237/// `2f5eed53a4727b4bf8880d8f3f199efc90e58503646d9ff8eff3a2ed3b24dbda`.
238const ENGLISH_WORDS: &str = include_str!("ids/english.txt");
239
240/// An [`IdAllocator`] over a fixed list of words.
241///
242/// It hands the words out in list order, moving on past each one it leases,
243/// so a word just released is the last to come back. [`Default`] uses a
244/// built-in list of 2048 common English words.
245pub struct WordAllocator {
246    words: Box<[Box<str>]>,
247    /// Each word's position in `words`.
248    positions: BTreeMap<Box<str>, usize>,
249    leased: Box<[AtomicBool]>,
250    /// Where the next lease starts looking.
251    cursor: AtomicUsize,
252}
253
254impl WordAllocator {
255    /// An allocator handing out `words`.
256    ///
257    /// # Panics
258    ///
259    /// Panics when `words` is empty, holds one word twice, or holds a word
260    /// that is not one or more lowercase ASCII letters.
261    pub fn new<W: Into<Box<str>>>(words: impl IntoIterator<Item = W>) -> Self {
262        let words: Box<[Box<str>]> = words.into_iter().map(Into::into).collect();
263        assert!(!words.is_empty(), "a word allocator needs words");
264        let mut positions = BTreeMap::new();
265        for (position, word) in words.iter().enumerate() {
266            assert!(
267                is_word(word),
268                "'{word}' is not one or more lowercase ASCII letters"
269            );
270            assert!(
271                positions.insert(word.clone(), position).is_none(),
272                "the word '{word}' is listed twice"
273            );
274        }
275        let leased = words.iter().map(|_| AtomicBool::new(false)).collect();
276        Self {
277            words,
278            positions,
279            leased,
280            cursor: AtomicUsize::new(0),
281        }
282    }
283}
284
285impl Default for WordAllocator {
286    fn default() -> Self {
287        Self::new(ENGLISH_WORDS.lines())
288    }
289}
290
291impl fmt::Debug for WordAllocator {
292    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
293        f.debug_struct("WordAllocator")
294            .field("words", &self.words.len())
295            .finish_non_exhaustive()
296    }
297}
298
299impl IdAllocator for WordAllocator {
300    fn lease(&self) -> Result<String, IdsExhausted> {
301        let count = self.words.len();
302        for _ in 0..count {
303            let position = self.cursor.fetch_add(1, Ordering::Relaxed) % count;
304            if !self.leased[position].swap(true, Ordering::AcqRel) {
305                return Ok(String::from(&*self.words[position]));
306            }
307        }
308        Err(IdsExhausted)
309    }
310
311    fn claim(&self, word: &str) -> Result<(), WordUnavailable> {
312        let unavailable = || WordUnavailable(String::from(word));
313        let position = *self.positions.get(word).ok_or_else(unavailable)?;
314        if self.leased[position].swap(true, Ordering::AcqRel) {
315            return Err(unavailable());
316        }
317        Ok(())
318    }
319
320    fn release(&self, word: &str) {
321        let position = *self
322            .positions
323            .get(word)
324            .unwrap_or_else(|| panic!("released '{word}', which this allocator never leased"));
325        assert!(
326            self.leased[position].swap(false, Ordering::AcqRel),
327            "released '{word}', which is not leased"
328        );
329    }
330}
331
332#[cfg(test)]
333mod tests {
334    use alloc::string::ToString;
335
336    use super::*;
337
338    #[test]
339    fn the_default_list_is_single_lowercase_words() {
340        assert_eq!(ENGLISH_WORDS.lines().count(), 2048);
341        // Building it checks every word's shape and that none is listed twice.
342        let _ = WordAllocator::default();
343    }
344
345    #[test]
346    #[should_panic(expected = "is not one or more lowercase ASCII letters")]
347    fn a_word_of_another_shape_is_refused() {
348        let _ = WordAllocator::new(["river", "task-1"]);
349    }
350
351    /// An allocator that hands out a word of the wrong shape.
352    struct Numbered;
353
354    impl IdAllocator for Numbered {
355        fn lease(&self) -> Result<String, IdsExhausted> {
356            Ok("7".to_string())
357        }
358
359        fn claim(&self, word: &str) -> Result<(), WordUnavailable> {
360            Err(WordUnavailable(word.to_string()))
361        }
362
363        fn release(&self, _word: &str) {}
364    }
365
366    #[test]
367    #[should_panic(expected = "handed out '7'")]
368    fn an_embedder_word_of_another_shape_fails_the_lease() {
369        let _ = AnyIdAllocator::new(Numbered).lease();
370    }
371
372    #[test]
373    fn live_leases_never_share_a_word_and_a_released_word_comes_back() {
374        let ids = AnyIdAllocator::new(WordAllocator::new(["river", "stone"]));
375        let river = ids.lease().expect("a free word");
376        let stone = ids.lease().expect("a free word");
377        assert_eq!((river.as_str(), stone.as_str()), ("river", "stone"));
378        assert_eq!(ids.lease().unwrap_err(), IdsExhausted);
379
380        drop(river);
381        assert_eq!(
382            ids.lease().expect("river is free again").to_string(),
383            "river"
384        );
385    }
386
387    #[test]
388    fn a_lease_ends_with_its_last_clone() {
389        let ids = AnyIdAllocator::new(WordAllocator::new(["river"]));
390        let lease = ids.lease().expect("a free word");
391        let held = lease.clone();
392        drop(lease);
393        assert_eq!(
394            ids.lease().unwrap_err(),
395            IdsExhausted,
396            "a clone still holds it"
397        );
398        drop(held);
399        assert_eq!(
400            &*ids.lease().expect("released with the last clone"),
401            "river"
402        );
403    }
404
405    #[test]
406    fn only_clones_are_the_same_lease() {
407        let ids = AnyIdAllocator::new(WordAllocator::new(["river"]));
408        let lease = ids.lease().expect("a free word");
409        assert!(lease.same_lease(&lease.clone()));
410        drop(lease);
411        let again = ids.lease().expect("river is free again");
412        let other = AnyIdAllocator::new(WordAllocator::new(["river"]))
413            .lease()
414            .expect("a free word");
415        assert_eq!(again.as_str(), other.as_str());
416        assert!(!again.same_lease(&other), "a word alone is not the lease");
417
418        let weak = again.downgrade();
419        assert!(weak.refers_to(&again));
420        assert!(!weak.refers_to(&other));
421        drop(again);
422        let after = ids.lease().expect("river is free again");
423        assert!(
424            !weak.refers_to(&after),
425            "a released lease is not its successor"
426        );
427    }
428
429    #[test]
430    fn a_weak_lease_upgrades_only_while_the_word_is_held() {
431        let ids = AnyIdAllocator::new(WordAllocator::new(["river"]));
432        let lease = ids.lease().expect("a free word");
433        let weak = lease.downgrade();
434        assert_eq!(weak.upgrade().as_deref(), Some("river"));
435        drop(lease);
436        assert!(weak.upgrade().is_none(), "the word went back");
437        let again = ids.lease().expect("river is free again");
438        assert!(
439            weak.upgrade().is_none(),
440            "a word leased again names something else: {again}"
441        );
442    }
443
444    #[test]
445    fn a_claimed_word_is_leased_until_its_lease_drops() {
446        let ids = AnyIdAllocator::new(WordAllocator::new(["river", "stone"]));
447        let river = ids.claim("river").expect("river is free");
448        assert_eq!(river.as_str(), "river");
449        assert_eq!(
450            ids.claim("river").unwrap_err(),
451            WordUnavailable("river".to_string()),
452            "a live lease holds it"
453        );
454        let stone = ids.lease().expect("stone is free");
455        assert_eq!(stone.as_str(), "stone");
456        assert_eq!(ids.lease().unwrap_err(), IdsExhausted, "river is claimed");
457        drop(river);
458        assert_eq!(&*ids.claim("river").expect("released"), "river");
459    }
460
461    #[test]
462    fn a_word_outside_the_list_cannot_be_claimed() {
463        let ids = AnyIdAllocator::new(WordAllocator::new(["river"]));
464        assert_eq!(
465            ids.claim("stone").unwrap_err(),
466            WordUnavailable("stone".to_string())
467        );
468    }
469
470    #[test]
471    #[should_panic(expected = "is listed twice")]
472    fn a_word_listed_twice_is_refused() {
473        let _ = WordAllocator::new(["river", "river"]);
474    }
475
476    #[test]
477    #[should_panic(expected = "which is not leased")]
478    fn releasing_a_free_word_is_a_bug() {
479        WordAllocator::new(["river"]).release("river");
480    }
481}