Skip to content
Draft
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
2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -309,7 +309,7 @@ tokio-stream = "0.1"

# Timing and UUIDs (for JTAG protocol)
chrono = "0.4"
uuid = { version = "1.6", features = ["v4", "v5", "serde"] }
uuid = { version = "1.6", features = ["v4", "v5", "v7", "serde"] }

# Safetensors for model/adapter weights
safetensors = "0.7"
Expand Down
12 changes: 12 additions & 0 deletions core/continuum-engine/src/inference/engine_contract.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
//! The core's edge of the core<->engine contract (CONTINUUM-ENGINE 4.11; the definition is the fork's
//! `server-continuum.h`, bound in `llama::contract`). Ids are their native 16 bytes in distinct types; a frame's
//! kind and tags are validated here exactly as the engine validates them (`validate`), and the cross-language test
//! (`tests.rs`) runs both validators over the same bytes so the two edges cannot drift.

mod ids;
mod validate;
#[cfg(test)]
mod tests;

pub use ids::{ActId, EngineInstanceId, LayerId};
pub use validate::{validate, FrameError, FrameKind};
56 changes: 56 additions & 0 deletions core/continuum-engine/src/inference/engine_contract/ids.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
//! The contract's ids: UUIDs in their 16 bytes, one type per kind, compared by exact equality only
//! (CONTINUUM-ENGINE 4.11.2). UUIDv7 time order is for reading logs, never for deciding freshness.

use llama::contract::ctm_id;
use uuid::Uuid;

macro_rules! wire_id {
($(#[$doc:meta])* $name:ident) => {
$(#[$doc])*
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct $name(Uuid);

impl $name {
pub fn from_uuid(id: Uuid) -> Self {
Self(id)
}
pub fn uuid(&self) -> Uuid {
self.0
}
/// The frame field's form: the UUID's 16 bytes in RFC 9562 order.
pub fn to_wire(self) -> ctm_id {
ctm_id { bytes: *self.0.as_bytes() }
}
pub fn from_wire(id: &ctm_id) -> Self {
Self(Uuid::from_bytes(id.bytes))
}
}
};
}

wire_id!(
/// The engine process's identity, minted by the engine at start and adopted at attach.
EngineInstanceId
);
wire_id!(
/// One act (a turn): minted once per act by the core; a retry keeps it; a learn pin is its act.
ActId
);
wire_id!(
/// One LoRA layer of a mind's genome.
LayerId
);

impl ActId {
/// A new act's id (UUIDv7).
pub fn mint() -> Self {
Self(Uuid::now_v7())
}
}

impl LayerId {
/// A new layer's id (UUIDv7).
pub fn mint() -> Self {
Self(Uuid::now_v7())
}
}
95 changes: 95 additions & 0 deletions core/continuum-engine/src/inference/engine_contract/tests.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
//! what this catches: the two edges of the core<->engine contract drifting. Every case runs the Rust validator and
//! the engine's own C validator (`ctm_validate`, linked from the fork) over the SAME bytes and requires the same
//! verdict, and the schema identity both sides compiled in to be equal (CONTINUUM-ENGINE 4.11.3).

use super::*;
use llama::contract as c;

fn bytes_of<T>(frame: &T) -> &[u8] {
// test: a bound POD frame viewed as its bytes, exactly what crosses the wire
unsafe { std::slice::from_raw_parts((frame as *const T).cast::<u8>(), std::mem::size_of::<T>()) }
}

fn engine_verdict(bytes: &[u8]) -> i32 {
// test: the fork's validator over the same bytes
unsafe { c::ctm_validate(bytes.as_ptr().cast(), bytes.len()) }
}

/// Rust and C agree on `bytes`; returns the shared verdict as the engine's code.
fn agree(bytes: &[u8]) -> i32 {
let rust = validate(bytes).map_or_else(FrameError::code, |_| c::CTM_VALID as i32);
let engine = engine_verdict(bytes);
assert_eq!(rust, engine, "the Rust and engine edges disagree on the same bytes");
rust
}

fn header(kind: u32, size: usize) -> c::ctm_frame_header {
c::ctm_frame_header {
magic: c::CTM_MAGIC,
schema_version: c::CTM_SCHEMA_VERSION as u16,
kind: kind as u16,
size: size as u32,
reserved: 0,
schema: c::ctm_id { bytes: c::SCHEMA_ID },
}
}

#[test]
fn both_edges_compiled_in_the_same_schema() {
// test: reading the linked static
let engine = unsafe { c::ctm_schema_id.bytes };
assert_eq!(engine, c::SCHEMA_ID, "core and engine were built from different contract headers");
}

#[test]
fn both_edges_give_every_frame_the_same_verdict() {
let mut p = c::ctm_prefetch { header: header(c::CTM_KIND_PREFETCH, std::mem::size_of::<c::ctm_prefetch>()), ..Default::default() };
assert_eq!(agree(bytes_of(&p)), c::CTM_VALID as i32);
let one_short = std::mem::size_of::<c::ctm_frame_header>() - 1;
assert_eq!(agree(&bytes_of(&p)[..one_short]), c::CTM_INVALID_SHORT as i32);
p.header.magic ^= 1;
assert_eq!(agree(bytes_of(&p)), c::CTM_INVALID_MAGIC as i32);
p.header.magic ^= 1;
p.header.schema_version = 2;
assert_eq!(agree(bytes_of(&p)), c::CTM_INVALID_VERSION as i32);
p.header.schema_version = c::CTM_SCHEMA_VERSION as u16;
p.header.schema.bytes[0] ^= 1;
assert_eq!(agree(bytes_of(&p)), c::CTM_INVALID_SCHEMA as i32);
p.header.schema.bytes[0] ^= 1;
p.header.kind = 999;
assert_eq!(agree(bytes_of(&p)), c::CTM_INVALID_KIND as i32);
p.header.kind = c::CTM_KIND_PREFETCH as u16;
p.header.size += 8;
assert_eq!(agree(bytes_of(&p)), c::CTM_INVALID_SIZE as i32);
p.header.size -= 8;
p.header.reserved = 1;
assert_eq!(agree(bytes_of(&p)), c::CTM_INVALID_RESERVED as i32);

let mut a = c::ctm_act_submit { header: header(c::CTM_KIND_ACT_SUBMIT, std::mem::size_of::<c::ctm_act_submit>()), ..Default::default() };
a.mode = c::CTM_ACT_GENERATE as u16;
a.flags = c::CTM_ACT_LEARN_PIN;
a.act = ActId::mint().to_wire();
assert_eq!(agree(bytes_of(&a)), c::CTM_VALID as i32);
a.mode = 7;
assert_eq!(agree(bytes_of(&a)), c::CTM_INVALID_TAG as i32, "an out-of-range enum is refused, never cast");
a.mode = c::CTM_ACT_LEARN as u16;
a.flags = 1 << 9;
assert_eq!(agree(bytes_of(&a)), c::CTM_INVALID_TAG as i32, "an unknown flag bit");
a.flags = 0;
a.prompt.offset = u64::MAX;
a.prompt.length = 2;
assert_eq!(agree(bytes_of(&a)), c::CTM_INVALID_BUFFER_BOUNDS as i32, "offset + length overflows");

let mut l = c::ctm_learn_duty { header: header(c::CTM_KIND_LEARN_DUTY, std::mem::size_of::<c::ctm_learn_duty>()), ..Default::default() };
l.mode = c::CTM_LEARN_DREAM as u16;
l.share_ppm = 1_000_001;
assert_eq!(agree(bytes_of(&l)), c::CTM_INVALID_TAG as i32, "a share past the whole");
}

#[test]
fn an_id_crosses_as_its_own_sixteen_bytes() {
let act = ActId::mint();
assert_eq!(act.to_wire().bytes, *act.uuid().as_bytes());
assert_eq!(ActId::from_wire(&act.to_wire()), act);
assert_eq!(act.uuid().get_version_num(), 7);
}
203 changes: 203 additions & 0 deletions core/continuum-engine/src/inference/engine_contract/validate.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,203 @@
//! The Rust edge's validation of a frame, the same rules as the engine's `ctm_validate` (server-continuum.cpp):
//! magic, schema version, schema identity, a known kind, the kind's exact size, zero reserved bytes, every tag in
//! range and every buffer's `offset + length` without overflow. Fields are read at the bound structs' own offsets
//! (`offset_of!`), little-endian, from bytes that need not be aligned; nothing is cast into an enum.

use llama::contract as c;
use std::mem::{offset_of, size_of};

/// Why a frame was refused; each the engine's `ctm_validation` value of the same name.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FrameError {
Short,
Magic,
Version,
Schema,
Kind,
Size,
Reserved,
Tag,
BufferBounds,
}

impl FrameError {
/// The engine's code for the same refusal (the cross-language test compares them).
pub fn code(self) -> i32 {
(match self {
Self::Short => c::CTM_INVALID_SHORT,
Self::Magic => c::CTM_INVALID_MAGIC,
Self::Version => c::CTM_INVALID_VERSION,
Self::Schema => c::CTM_INVALID_SCHEMA,
Self::Kind => c::CTM_INVALID_KIND,
Self::Size => c::CTM_INVALID_SIZE,
Self::Reserved => c::CTM_INVALID_RESERVED,
Self::Tag => c::CTM_INVALID_TAG,
Self::BufferBounds => c::CTM_INVALID_BUFFER_BOUNDS,
}) as i32
}
}

/// A frame's kind, converted from its raw tag; an unknown tag is `FrameError::Kind`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FrameKind {
Attach,
EngineDescriptor,
ActSubmit,
ActDone,
Cancel,
Prefetch,
Placed,
PinRelease,
Released,
GenomeSet,
LearnDuty,
Refused,
}

impl FrameKind {
fn from_tag(tag: u16) -> Option<Self> {
Some(match u32::from(tag) {
c::CTM_KIND_ATTACH => Self::Attach,
c::CTM_KIND_ENGINE_DESCRIPTOR => Self::EngineDescriptor,
c::CTM_KIND_ACT_SUBMIT => Self::ActSubmit,
c::CTM_KIND_ACT_DONE => Self::ActDone,
c::CTM_KIND_CANCEL => Self::Cancel,
c::CTM_KIND_PREFETCH => Self::Prefetch,
c::CTM_KIND_PLACED => Self::Placed,
c::CTM_KIND_PIN_RELEASE => Self::PinRelease,
c::CTM_KIND_RELEASED => Self::Released,
c::CTM_KIND_GENOME_SET => Self::GenomeSet,
c::CTM_KIND_LEARN_DUTY => Self::LearnDuty,
c::CTM_KIND_REFUSED => Self::Refused,
_ => return None,
})
}

/// The kind's fixed size, the same as the engine's `ctm_frame_size`.
pub fn size(self) -> usize {
match self {
Self::Attach => size_of::<c::ctm_attach>(),
Self::EngineDescriptor => size_of::<c::ctm_engine_descriptor>(),
Self::ActSubmit => size_of::<c::ctm_act_submit>(),
Self::ActDone => size_of::<c::ctm_act_done>(),
Self::Cancel => size_of::<c::ctm_cancel>(),
Self::Prefetch => size_of::<c::ctm_prefetch>(),
Self::Placed => size_of::<c::ctm_placed>(),
Self::PinRelease => size_of::<c::ctm_pin_release>(),
Self::Released => size_of::<c::ctm_released>(),
Self::GenomeSet => size_of::<c::ctm_genome_set>(),
Self::LearnDuty => size_of::<c::ctm_learn_duty>(),
Self::Refused => size_of::<c::ctm_refused>(),
}
}
}

struct Frame<'a>(&'a [u8]);

impl Frame<'_> {
fn u16(&self, at: usize) -> u16 {
u16::from_le_bytes([self.0[at], self.0[at + 1]])
}
fn u32(&self, at: usize) -> u32 {
let mut b = [0u8; 4];
b.copy_from_slice(&self.0[at..at + 4]);
u32::from_le_bytes(b)
}
fn u64(&self, at: usize) -> u64 {
let mut b = [0u8; 8];
b.copy_from_slice(&self.0[at..at + 8]);
u64::from_le_bytes(b)
}
/// `offset + length` of the buffer_ref at `at` does not overflow.
fn buffer_ok(&self, at: usize) -> bool {
let offset = self.u64(at + offset_of!(c::ctm_buffer_ref, offset));
let length = self.u64(at + offset_of!(c::ctm_buffer_ref, length));
offset.checked_add(length).is_some()
}
}

fn in_range(v: u32, valid: std::ops::Range<u32>) -> bool {
valid.contains(&v)
}

/// Validate `bytes` as one frame of this build's schema; its kind when valid.
pub fn validate(bytes: &[u8]) -> Result<FrameKind, FrameError> {
if bytes.len() < size_of::<c::ctm_frame_header>() {
return Err(FrameError::Short);
}
let f = Frame(bytes);
if f.u32(offset_of!(c::ctm_frame_header, magic)) != c::CTM_MAGIC {
return Err(FrameError::Magic);
}
if u32::from(f.u16(offset_of!(c::ctm_frame_header, schema_version))) != c::CTM_SCHEMA_VERSION {
return Err(FrameError::Version);
}
let schema_at = offset_of!(c::ctm_frame_header, schema);
if bytes[schema_at..schema_at + 16] != c::SCHEMA_ID {
return Err(FrameError::Schema);
}
let kind = FrameKind::from_tag(f.u16(offset_of!(c::ctm_frame_header, kind))).ok_or(FrameError::Kind)?;
if usize::try_from(f.u32(offset_of!(c::ctm_frame_header, size))).ok() != Some(kind.size()) {
return Err(FrameError::Size);
}
if bytes.len() < kind.size() {
return Err(FrameError::Short);
}
if f.u32(offset_of!(c::ctm_frame_header, reserved)) != 0 {
return Err(FrameError::Reserved);
}
check_tags(kind, &f).map(|()| kind)
}

fn check_tags(kind: FrameKind, f: &Frame<'_>) -> Result<(), FrameError> {
let tag = |ok: bool| if ok { Ok(()) } else { Err(FrameError::Tag) };
let zero = |ok: bool| if ok { Ok(()) } else { Err(FrameError::Reserved) };
let bounds = |ok: bool| if ok { Ok(()) } else { Err(FrameError::BufferBounds) };
match kind {
FrameKind::EngineDescriptor => {
zero(f.u16(offset_of!(c::ctm_engine_descriptor, reserved0)) == 0)?;
bounds(f.buffer_ok(offset_of!(c::ctm_engine_descriptor, resources)))
}
FrameKind::ActSubmit => {
zero(f.u16(offset_of!(c::ctm_act_submit, reserved0)) == 0)?;
tag(in_range(u32::from(f.u16(offset_of!(c::ctm_act_submit, mode))), 1..c::CTM_ACT_MODE_COUNT))?;
tag(f.u32(offset_of!(c::ctm_act_submit, flags)) & !c::CTM_ACT_FLAGS_ALL == 0)?;
for at in [
offset_of!(c::ctm_act_submit, prompt),
offset_of!(c::ctm_act_submit, labels),
offset_of!(c::ctm_act_submit, view),
offset_of!(c::ctm_act_submit, sampling),
] {
bounds(f.buffer_ok(at))?;
}
Ok(())
}
FrameKind::ActDone => {
tag(in_range(u32::from(f.u16(offset_of!(c::ctm_act_done, outcome))), 1..c::CTM_OUTCOME_COUNT))?;
tag(in_range(u32::from(f.u16(offset_of!(c::ctm_act_done, reason))), 0..c::CTM_REASON_COUNT))?;
tag(in_range(u32::from(f.u16(offset_of!(c::ctm_act_done, mind_from))), 0..c::CTM_MIND_FROM_COUNT))?;
tag(u32::from(f.u16(offset_of!(c::ctm_act_done, flags))) & !c::CTM_DONE_FLAGS_ALL == 0)?;
bounds(f.buffer_ok(offset_of!(c::ctm_act_done, observations)))
}
FrameKind::Placed => {
zero(f.u16(offset_of!(c::ctm_placed, reserved0)) == 0 && f.u32(offset_of!(c::ctm_placed, reserved1)) == 0)?;
tag(in_range(u32::from(f.u16(offset_of!(c::ctm_placed, place))), 1..c::CTM_PLACE_COUNT))
}
FrameKind::Released => {
zero(f.u16(offset_of!(c::ctm_released, reserved0)) == 0 && f.u32(offset_of!(c::ctm_released, reserved1)) == 0)?;
tag(in_range(u32::from(f.u16(offset_of!(c::ctm_released, outcome))), 1..c::CTM_PIN_COUNT))
}
FrameKind::GenomeSet => bounds(f.buffer_ok(offset_of!(c::ctm_genome_set, layers))),
FrameKind::LearnDuty => {
zero(f.u16(offset_of!(c::ctm_learn_duty, reserved0)) == 0)?;
tag(in_range(u32::from(f.u16(offset_of!(c::ctm_learn_duty, mode))), 1..c::CTM_LEARN_MODE_COUNT))?;
tag(f.u32(offset_of!(c::ctm_learn_duty, share_ppm)) <= 1_000_000)
}
FrameKind::Refused => {
zero(f.u32(offset_of!(c::ctm_refused, reserved0)) == 0)?;
tag(in_range(u32::from(f.u16(offset_of!(c::ctm_refused, refused_kind))), 0..c::CTM_KIND_KIND_COUNT))?;
tag(in_range(u32::from(f.u16(offset_of!(c::ctm_refused, reason))), 0..c::CTM_REASON_COUNT))
}
FrameKind::Attach | FrameKind::Cancel | FrameKind::Prefetch | FrameKind::PinRelease => Ok(()),
}
}
1 change: 1 addition & 0 deletions core/continuum-engine/src/inference/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ pub mod backends;
pub mod batching_probe;
pub mod child_log;
pub mod embed_lane_memory;
pub mod engine_contract;
pub mod engine_client;
pub use engine_client::engine_client;
pub mod engine_stall;
Expand Down
Loading
Loading