Stream Muninn Move evidence over CultMesh

This commit is contained in:
Meta Vens 2026-06-12 10:45:47 +01:00
commit 8e6322c7a1
7 changed files with 792 additions and 5 deletions

2
Cargo.lock generated
View file

@ -502,6 +502,8 @@ dependencies = [
"cultmesh-rs",
"libc",
"odin-core",
"rmp-serde",
"serde",
]
[[package]]

View file

@ -14,3 +14,5 @@ anyhow = "1"
cultmesh-rs = { path = "../../vendor/cultmesh-rs" }
libc = "0.2"
odin-core = { path = "../odin-core" }
rmp-serde = "1.3"
serde = { version = "1", features = ["derive"] }

View file

@ -1,9 +1,13 @@
use anyhow::{Context, Result, anyhow};
use cultmesh_rs::{CultMesh, CultMeshNodeOptions};
use cultmesh_rs::{
CultMesh, CultMeshNodeOptions, CultMeshSharedMemoryFrameRing, CultMeshStreamBodyTransport,
CultMeshStreamCatalog, CultMeshStreamClock, CultMeshStreamDescriptor, CultMeshStreamKind,
};
use odin_core::{
MuninnCaptureStreamRecord, MuninnMoveControllerStateRecord, MuninnMoveLightCommandRecord,
MuninnObsStreamCatalogRecord, MuninnTelemetrySurfaceRecord, OdinDocuments,
};
use serde::Serialize;
use std::env;
use std::fs;
use std::io::Write;
@ -57,6 +61,10 @@ struct Options {
move_repeat_count: u32,
command_id: Option<String>,
move_state_sources: Vec<MoveStateSource>,
move_evidence_stream_id: Option<String>,
move_evidence_verse_id: String,
move_evidence_ring_slots: usize,
move_evidence_slot_bytes: usize,
}
#[derive(Clone, Debug, PartialEq, Eq)]
@ -87,6 +95,18 @@ struct ActiveMoveStateSource {
joystick_buttons: [bool; 32],
}
#[derive(Serialize)]
struct MuninnMoveEvidenceStreamFrame<'a>(
&'a str,
&'a str,
i64,
&'a [MuninnMoveMarkerCandidateWire],
&'a [MuninnMoveControllerStateRecord],
);
#[derive(Serialize)]
struct MuninnMoveMarkerCandidateWire;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct JoystickEvent {
event_type: u8,
@ -133,6 +153,7 @@ fn main() -> Result<()> {
fn serve(options: Options) -> Result<()> {
ensure_state_dirs(&options)?;
let mut move_evidence_stream = create_move_evidence_stream(&options)?;
let mut active_move_lights = Vec::new();
let mut active_move_states: Vec<ActiveMoveStateSource> = options
.move_state_sources
@ -155,6 +176,7 @@ fn serve(options: Options) -> Result<()> {
&options,
&mut active_move_states,
&mut HidMoveControllerStateReader,
move_evidence_stream.as_mut(),
)?;
publish_surface(&mut node, &options, "idle", &[])?;
if options.interval_seconds.is_none()
@ -172,6 +194,13 @@ fn serve(options: Options) -> Result<()> {
}
}
struct ActiveMoveEvidenceStream {
catalog: CultMeshStreamCatalog,
stream_id: String,
producer_peer_id: String,
frame_counter: u64,
}
fn activate(options: Options, spawner: impl ProcessSpawner) -> Result<()> {
ensure_state_dirs(&options)?;
let mut node = open_node(&options, "muninn-activation")?;
@ -370,6 +399,88 @@ fn publish_obs_catalog(
Ok(())
}
fn create_move_evidence_stream(options: &Options) -> Result<Option<ActiveMoveEvidenceStream>> {
if options.move_state_sources.is_empty() {
return Ok(None);
}
let stream_id = options
.move_evidence_stream_id
.clone()
.unwrap_or_else(|| format!("muninn:{}:move-evidence", options.host_id));
let producer_peer_id = format!("muninn:{}", options.host_id);
let clock_domain_id = format!("{}:clock", producer_peer_id);
let descriptor = CultMeshStreamDescriptor::new(
stream_id.clone(),
options.move_evidence_verse_id.clone(),
producer_peer_id.clone(),
CultMeshStreamKind::Bytes,
CultMeshStreamClock::new(clock_domain_id)?
.source_id(stream_id.clone())?
.confidence(1.0)
.evidence_kind("muninn-move-evidence")?,
vec![
CultMeshStreamBodyTransport::SharedMemory,
CultMeshStreamBodyTransport::CultCachePage,
],
)?
.label("Muninn Move evidence")?
.max_in_flight_frames(options.move_evidence_ring_slots as u32)
.metadata_schema_id("mimir.muninn_move_evidence_stream_frame.v1")?;
let mut catalog = CultMesh::create_stream_catalog();
catalog.declare(descriptor);
catalog.create_shared_memory_ring(
&stream_id,
options.move_evidence_ring_slots,
options.move_evidence_slot_bytes,
)?;
Ok(Some(ActiveMoveEvidenceStream {
catalog,
stream_id,
producer_peer_id,
frame_counter: 0,
}))
}
fn publish_move_evidence_stream_frame(
stream: &mut ActiveMoveEvidenceStream,
controller_states: &[MuninnMoveControllerStateRecord],
) -> Result<Option<cultmesh_rs::CultMeshStreamFrameHandle>> {
if controller_states.is_empty() {
return Ok(None);
}
let published_at_ns = timestamp_ns()?;
let frame_id = format!("{}:{}", stream.stream_id, stream.frame_counter);
stream.frame_counter = stream.frame_counter.saturating_add(1);
let marker_candidates: &[MuninnMoveMarkerCandidateWire] = &[];
let frame = MuninnMoveEvidenceStreamFrame(
&frame_id,
&stream.producer_peer_id,
published_at_ns,
marker_candidates,
controller_states,
);
let payload =
rmp_serde::to_vec(&frame).context("encoding Muninn Move evidence stream frame")?;
let handle = {
let ring: &mut CultMeshSharedMemoryFrameRing =
stream
.catalog
.ring_mut(&stream.stream_id)
.ok_or_else(|| anyhow!("missing Muninn Move evidence ring"))?;
ring.try_publish_copy(&payload, published_at_ns, 0)?
};
if let Some(handle) = handle {
stream.catalog.publish_frame(handle.clone())?;
Ok(Some(handle))
} else {
Ok(None)
}
}
trait MoveLightWriter {
fn write_report(&mut self, hidraw_path: &str, report: &[u8]) -> Result<()>;
}
@ -470,7 +581,9 @@ fn publish_move_controller_states(
options: &Options,
active: &mut [ActiveMoveStateSource],
reader: &mut impl MoveControllerStateReader,
move_evidence_stream: Option<&mut ActiveMoveEvidenceStream>,
) -> Result<()> {
let mut published_records = Vec::new();
for state in active {
let record = if is_joystick_path(&state.source.hidraw_path) {
let events = reader.read_joystick_events(&state.source.hidraw_path)?;
@ -522,6 +635,10 @@ fn publish_move_controller_states(
&format!("{}:{}", record.stream_id, record.sequence),
&record,
)?;
published_records.push(record);
}
if let Some(stream) = move_evidence_stream {
publish_move_evidence_stream_frame(stream, &published_records)?;
}
Ok(())
}
@ -1169,6 +1286,10 @@ impl Options {
move_repeat_count: 1,
command_id: None,
move_state_sources: Vec::new(),
move_evidence_stream_id: None,
move_evidence_verse_id: "mimir-live".to_string(),
move_evidence_ring_slots: 4,
move_evidence_slot_bytes: 8192,
};
let mut args = args.peekable();
@ -1232,6 +1353,25 @@ impl Options {
.move_state_sources
.push(parse_move_state_source(&value)?);
}
"--move-evidence-stream" => {
options.move_evidence_stream_id =
Some(take_value(&mut args, "--move-evidence-stream")?)
}
"--move-evidence-verse" => {
options.move_evidence_verse_id = take_value(&mut args, "--move-evidence-verse")?
}
"--move-evidence-ring-slots" => {
options.move_evidence_ring_slots =
take_value(&mut args, "--move-evidence-ring-slots")?
.parse()
.context("--move-evidence-ring-slots must be a positive integer")?
}
"--move-evidence-slot-bytes" => {
options.move_evidence_slot_bytes =
take_value(&mut args, "--move-evidence-slot-bytes")?
.parse()
.context("--move-evidence-slot-bytes must be a positive integer")?
}
"--color" => options.move_colors.push(take_value(&mut args, "--color")?),
"--duration-ms" => options
.move_durations_ms
@ -1255,6 +1395,26 @@ impl Options {
if options.interval_seconds == Some(0) {
return Err(anyhow!("--interval-seconds must be greater than zero"));
}
if options.move_evidence_verse_id.trim().is_empty() {
return Err(anyhow!("--move-evidence-verse must be non-empty"));
}
if options
.move_evidence_stream_id
.as_ref()
.is_some_and(|value| value.trim().is_empty())
{
return Err(anyhow!("--move-evidence-stream must be non-empty"));
}
if options.move_evidence_ring_slots == 0 {
return Err(anyhow!(
"--move-evidence-ring-slots must be greater than zero"
));
}
if options.move_evidence_slot_bytes == 0 {
return Err(anyhow!(
"--move-evidence-slot-bytes must be greater than zero"
));
}
Ok(options)
}
}
@ -1281,7 +1441,7 @@ fn timestamp_ns() -> Result<i64> {
}
fn help_text() -> &'static str {
"Usage: muninn [serve|activate|request-move-light|move-light-status|move-state-status] [--store <path>] [--target-host <host>] [--port <port>] [--obs-target-host <host>] [--obs-port <port>] [--loopback-script <path>] [--ffmpeg <path>] [--move-state <move-id>=<hidraw-path>] [--dry-run] [--health]\n\nMuninn is Odin's portable telemetry Verse assembler. serve publishes cheap typed telemetry affordances and optional source-local Move controller state; activate starts an explicitly requested local stream; request-move-light publishes a typed Move light command for Muninn serve to execute; move-light-status reads typed command receipts; move-state-status reads typed controller-state records."
"Usage: muninn [serve|activate|request-move-light|move-light-status|move-state-status] [--store <path>] [--target-host <host>] [--port <port>] [--obs-target-host <host>] [--obs-port <port>] [--loopback-script <path>] [--ffmpeg <path>] [--move-state <move-id>=<hidraw-path>] [--move-evidence-stream <stream-id>] [--move-evidence-verse <verse-id>] [--dry-run] [--health]\n\nMuninn is Odin's portable telemetry Verse assembler. serve publishes cheap typed telemetry affordances, optional source-local Move controller state, and a CultMesh Move evidence stream when Move state sources are attached; activate starts an explicitly requested local stream; request-move-light publishes a typed Move light command for Muninn serve to execute; move-light-status reads typed command receipts; move-state-status reads typed controller-state records."
}
fn parse_move_state_source(value: &str) -> Result<MoveStateSource> {
@ -1304,6 +1464,7 @@ fn parse_move_state_source(value: &str) -> Result<MoveStateSource> {
#[cfg(test)]
mod tests {
use super::*;
use serde::Deserialize;
#[derive(Default)]
struct RecordingMoveLightWriter {
@ -1521,6 +1682,8 @@ mod tests {
"nightwing",
"--move-state",
"move-usb=/dev/hidraw1",
"--move-evidence-stream",
"muninn:nightwing:move-evidence",
]
.into_iter()
.map(String::from),
@ -1534,6 +1697,102 @@ mod tests {
hidraw_path: "/dev/hidraw1".to_string(),
}]
);
assert_eq!(
options.move_evidence_stream_id.as_deref(),
Some("muninn:nightwing:move-evidence")
);
assert_eq!(options.move_evidence_verse_id, "mimir-live");
}
#[derive(Deserialize)]
struct DecodedMoveEvidenceStreamFrame(
String,
String,
i64,
Vec<DecodedMarkerCandidate>,
Vec<MuninnMoveControllerStateRecord>,
);
#[derive(Deserialize)]
struct DecodedMarkerCandidate;
#[test]
fn move_controller_state_publishes_mimir_compatible_cultmesh_frame() {
let options = Options::parse(
[
"serve",
"--host",
"nightwing",
"--move-state",
"move-usb=/dev/input/js0",
]
.into_iter()
.map(String::from),
)
.unwrap();
let source = options.move_state_sources[0].clone();
let record = build_move_controller_state_record_from_joystick(
&options,
&source,
7,
[1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0],
{
let mut buttons = [false; 32];
buttons[16] = true;
buttons[17] = true;
buttons
},
123_456_789,
"unix-1".to_string(),
);
let mut stream = create_move_evidence_stream(&options)
.unwrap()
.expect("move state source should create a stream");
let handle = publish_move_evidence_stream_frame(&mut stream, &[record.clone()])
.unwrap()
.expect("controller state should publish a frame");
assert_eq!(handle.stream_id, "muninn:nightwing:move-evidence");
assert_eq!(
stream
.catalog
.latest_frame("muninn:nightwing:move-evidence")
.unwrap()
.sequence,
0
);
assert_eq!(
stream
.catalog
.get("muninn:nightwing:move-evidence")
.unwrap()
.metadata_schema_id
.as_deref(),
Some("mimir.muninn_move_evidence_stream_frame.v1")
);
let lease = stream
.catalog
.ring("muninn:nightwing:move-evidence")
.and_then(CultMeshSharedMemoryFrameRing::try_acquire_latest_read)
.expect("latest frame should be readable");
let decoded: DecodedMoveEvidenceStreamFrame = rmp_serde::from_slice(lease.bytes()).unwrap();
assert_eq!(decoded.0, "muninn:nightwing:move-evidence:0");
assert_eq!(decoded.1, "muninn:nightwing");
assert!(decoded.2 > 0);
assert!(decoded.3.is_empty());
assert_eq!(decoded.4.len(), 1);
assert_eq!(decoded.4[0].stream_id, record.stream_id);
assert_eq!(decoded.4[0].host_id, record.host_id);
assert_eq!(decoded.4[0].move_id, record.move_id);
assert_eq!(decoded.4[0].sequence, record.sequence);
assert_eq!(decoded.4[0].source_timestamp_ns, record.source_timestamp_ns);
assert_eq!(decoded.4[0].accelerometer_xyz, record.accelerometer_xyz);
assert_eq!(decoded.4[0].gyroscope_xyz, record.gyroscope_xyz);
assert_eq!(decoded.4[0].magnetometer_xyz, record.magnetometer_xyz);
assert_eq!(decoded.4[0].buttons, record.buttons);
assert!(decoded.4[0].battery01.is_nan());
}
#[test]

View file

@ -116,7 +116,11 @@ startup to burn capture resources.
Move optical marker extraction belongs to Muninn because it is sensor stream
exposure, not Mimir fusion or Odin registry truth. The native helper lives at
`crates/muninn-move-tracker`; Muninn may publish per-frame candidates as
`muninn.move_marker_candidate.v1`. Mimir consumes those candidate streams into
`muninn.move_marker_candidate.v1`. USB Move controller facts are
`muninn.move_controller_state.v1` receipts. Those records are not the hot
tracking transport: Muninn bundles marker candidates and controller states into
a CultMesh bytes stream frame with metadata schema
`mimir.muninn_move_evidence_stream_frame.v1`. Mimir consumes that stream into
tracking buffers and later fusion. Odin indexes the schema and projection
surface only.
@ -149,6 +153,9 @@ Verse announcement
- Device clients own sensor and media capture; Mimir owns the normalized ingest ledger; Odin owns the aggregate operator projection.
- Muninn advertises local telemetry affordances cheaply and starts capture only
after an explicit activation request.
- Muninn's live Move evidence is a CultMesh stream frame body; CultCache
Move records are receipts/debug state and must not become Mimir's hot
tracking path.
- Translation paths must name source schema, target schema, lossiness, authority, and version.
- Service presentation flows are CultMesh/Eve/CultUI interface projections. Odin aggregates those projection graphs; it does not replace them with nameplate summaries.
- Renderers lower surfaces only. If a renderer fixes network truth, the machine is split-brained.

View file

@ -13,7 +13,8 @@ microphones, cameras, and future sensors.
- Inputs: cheap local probes, operator or Verse activation requests, and local
capture tools such as FFmpeg or WASAPI helpers.
- Outputs: `muninn.telemetry_surface.v1`, active `muninn.capture_stream.v1`,
and Move optical `muninn.move_marker_candidate.v1` records.
Move receipt records, and a CultMesh bytes stream carrying live Move evidence
frames for Mimir.
- Forbidden writers: daemon startup, Idunn keepalive, Mimir ingest, OBS, Odin,
Gjallar, and renderer bodies must not start capture by implication.
@ -79,6 +80,16 @@ own raw capture, candidate extraction, calibration, triangulation, IMU fusion,
prediction, or final 6DoF pose. Muninn does not synthesize wand pose; it
reports what the local body saw and read from USB.
The hot tracking path is a CultMesh stream, not CultCache polling. When
`serve` has one or more `--move-state` sources, it declares
`muninn:<host>:move-evidence` in Verse `mimir-live` and publishes
MessagePack `mimir.muninn_move_evidence_stream_frame.v1` bytes through a
shared-memory frame ring. The frame contains any marker candidates available
from local optical extraction plus the controller states read from USB. The
`muninn.move_marker_candidate.v1` and `muninn.move_controller_state.v1` records
remain receipts/debug state in the `.cc` store; Mimir drinks the stream and
owns association, calibration, fusion, prediction, and final pose.
On Linux hosts, enable the controller-state feed by passing one or more Move
joystick sources to `serve`:
@ -92,6 +103,9 @@ muninn serve \
The published values are raw Linux joystick/HID counts. Mimir owns calibration,
axis interpretation, unit conversion, fusion, prediction, and resolved pose
publication. Hidraw remains the local output path for LED reports.
Use `--move-evidence-stream <stream-id>` or `--move-evidence-verse <verse-id>`
only when the default `muninn:<host>:move-evidence` / `mimir-live` address is
not the desired Mimir-facing stream identity.
## Move Light Commands
@ -145,3 +159,6 @@ restart actuator launches `serve --host nightwing --interval-seconds 15` with
`--move-state move-usb=/dev/input/by-id/usb-Sony_Computer_Entertainment_Motion_Controller-joystick`,
PID, and logs under
`/home/metacrat/.local/state/gamecult/muninn`.
With that Move state source attached, `serve` also publishes the
`muninn:nightwing:move-evidence` CultMesh stream frame body that Mimir's native
Move evidence reservoir consumes.

1
vendor/cultmesh-rs/Cargo.lock generated vendored
View file

@ -171,6 +171,7 @@ dependencies = [
"rmp-serde",
"serde",
"serde_bytes",
"serde_json",
"uuid",
]

View file

@ -3,6 +3,7 @@ use cultcache_rs::CultCache;
use cultcache_rs::DatabaseEntry;
use cultcache_rs::SingleFileMessagePackBackingStore;
use cultnet_rs::CultNetDocumentRegistry;
use std::collections::BTreeMap;
use std::path::Path;
pub trait CultMeshDocumentSet: Clone + Send + Sync + 'static {
@ -33,7 +34,8 @@ macro_rules! cultmesh_documents {
) -> ::anyhow::Result<()> {
$(
registry.register(
cultnet_rs::CultNetDocumentBinding::for_entry::<$entry>(
cultnet_rs::CultNetDocumentBinding::for_entry_with_schema_id::<$entry>(
$schema_version.to_string(),
$schema_version.to_string(),
),
);
@ -65,6 +67,439 @@ pub struct CultMeshNode {
documents: CultNetDocumentRegistry,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum CultMeshStreamKind {
Audio,
Video,
Tensor,
Bytes,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum CultMeshStreamBodyTransport {
SharedMemory,
SharedD3d12Texture,
SharedD3d11Texture,
DmaBuf,
IoSurface,
AHardwareBuffer,
CultCachePage,
InlineBytes,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum CultMeshStreamAccess {
Read,
Write,
ReadWrite,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum CultMeshStreamCopyBudget {
ZeroCopyTarget,
OneCopyFallback,
OpaqueRuntime,
}
#[derive(Clone, Debug, PartialEq)]
pub struct CultMeshStreamClock {
pub clock_domain_id: String,
pub source_id: Option<String>,
pub sample_rate: i32,
pub offset_to_verse_time_ns: i64,
pub confidence: f64,
pub evidence_kind: Option<String>,
}
impl CultMeshStreamClock {
pub fn new(clock_domain_id: impl Into<String>) -> Result<Self> {
let clock_domain_id = require_non_empty(clock_domain_id.into(), "clock_domain_id")?;
Ok(Self {
clock_domain_id,
source_id: None,
sample_rate: 0,
offset_to_verse_time_ns: 0,
confidence: 0.0,
evidence_kind: None,
})
}
pub fn source_id(mut self, source_id: impl Into<String>) -> Result<Self> {
self.source_id = Some(require_non_empty(source_id.into(), "source_id")?);
Ok(self)
}
pub fn confidence(mut self, confidence: f64) -> Self {
self.confidence = confidence;
self
}
pub fn evidence_kind(mut self, evidence_kind: impl Into<String>) -> Result<Self> {
self.evidence_kind = Some(require_non_empty(evidence_kind.into(), "evidence_kind")?);
Ok(self)
}
}
#[derive(Clone, Debug, PartialEq)]
pub struct CultMeshStreamDescriptor {
pub stream_id: String,
pub verse_id: String,
pub owner_peer_id: String,
pub kind: CultMeshStreamKind,
pub clock: CultMeshStreamClock,
pub preferred_transports: Vec<CultMeshStreamBodyTransport>,
pub label: Option<String>,
pub required_access: CultMeshStreamAccess,
pub max_in_flight_frames: u32,
pub metadata_schema_id: Option<String>,
}
impl CultMeshStreamDescriptor {
pub fn new(
stream_id: impl Into<String>,
verse_id: impl Into<String>,
owner_peer_id: impl Into<String>,
kind: CultMeshStreamKind,
clock: CultMeshStreamClock,
preferred_transports: Vec<CultMeshStreamBodyTransport>,
) -> Result<Self> {
if preferred_transports.is_empty() {
anyhow::bail!("preferred_transports must not be empty");
}
Ok(Self {
stream_id: require_non_empty(stream_id.into(), "stream_id")?,
verse_id: require_non_empty(verse_id.into(), "verse_id")?,
owner_peer_id: require_non_empty(owner_peer_id.into(), "owner_peer_id")?,
kind,
clock,
preferred_transports,
label: None,
required_access: CultMeshStreamAccess::Read,
max_in_flight_frames: 0,
metadata_schema_id: None,
})
}
pub fn label(mut self, label: impl Into<String>) -> Result<Self> {
self.label = Some(require_non_empty(label.into(), "label")?);
Ok(self)
}
pub fn max_in_flight_frames(mut self, max_in_flight_frames: u32) -> Self {
self.max_in_flight_frames = max_in_flight_frames;
self
}
pub fn metadata_schema_id(mut self, metadata_schema_id: impl Into<String>) -> Result<Self> {
self.metadata_schema_id = Some(require_non_empty(metadata_schema_id.into(), "metadata_schema_id")?);
Ok(self)
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct CultMeshStreamConsumerProfile {
pub peer_id: String,
pub verse_id: String,
pub supported_transports: Vec<CultMeshStreamBodyTransport>,
pub accepted_kinds: Vec<CultMeshStreamKind>,
pub max_in_flight_frames: u32,
}
impl CultMeshStreamConsumerProfile {
pub fn new(
peer_id: impl Into<String>,
verse_id: impl Into<String>,
supported_transports: Vec<CultMeshStreamBodyTransport>,
) -> Result<Self> {
if supported_transports.is_empty() {
anyhow::bail!("supported_transports must not be empty");
}
Ok(Self {
peer_id: require_non_empty(peer_id.into(), "peer_id")?,
verse_id: require_non_empty(verse_id.into(), "verse_id")?,
supported_transports,
accepted_kinds: Vec::new(),
max_in_flight_frames: 0,
})
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct CultMeshStreamNegotiation {
pub stream_id: String,
pub producer_peer_id: String,
pub consumer_peer_id: String,
pub transport: CultMeshStreamBodyTransport,
pub access: CultMeshStreamAccess,
pub max_in_flight_frames: u32,
pub copy_budget: CultMeshStreamCopyBudget,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct CultMeshStreamFrameHandle {
pub stream_id: String,
pub sequence: u64,
pub timestamp_ns: i64,
pub duration_ns: i64,
pub transport: CultMeshStreamBodyTransport,
pub byte_length: usize,
pub resource_key: Option<String>,
pub unavoidable_copy_count: u32,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct CultMeshSharedMemoryFrameRingStats {
pub stream_id: String,
pub slot_count: usize,
pub slot_byte_length: usize,
pub published_frames: u64,
pub dropped_frames: u64,
pub blocked_writes: u64,
pub latest_sequence: u64,
pub unavoidable_copy_count: u64,
}
pub struct CultMeshFrameReadLease<'a> {
pub handle: CultMeshStreamFrameHandle,
bytes: &'a [u8],
}
impl CultMeshFrameReadLease<'_> {
pub fn bytes(&self) -> &[u8] {
self.bytes
}
}
#[derive(Clone, Debug)]
pub struct CultMeshSharedMemoryFrameRing {
stream_id: String,
slot_byte_length: usize,
slots: Vec<Option<(CultMeshStreamFrameHandle, Vec<u8>)>>,
write_cursor: usize,
latest_slot: Option<usize>,
next_sequence: u64,
published_frames: u64,
dropped_frames: u64,
blocked_writes: u64,
unavoidable_copy_count: u64,
}
impl CultMeshSharedMemoryFrameRing {
pub fn new(stream_id: impl Into<String>, slot_count: usize, slot_byte_length: usize) -> Result<Self> {
let stream_id = require_non_empty(stream_id.into(), "stream_id")?;
if slot_count == 0 {
anyhow::bail!("slot_count must be greater than zero");
}
if slot_byte_length == 0 {
anyhow::bail!("slot_byte_length must be greater than zero");
}
Ok(Self {
stream_id,
slot_byte_length,
slots: vec![None; slot_count],
write_cursor: 0,
latest_slot: None,
next_sequence: 0,
published_frames: 0,
dropped_frames: 0,
blocked_writes: 0,
unavoidable_copy_count: 0,
})
}
pub fn try_publish_copy(
&mut self,
bytes: &[u8],
timestamp_ns: i64,
duration_ns: i64,
) -> Result<Option<CultMeshStreamFrameHandle>> {
if bytes.len() > self.slot_byte_length {
anyhow::bail!("frame byte length exceeds slot size");
}
if self.slots.is_empty() {
self.blocked_writes += 1;
return Ok(None);
}
let slot_index = self.write_cursor;
if self.slots[slot_index].is_some() {
self.dropped_frames += 1;
}
let handle = CultMeshStreamFrameHandle {
stream_id: self.stream_id.clone(),
sequence: self.next_sequence,
timestamp_ns,
duration_ns,
transport: CultMeshStreamBodyTransport::SharedMemory,
byte_length: bytes.len(),
resource_key: Some(format!("{}:slot:{slot_index}", self.stream_id)),
unavoidable_copy_count: 1,
};
self.slots[slot_index] = Some((handle.clone(), bytes.to_vec()));
self.latest_slot = Some(slot_index);
self.write_cursor = (slot_index + 1) % self.slots.len();
self.next_sequence = self.next_sequence.saturating_add(1);
self.published_frames = self.published_frames.saturating_add(1);
self.unavoidable_copy_count = self.unavoidable_copy_count.saturating_add(1);
Ok(Some(handle))
}
pub fn try_acquire_latest_read(&self) -> Option<CultMeshFrameReadLease<'_>> {
let slot_index = self.latest_slot?;
let (handle, bytes) = self.slots[slot_index].as_ref()?;
Some(CultMeshFrameReadLease {
handle: handle.clone(),
bytes,
})
}
pub fn stats(&self) -> CultMeshSharedMemoryFrameRingStats {
let latest_sequence = self
.latest_slot
.and_then(|slot| self.slots[slot].as_ref().map(|(handle, _)| handle.sequence))
.unwrap_or(0);
CultMeshSharedMemoryFrameRingStats {
stream_id: self.stream_id.clone(),
slot_count: self.slots.len(),
slot_byte_length: self.slot_byte_length,
published_frames: self.published_frames,
dropped_frames: self.dropped_frames,
blocked_writes: self.blocked_writes,
latest_sequence,
unavoidable_copy_count: self.unavoidable_copy_count,
}
}
}
#[derive(Clone, Debug, Default)]
pub struct CultMeshStreamCatalog {
streams: BTreeMap<String, CultMeshStreamDescriptor>,
latest_frames: BTreeMap<String, CultMeshStreamFrameHandle>,
rings: BTreeMap<String, CultMeshSharedMemoryFrameRing>,
}
impl CultMeshStreamCatalog {
pub fn declare(&mut self, stream: CultMeshStreamDescriptor) {
self.streams.insert(stream.stream_id.clone(), stream);
}
pub fn get(&self, stream_id: &str) -> Option<&CultMeshStreamDescriptor> {
self.streams.get(stream_id)
}
pub fn streams(&self) -> Vec<&CultMeshStreamDescriptor> {
self.streams.values().collect()
}
pub fn find(&self, verse_id: &str, kind: Option<CultMeshStreamKind>) -> Vec<&CultMeshStreamDescriptor> {
self.streams
.values()
.filter(|stream| stream.verse_id == verse_id && kind.is_none_or(|k| stream.kind == k))
.collect()
}
pub fn negotiate(
&self,
stream_id: &str,
consumer: &CultMeshStreamConsumerProfile,
) -> Result<CultMeshStreamNegotiation> {
let stream = self
.streams
.get(stream_id)
.ok_or_else(|| anyhow::anyhow!("unknown CultMesh stream '{stream_id}'"))?;
if stream.verse_id != consumer.verse_id {
anyhow::bail!("stream and consumer must belong to the same Verse");
}
if !consumer.accepted_kinds.is_empty() && !consumer.accepted_kinds.contains(&stream.kind) {
anyhow::bail!("consumer does not accept stream kind");
}
let transport = stream
.preferred_transports
.iter()
.copied()
.find(|candidate| consumer.supported_transports.contains(candidate))
.ok_or_else(|| anyhow::anyhow!("stream and consumer have no compatible body transport"))?;
let producer_max = if stream.max_in_flight_frames == 0 {
u32::MAX
} else {
stream.max_in_flight_frames
};
let consumer_max = if consumer.max_in_flight_frames == 0 {
u32::MAX
} else {
consumer.max_in_flight_frames
};
Ok(CultMeshStreamNegotiation {
stream_id: stream.stream_id.clone(),
producer_peer_id: stream.owner_peer_id.clone(),
consumer_peer_id: consumer.peer_id.clone(),
transport,
access: stream.required_access,
max_in_flight_frames: producer_max.min(consumer_max),
copy_budget: copy_budget_for(transport),
})
}
pub fn create_shared_memory_ring(
&mut self,
stream_id: &str,
slot_count: usize,
slot_byte_length: usize,
) -> Result<&mut CultMeshSharedMemoryFrameRing> {
if !self.streams.contains_key(stream_id) {
anyhow::bail!("unknown CultMesh stream '{stream_id}'");
}
self.rings.insert(
stream_id.to_string(),
CultMeshSharedMemoryFrameRing::new(stream_id, slot_count, slot_byte_length)?,
);
Ok(self
.rings
.get_mut(stream_id)
.expect("ring was inserted for stream"))
}
pub fn ring(&self, stream_id: &str) -> Option<&CultMeshSharedMemoryFrameRing> {
self.rings.get(stream_id)
}
pub fn ring_mut(&mut self, stream_id: &str) -> Option<&mut CultMeshSharedMemoryFrameRing> {
self.rings.get_mut(stream_id)
}
pub fn publish_frame(&mut self, handle: CultMeshStreamFrameHandle) -> Result<()> {
if !self.streams.contains_key(&handle.stream_id) {
anyhow::bail!("unknown CultMesh stream '{}'", handle.stream_id);
}
self.latest_frames.insert(handle.stream_id.clone(), handle);
Ok(())
}
pub fn latest_frame(&self, stream_id: &str) -> Option<&CultMeshStreamFrameHandle> {
self.latest_frames.get(stream_id)
}
}
fn copy_budget_for(transport: CultMeshStreamBodyTransport) -> CultMeshStreamCopyBudget {
match transport {
CultMeshStreamBodyTransport::SharedMemory
| CultMeshStreamBodyTransport::SharedD3d12Texture
| CultMeshStreamBodyTransport::SharedD3d11Texture
| CultMeshStreamBodyTransport::DmaBuf
| CultMeshStreamBodyTransport::IoSurface
| CultMeshStreamBodyTransport::AHardwareBuffer => CultMeshStreamCopyBudget::ZeroCopyTarget,
CultMeshStreamBodyTransport::CultCachePage => CultMeshStreamCopyBudget::OneCopyFallback,
CultMeshStreamBodyTransport::InlineBytes => CultMeshStreamCopyBudget::OpaqueRuntime,
}
}
fn require_non_empty(value: String, name: &str) -> Result<String> {
if value.trim().is_empty() {
anyhow::bail!("{name} must be non-empty");
}
Ok(value)
}
impl CultMeshNode {
pub fn runtime_id(&self) -> &str {
&self.runtime_id
@ -139,6 +574,10 @@ impl CultMesh {
{
Self::create_node(store_path, documents, options)
}
pub fn create_stream_catalog() -> CultMeshStreamCatalog {
CultMeshStreamCatalog::default()
}
}
pub fn create_node<D>(
@ -163,6 +602,10 @@ where
CultMesh::start_node(store_path, documents, options)
}
pub fn create_stream_catalog() -> CultMeshStreamCatalog {
CultMesh::create_stream_catalog()
}
#[cfg(test)]
mod tests {
use super::*;
@ -209,4 +652,60 @@ mod tests {
);
Ok(())
}
#[test]
fn stream_catalog_negotiates_and_publishes_latest_shared_memory_frame() -> Result<()> {
let mut catalog = CultMesh::create_stream_catalog();
let stream = CultMeshStreamDescriptor::new(
"muninn:nightwing:move-evidence",
"mimir-live",
"muninn:nightwing",
CultMeshStreamKind::Bytes,
CultMeshStreamClock::new("muninn:nightwing:clock")?
.source_id("muninn:nightwing:move-evidence")?
.confidence(1.0)
.evidence_kind("muninn-move-evidence")?,
vec![
CultMeshStreamBodyTransport::SharedMemory,
CultMeshStreamBodyTransport::CultCachePage,
],
)?
.label("Muninn Move evidence")?
.max_in_flight_frames(4)
.metadata_schema_id("mimir.muninn_move_evidence_stream_frame.v1")?;
catalog.declare(stream);
let consumer = CultMeshStreamConsumerProfile::new(
"mimir:starfire",
"mimir-live",
vec![CultMeshStreamBodyTransport::SharedMemory],
)?;
let negotiation = catalog.negotiate("muninn:nightwing:move-evidence", &consumer)?;
assert_eq!(negotiation.transport, CultMeshStreamBodyTransport::SharedMemory);
assert_eq!(negotiation.copy_budget, CultMeshStreamCopyBudget::ZeroCopyTarget);
let handle = {
let ring = catalog.create_shared_memory_ring(
"muninn:nightwing:move-evidence",
4,
128,
)?;
ring.try_publish_copy(&[1, 2, 3], 42, 0)?
.expect("frame should publish")
};
catalog.publish_frame(handle.clone())?;
assert_eq!(
catalog.latest_frame("muninn:nightwing:move-evidence"),
Some(&handle)
);
let lease = catalog
.ring("muninn:nightwing:move-evidence")
.and_then(CultMeshSharedMemoryFrameRing::try_acquire_latest_read)
.expect("latest frame should be readable");
assert_eq!(lease.handle.sequence, 0);
assert_eq!(lease.bytes(), &[1, 2, 3]);
Ok(())
}
}