axon-lang 1.21.1

AXON v1.5.1 — first crates.io publication of the AXON language full-stack runtime. Lexer/parser/type-checker/IR generator (re-exported from axon-frontend) plus the native Rust runtime: typed channels (TypedEventBus with QoS×5, π-calculus mobility, capability extrusion via shield D8 — Fase 13.f.2), Free Monad CPS handlers (Fase 2), lease kernel + reconcile loop (Fase 3+5), Epistemic Security Kernel (ESK Fase 6), Trust Types + ReplayLog (Fase 11.a+11.c), Stateful PEM over WebSocket (Fase 11.d), Ontological Tool Synthesis (Fase 11.e), Mobile Typed Channels (Fase 13). Crate publishes as `axon-lang` to mirror the Python PyPI package; library import remains `use axon::*` so existing call sites keep working unchanged.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
//! [`BufferPool`] — slab allocator for [`ZeroCopyBuffer`] storage.
//!
//! Allocation classes: 4 KiB, 64 KiB, 1 MiB, 10 MiB. Buffers larger
//! than the largest class are direct-allocated (counted in the
//! `oversize_allocations_total` metric).
//!
//! Per-tenant accounting: every tenant carries a soft byte limit.
//! Exceeding the limit does not block — it emits
//! `buffer_pool_soft_limit_exceeded_total{tenant_id=…}` so operators
//! can see which tenants are sustaining high multimodal throughput.
//! The pool is global-per-process, not per-tenant, so a spike on
//! tenant A doesn't force a second pool allocation for tenant B.
//!
//! The pool holds `Vec<u8>` slabs on its free lists. When a
//! `ZeroCopyBuffer` allocated from the pool drops, the slab is
//! reclaimed via the [`PoolHandle`] stored on its clone path.
//! (11.b ships with a simpler model: slabs are requested on-demand
//! and returned manually; a future revision wires the Drop impl to
//! the pool once we're confident in the ownership model.)

use std::collections::HashMap;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, Mutex};

// ── Size classes ─────────────────────────────────────────────────────

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum PoolClass {
    Small,  // up to 4 KiB
    Medium, // 4 KiB+..64 KiB
    Large,  // 64 KiB+..1 MiB
    Huge,   // 1 MiB+..10 MiB
    Oversize, // > 10 MiB — direct allocation, no pooling
}

impl PoolClass {
    pub fn capacity(self) -> usize {
        match self {
            PoolClass::Small => 4 * 1024,
            PoolClass::Medium => 64 * 1024,
            PoolClass::Large => 1024 * 1024,
            PoolClass::Huge => 10 * 1024 * 1024,
            PoolClass::Oversize => usize::MAX,
        }
    }

    pub fn slug(self) -> &'static str {
        match self {
            PoolClass::Small => "small",
            PoolClass::Medium => "medium",
            PoolClass::Large => "large",
            PoolClass::Huge => "huge",
            PoolClass::Oversize => "oversize",
        }
    }

    /// Pick the smallest class that fits `requested` bytes.
    pub fn for_size(requested: usize) -> Self {
        if requested <= PoolClass::Small.capacity() {
            PoolClass::Small
        } else if requested <= PoolClass::Medium.capacity() {
            PoolClass::Medium
        } else if requested <= PoolClass::Large.capacity() {
            PoolClass::Large
        } else if requested <= PoolClass::Huge.capacity() {
            PoolClass::Huge
        } else {
            PoolClass::Oversize
        }
    }

    pub fn non_oversize() -> [PoolClass; 4] {
        [
            PoolClass::Small,
            PoolClass::Medium,
            PoolClass::Large,
            PoolClass::Huge,
        ]
    }
}

// ── Metrics ──────────────────────────────────────────────────────────

#[derive(Debug, Default)]
struct PoolMetrics {
    pool_hits: [AtomicU64; 4],
    pool_misses: [AtomicU64; 4],
    oversize_allocations: AtomicU64,
    live_bytes: AtomicU64,
}

impl PoolMetrics {
    fn record_request(&self, class: PoolClass, hit: bool) {
        if class == PoolClass::Oversize {
            self.oversize_allocations.fetch_add(1, Ordering::Relaxed);
            return;
        }
        let idx = match class {
            PoolClass::Small => 0,
            PoolClass::Medium => 1,
            PoolClass::Large => 2,
            PoolClass::Huge => 3,
            PoolClass::Oversize => unreachable!(),
        };
        if hit {
            self.pool_hits[idx].fetch_add(1, Ordering::Relaxed);
        } else {
            self.pool_misses[idx].fetch_add(1, Ordering::Relaxed);
        }
    }
}

/// Point-in-time snapshot for metric export. Each field maps 1:1 to
/// a Prometheus counter surfaced by the adopter's observability layer.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct BufferPoolSnapshot {
    pub pool_hits: HashMap<PoolClass, u64>,
    pub pool_misses: HashMap<PoolClass, u64>,
    pub oversize_allocations_total: u64,
    pub live_bytes: u64,
    pub tenant_live_bytes: HashMap<String, u64>,
    pub tenant_soft_limit_exceeded_total: HashMap<String, u64>,
}

// ── Tenant accounting ────────────────────────────────────────────────

#[derive(Debug)]
struct TenantAccount {
    soft_limit_bytes: u64,
    live_bytes: u64,
    soft_limit_exceeded_total: u64,
}

impl TenantAccount {
    fn new(soft_limit_bytes: u64) -> Self {
        TenantAccount {
            soft_limit_bytes,
            live_bytes: 0,
            soft_limit_exceeded_total: 0,
        }
    }
}

// ── BufferPool ───────────────────────────────────────────────────────

/// Slab-allocating pool. Shared across tenants; tenant accounting
/// happens at the metrics layer only. Thread-safe via `Mutex` on the
/// per-class free lists; metrics are lock-free atomics.
pub struct BufferPool {
    /// Free lists per class. Each `Vec<u8>` in the free list has
    /// capacity equal to the class's configured capacity.
    free_lists: [Mutex<Vec<Vec<u8>>>; 4],
    metrics: PoolMetrics,
    tenants: Mutex<HashMap<Arc<str>, TenantAccount>>,
    default_tenant_soft_limit_bytes: u64,
}

impl BufferPool {
    /// Construct with the given per-tenant default soft limit (bytes).
    pub fn new(default_tenant_soft_limit_bytes: u64) -> Self {
        BufferPool {
            free_lists: [
                Mutex::new(Vec::new()),
                Mutex::new(Vec::new()),
                Mutex::new(Vec::new()),
                Mutex::new(Vec::new()),
            ],
            metrics: PoolMetrics::default(),
            tenants: Mutex::new(HashMap::new()),
            default_tenant_soft_limit_bytes,
        }
    }

    /// Configure a per-tenant override. Unknown tenants get the
    /// default limit on their first allocation.
    pub fn set_tenant_soft_limit(
        &self,
        tenant_id: impl Into<Arc<str>>,
        soft_limit_bytes: u64,
    ) {
        let arc: Arc<str> = tenant_id.into();
        let mut guard = self.tenants.lock().expect("tenant map poisoned");
        guard
            .entry(arc)
            .or_insert_with(|| TenantAccount::new(soft_limit_bytes))
            .soft_limit_bytes = soft_limit_bytes;
    }

    /// Acquire a slab of at least `requested` bytes. Returns the
    /// allocated `Vec<u8>` and the class it came from. The `Vec` is
    /// empty (len=0) but has the capacity of its class; callers
    /// `extend_from_slice` into it.
    pub fn acquire(&self, requested: usize) -> (Vec<u8>, PoolClass) {
        let class = PoolClass::for_size(requested);
        if class == PoolClass::Oversize {
            self.metrics.record_request(class, false);
            return (Vec::with_capacity(requested), class);
        }
        let idx = class_index(class);
        let mut free = self.free_lists[idx]
            .lock()
            .expect("free list poisoned");
        if let Some(mut slab) = free.pop() {
            self.metrics.record_request(class, true);
            slab.clear();
            (slab, class)
        } else {
            self.metrics.record_request(class, false);
            (Vec::with_capacity(class.capacity()), class)
        }
    }

    /// Return a previously acquired slab to the pool. Callers typically
    /// do this via the Drop impl of the wrapping buffer once all
    /// views have dropped. In 11.b we expose the API explicitly; a
    /// Drop-wired version lands in a follow-up revision.
    pub fn release(&self, mut slab: Vec<u8>, class: PoolClass) {
        if class == PoolClass::Oversize {
            // Direct allocations aren't pooled — let them drop.
            drop(slab);
            return;
        }
        let idx = class_index(class);
        slab.clear();
        let mut free = self.free_lists[idx]
            .lock()
            .expect("free list poisoned");
        // Cap the free list per class to avoid unbounded growth on
        // idle workloads. 64 slabs per class is plenty for most
        // steady-state ingest rates; excess slabs drop to the heap.
        if free.len() < 64 {
            free.push(slab);
        } else {
            drop(slab);
        }
    }

    /// Record `bytes` of live buffer allocation against a tenant.
    /// Emits the soft-limit-exceeded counter when appropriate.
    pub fn record_tenant_allocation(
        &self,
        tenant_id: impl Into<Arc<str>>,
        bytes: u64,
    ) {
        let arc: Arc<str> = tenant_id.into();
        let default_limit = self.default_tenant_soft_limit_bytes;
        let mut guard = self.tenants.lock().expect("tenant map poisoned");
        let entry = guard
            .entry(arc)
            .or_insert_with(|| TenantAccount::new(default_limit));
        entry.live_bytes = entry.live_bytes.saturating_add(bytes);
        if entry.live_bytes > entry.soft_limit_bytes {
            entry.soft_limit_exceeded_total += 1;
        }
        drop(guard);
        self.metrics
            .live_bytes
            .fetch_add(bytes, Ordering::Relaxed);
    }

    /// Symmetric to [`record_tenant_allocation`]; called when a
    /// buffer drops.
    pub fn record_tenant_release(
        &self,
        tenant_id: impl Into<Arc<str>>,
        bytes: u64,
    ) {
        let arc: Arc<str> = tenant_id.into();
        let mut guard = self.tenants.lock().expect("tenant map poisoned");
        if let Some(entry) = guard.get_mut(&arc) {
            entry.live_bytes = entry.live_bytes.saturating_sub(bytes);
        }
        drop(guard);
        self.metrics
            .live_bytes
            .fetch_sub(bytes.min(self.metrics.live_bytes.load(Ordering::Relaxed)), Ordering::Relaxed);
    }

    /// Snapshot for metric export / tests.
    pub fn snapshot(&self) -> BufferPoolSnapshot {
        let mut pool_hits = HashMap::new();
        let mut pool_misses = HashMap::new();
        for class in PoolClass::non_oversize() {
            let idx = class_index(class);
            pool_hits.insert(
                class,
                self.metrics.pool_hits[idx].load(Ordering::Relaxed),
            );
            pool_misses.insert(
                class,
                self.metrics.pool_misses[idx].load(Ordering::Relaxed),
            );
        }
        let guard = self.tenants.lock().expect("tenant map poisoned");
        let tenant_live_bytes: HashMap<String, u64> = guard
            .iter()
            .map(|(k, v)| (k.to_string(), v.live_bytes))
            .collect();
        let tenant_soft_limit_exceeded_total: HashMap<String, u64> = guard
            .iter()
            .map(|(k, v)| (k.to_string(), v.soft_limit_exceeded_total))
            .collect();
        BufferPoolSnapshot {
            pool_hits,
            pool_misses,
            oversize_allocations_total: self
                .metrics
                .oversize_allocations
                .load(Ordering::Relaxed),
            live_bytes: self.metrics.live_bytes.load(Ordering::Relaxed),
            tenant_live_bytes,
            tenant_soft_limit_exceeded_total,
        }
    }
}

impl Default for BufferPool {
    fn default() -> Self {
        // Default per-tenant soft limit: 256 MiB. Matches the
        // "reasonable single user" envelope; adopters override per
        // plan / per tenant.
        BufferPool::new(256 * 1024 * 1024)
    }
}

fn class_index(class: PoolClass) -> usize {
    match class {
        PoolClass::Small => 0,
        PoolClass::Medium => 1,
        PoolClass::Large => 2,
        PoolClass::Huge => 3,
        PoolClass::Oversize => panic!("oversize class has no free list"),
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn size_classes_map_correctly() {
        assert_eq!(PoolClass::for_size(1), PoolClass::Small);
        assert_eq!(PoolClass::for_size(4 * 1024), PoolClass::Small);
        assert_eq!(
            PoolClass::for_size(4 * 1024 + 1),
            PoolClass::Medium
        );
        assert_eq!(PoolClass::for_size(64 * 1024), PoolClass::Medium);
        assert_eq!(
            PoolClass::for_size(64 * 1024 + 1),
            PoolClass::Large
        );
        assert_eq!(PoolClass::for_size(1024 * 1024), PoolClass::Large);
        assert_eq!(
            PoolClass::for_size(1024 * 1024 + 1),
            PoolClass::Huge
        );
        assert_eq!(
            PoolClass::for_size(10 * 1024 * 1024),
            PoolClass::Huge
        );
        assert_eq!(
            PoolClass::for_size(10 * 1024 * 1024 + 1),
            PoolClass::Oversize
        );
    }

    #[test]
    fn acquire_returns_slab_with_class_capacity() {
        let pool = BufferPool::default();
        let (slab, class) = pool.acquire(8 * 1024);
        assert_eq!(class, PoolClass::Medium);
        assert_eq!(slab.len(), 0);
        assert!(slab.capacity() >= PoolClass::Medium.capacity());
    }

    #[test]
    fn release_reuses_slab() {
        let pool = BufferPool::default();
        let (mut slab, class) = pool.acquire(1000);
        slab.extend_from_slice(&[42u8; 1000]);
        pool.release(slab, class);

        let (slab2, class2) = pool.acquire(1000);
        assert_eq!(class, class2);
        // Reused slab comes out cleared.
        assert!(slab2.is_empty());
        let snap = pool.snapshot();
        assert_eq!(snap.pool_hits[&PoolClass::Small], 1);
    }

    #[test]
    fn oversize_bypasses_pool() {
        let pool = BufferPool::default();
        let huge = 50 * 1024 * 1024;
        let (slab, class) = pool.acquire(huge);
        assert_eq!(class, PoolClass::Oversize);
        assert!(slab.capacity() >= huge);
        let snap = pool.snapshot();
        assert_eq!(snap.oversize_allocations_total, 1);
    }

    #[test]
    fn tenant_soft_limit_exceeded_increments() {
        let pool = BufferPool::new(1024); // 1 KiB soft limit
        pool.record_tenant_allocation("alpha", 2048); // over
        pool.record_tenant_allocation("alpha", 512);  // still over
        let snap = pool.snapshot();
        assert_eq!(
            snap.tenant_soft_limit_exceeded_total["alpha"],
            2
        );
        assert_eq!(snap.tenant_live_bytes["alpha"], 2560);
    }

    #[test]
    fn per_tenant_override_applies() {
        let pool = BufferPool::new(1024);
        pool.set_tenant_soft_limit("premium", 10 * 1024);
        pool.record_tenant_allocation("premium", 5 * 1024);
        let snap = pool.snapshot();
        // 5 KiB under 10 KiB override → no exceed.
        assert_eq!(
            snap.tenant_soft_limit_exceeded_total["premium"],
            0
        );
    }

    #[test]
    fn free_list_caps_at_64() {
        let pool = BufferPool::default();
        for _ in 0..100 {
            let (slab, class) = pool.acquire(1000);
            pool.release(slab, class);
        }
        // No direct assertion on internal state — just checking we
        // don't blow up. Next acquire should still work.
        let (_slab, class) = pool.acquire(1000);
        assert_eq!(class, PoolClass::Small);
    }
}