Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,8 @@ changes:
the native `cause` chain; retry delays are read from `responseHeaders`, not
`retryMs`.
- **DTOs are generated.** Hand-written 0.5 wire types are removed; ABI 1 /
ops 1.0 and the manifest digest must match the native library.
ops 1.0 and manifest compatibility (`MANIFEST_DIGEST` fast-path or full
`TYPE_SCHEMA_HASHES` `schemaHash` fallback) are checked against the native library.
- **Recording stays on schema 2.** Schema 3 and transport replay are a
follow-up.

Expand Down
54 changes: 44 additions & 10 deletions aimux-core/src/trace/store.rs
Original file line number Diff line number Diff line change
Expand Up @@ -90,17 +90,36 @@ pub(crate) struct TraceStore {
}

impl TraceStore {
#[cfg(test)]
pub fn new(cap: usize, per_scope_cap: usize) -> Self {
assert!(cap > 0);
TraceStore {
Self::try_new(cap, per_scope_cap).expect("trace store capacity allocation")
}

pub fn try_new(cap: usize, per_scope_cap: usize) -> Result<Self, &'static str> {
if cap == 0 {
return Err("trace store capacity must be greater than zero");
}
let mut ring = Vec::new();
ring.try_reserve_exact(cap)
.map_err(|_| "trace store capacity exceeds available memory")?;
ring.resize_with(cap, RingSlot::default);
Ok(TraceStore {
cap,
per_scope_cap,
ring: (0..cap).map(|_| RingSlot::default()).collect(),
ring,
next: 0,
index: HashMap::new(),
scope_count: HashMap::new(),
tombstone_hits: 0,
}
})
}

pub fn clear(&mut self) {
self.ring.fill_with(RingSlot::default);
self.next = 0;
self.index.clear();
self.scope_count.clear();
self.tombstone_hits = 0;
}

pub fn records_in_scope(&self, scope: u64) -> u64 {
Expand Down Expand Up @@ -421,15 +440,30 @@ impl RingTraceStore {

#[must_use]
pub fn with_capacity(cap: usize, per_scope_cap: usize) -> Self {
assert!(cap > 0 && per_scope_cap > 0);
Self {
Self::try_with_capacity(cap, per_scope_cap).expect("ring trace store capacity allocation")
}

/// Create a bounded ring trace store without aborting on allocation failure.
///
/// # Errors
/// Returns an error if either capacity is zero or memory allocation fails.
pub fn try_with_capacity(cap: usize, per_scope_cap: usize) -> Result<Self, &'static str> {
if cap == 0 || per_scope_cap == 0 {
return Err("trace store capacities must be greater than zero");
}
let store = TraceStore::try_new(cap, per_scope_cap)?;
let mut records = VecDeque::new();
records
.try_reserve_exact(cap)
.map_err(|_| "trace store capacity exceeds available memory")?;
Ok(Self {
audit_mode: TraceAuditMode::Off,
inner: Mutex::new(Inner {
store: TraceStore::new(cap, per_scope_cap),
records: VecDeque::with_capacity(cap),
store,
records,
by_session: HashMap::new(),
}),
}
})
}

/// Audit policy inherited by trace decorators created for this store.
Expand All @@ -446,7 +480,7 @@ impl RingTraceStore {

pub fn clear(&self) {
let mut inner = self.inner.lock().unwrap();
inner.store = TraceStore::new(inner.store.cap, inner.store.per_scope_cap);
inner.store.clear();
inner.records.clear();
inner.by_session.clear();
}
Expand Down
4 changes: 2 additions & 2 deletions aimux-ffi/include/aimux.h
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
/* Generated by aimux-codegen. Do not edit. Manifest SHA-256: 9c7f306459ec0009f6bca66c0abbb36fc3740b5fc6330c47a6fd73a6bc16caae */
/* Generated by aimux-codegen. Do not edit. Manifest SHA-256: cd147fa9595ede3951744fa261da98cc18c204e65b4081073ad3a3c1b68bfd92 */
#ifndef AIMUX_H
#define AIMUX_H

Expand All @@ -11,7 +11,7 @@ extern "C" {

#define AIMUX_ABI_VERSION UINT32_C(65536)
#define AIMUX_OPS_VERSION "1.0"
#define AIMUX_MANIFEST_DIGEST "9c7f306459ec0009f6bca66c0abbb36fc3740b5fc6330c47a6fd73a6bc16caae"
#define AIMUX_MANIFEST_DIGEST "cd147fa9595ede3951744fa261da98cc18c204e65b4081073ad3a3c1b68bfd92"

#define AIMUX_OP_ABORT_CREATE "abort.create"
#define AIMUX_OP_ABORT_SIGNAL "abort.signal"
Expand Down
16 changes: 10 additions & 6 deletions aimux-ops/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -83,12 +83,16 @@ finalizers enqueue cleanup.
`manifest::manifest()` exports all 76 operations, including two Decision
operations and four provider/registry management operations
(`provider.descriptors`, `registry.fromConfig`, `registry.list`,
`registry.update`) beyond RFC-0039's original 70, 23 handle kinds, error codes
and a `types` catalogue. Ops controls and result wrappers carry schemas; canonical
business fields retain explicit type references. Codegen publishes the C header,
language constants and schemas. Its `--check` detects missing, stale and changed
outputs. The manifest's `digest` field equals `manifest_digest()`; hashing sorts
object keys and operation names and excludes the `digest` field itself.
`registry.update`) beyond RFC-0039's original 70, 23 handle kinds, error codes,
`generatorVersion`, `sources` (pinned upstream SDK versions/integrity), and a
`types` catalogue carrying per-type `revision` and transitive `schemaHash`.
Codegen publishes the C header, `schema/manifest.json` (which records `inputHash`
alongside `digest`), per-language `TYPE_SCHEMA_HASHES` constants, and JSON
schemas. Its `--check` detects missing, stale and changed outputs. The
manifest's `digest` field equals `manifest_digest()`; self-verifying either the
runtime manifest or `schema/manifest.json` removes both `digest` and `inputHash`
from the top-level object, sorts `ops` by `name`, recursively sorts all object
keys, and hashes the compact JSON with SHA-256.

Registered differences from RFC-0039 include the Decision kind and operations,
BinaryPush-only JSON rejection for operation.push, and the native finalizer
Expand Down
12 changes: 11 additions & 1 deletion aimux-ops/src/dto_vectors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -143,6 +143,9 @@ fn dto_vectors_round_trip_through_rust() {
}
"ModelPrompt" => round_trip::<aimux_core::message::ModelPrompt>(value.clone()),
"NamespacedKind" => round_trip::<aimux_core::types::NamespacedKind>(value.clone()),
"OperationNextParams" => {
round_trip::<crate::ops::operation::OperationNextParams>(value.clone())
}
"Output" => round_trip::<aimux_core::output::Output>(value.clone()),
"OutputTokenDetails" => {
round_trip::<aimux_core::types::OutputTokenDetails>(value.clone())
Expand Down Expand Up @@ -241,8 +244,15 @@ fn dto_vectors_round_trip_through_rust() {
"VideoResult" => round_trip::<aimux_core::video_model::VideoResult>(value.clone()),
"Warning" => round_trip::<aimux_core::types::Warning>(value.clone()),
name => panic!("unregistered vector type {name}: {file}"),
};
if entry["expectError"].as_bool().unwrap_or(false) {
assert!(
result.is_err(),
"{file}: expected error on negative vector, got {result:?}"
);
continue;
}
.unwrap_or_else(|error| panic!("{file}: {error}"));
let result = result.unwrap_or_else(|error| panic!("{file}: {error}"));
let expected = entry["expect"].as_str().map_or(value, |file| {
assert!(
std::path::Path::new(file)
Expand Down
70 changes: 66 additions & 4 deletions aimux-ops/src/handle.rs
Original file line number Diff line number Diff line change
Expand Up @@ -241,17 +241,34 @@ impl HandleRegistry {
REGISTRY.get_or_init(Self::default)
}

/// Insert a resource, failing permanently rather than wrapping the allocator.
/// Reserve a live handle ID before performing pre-registration setup.
///
/// Dropping the returned reservation without committing discards the unused ID
/// without leaking an entry or reusing IDs.
///
/// # Errors
/// Returns HandleExhausted on overflow.
pub fn insert(&self, owner: Owner, entry: Entry) -> Result<HandleId, OpsError> {
pub fn reserve(&self) -> Result<HandleReservation, OpsError> {
let id = allocate(&NEXT_ID)?;
Ok(HandleReservation { id })
}

/// Commit a reserved handle ID into the registry.
pub fn commit(&self, owner: Owner, reservation: HandleReservation, entry: Entry) -> HandleId {
self.entries
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.insert(id, (owner, entry));
Ok(HandleId(id))
.insert(reservation.id, (owner, entry));
HandleId(reservation.id)
}

/// Insert a resource, failing permanently rather than wrapping the allocator.
///
/// # Errors
/// Returns HandleExhausted on overflow.
pub fn insert(&self, owner: Owner, entry: Entry) -> Result<HandleId, OpsError> {
let reservation = self.reserve()?;
Ok(self.commit(owner, reservation, entry))
}

/// Clone a live resource after checking its owner and kind.
Expand Down Expand Up @@ -317,6 +334,51 @@ pub fn allocate(next: &AtomicU64) -> Result<u64, OpsError> {
}
}

/// Pre-allocated handle ID waiting to be committed into [`HandleRegistry`].
pub struct HandleReservation {
id: u64,
}

struct ExhaustionState {
active_guards: usize,
saved_next_id: u64,
}

static EXHAUSTION_STATE: Mutex<ExhaustionState> = Mutex::new(ExhaustionState {
active_guards: 0,
saved_next_id: 0,
});

#[doc(hidden)]
pub struct ExhaustionGuard {
_private: (),
}

impl Drop for ExhaustionGuard {
fn drop(&mut self) {
let mut state = EXHAUSTION_STATE
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
state.active_guards = state.active_guards.saturating_sub(1);
if state.active_guards == 0 {
NEXT_ID.store(state.saved_next_id, Ordering::SeqCst);
}
}
}

#[doc(hidden)]
#[must_use]
pub fn test_exhaust_process_handle_allocator() -> ExhaustionGuard {
let mut state = EXHAUSTION_STATE
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
if state.active_guards == 0 {
state.saved_next_id = NEXT_ID.swap(0, Ordering::SeqCst);
}
state.active_guards += 1;
ExhaustionGuard { _private: () }
}

#[cfg(test)]
mod tests {
use super::*;
Expand Down
1 change: 1 addition & 0 deletions aimux-ops/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ pub mod manifest;
pub mod op;
pub mod operation;
mod request;
mod sources;

pub mod ops {
pub mod composite;
Expand Down
2 changes: 1 addition & 1 deletion aimux-ops/src/manifest.digest
Original file line number Diff line number Diff line change
@@ -1 +1 @@
9c7f306459ec0009f6bca66c0abbb36fc3740b5fc6330c47a6fd73a6bc16caae
cd147fa9595ede3951744fa261da98cc18c204e65b4081073ad3a3c1b68bfd92
Binary file modified aimux-ops/src/manifest.json.zlib
Binary file not shown.
Loading
Loading